use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
use axum::extract::{ConnectInfo, Request, State};
use axum::http::{HeaderMap, HeaderValue};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use seiva_ports::Clock;
use crate::problem::Problem;
use crate::request_id::RequestIdExt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RateLimit {
pub max_requests: u32,
pub window: Duration,
}
impl RateLimit {
pub const DEFAULT_MAX_REQUESTS: u32 = 300;
pub const DEFAULT_WINDOW: Duration = Duration::from_secs(60);
}
impl Default for RateLimit {
fn default() -> Self {
Self {
max_requests: Self::DEFAULT_MAX_REQUESTS,
window: Self::DEFAULT_WINDOW,
}
}
}
#[derive(Debug, Default, Clone, Copy)]
struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> SystemTime {
SystemTime::now()
}
}
#[derive(Debug, Clone, Copy)]
struct Window {
start: SystemTime,
count: u32,
}
pub const MAX_TRACKED_CLIENTS: usize = 100_000;
#[derive(Clone)]
pub struct RateLimiter {
limit: RateLimit,
clock: Arc<dyn Clock>,
windows: Arc<Mutex<HashMap<IpAddr, Window>>>,
trust_forwarded_for: bool,
}
impl RateLimiter {
#[must_use]
pub fn new(limit: RateLimit) -> Self {
Self::with_clock(limit, Arc::new(SystemClock))
}
#[must_use]
pub fn with_clock(limit: RateLimit, clock: Arc<dyn Clock>) -> Self {
Self {
limit,
clock,
windows: Arc::new(Mutex::new(HashMap::new())),
trust_forwarded_for: false,
}
}
#[must_use]
pub fn trusting_forwarded_for(mut self, trust: bool) -> Self {
self.trust_forwarded_for = trust;
self
}
fn check(&self, key: IpAddr) -> Result<(), Duration> {
let now = self.clock.now();
let mut windows = self.windows.lock().unwrap_or_else(|e| e.into_inner());
if windows.len() >= MAX_TRACKED_CLIENTS && !windows.contains_key(&key) {
windows.retain(|_, w| {
now.duration_since(w.start).unwrap_or(Duration::ZERO) < self.limit.window
});
if windows.len() >= MAX_TRACKED_CLIENTS && !windows.contains_key(&key) {
return Ok(());
}
}
let window = windows.entry(key).or_insert(Window {
start: now,
count: 0,
});
let elapsed = now.duration_since(window.start).unwrap_or(Duration::ZERO);
if elapsed >= self.limit.window {
window.start = now;
window.count = 1;
return Ok(());
}
if window.count < self.limit.max_requests {
window.count += 1;
Ok(())
} else {
Err(self.limit.window - elapsed)
}
}
}
const UNKNOWN_PEER: IpAddr = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
fn forwarded_client_ip(headers: &HeaderMap) -> Option<IpAddr> {
headers
.get("x-forwarded-for")?
.to_str()
.ok()?
.rsplit(',')
.find_map(|entry| entry.trim().parse::<IpAddr>().ok())
}
fn client_key(request: &Request, trust_forwarded_for: bool) -> IpAddr {
if trust_forwarded_for {
if let Some(ip) = forwarded_client_ip(request.headers()) {
return ip;
}
}
request
.extensions()
.get::<ConnectInfo<SocketAddr>>()
.map(|ci| ci.0.ip())
.unwrap_or(UNKNOWN_PEER)
}
pub async fn rate_limit(
State(limiter): State<RateLimiter>,
request: Request,
next: Next,
) -> Response {
let key = client_key(&request, limiter.trust_forwarded_for);
match limiter.check(key) {
Ok(()) => next.run(request).await,
Err(retry_after) => {
let request_id = request.extensions().request_id();
let seconds = retry_after.as_secs() + u64::from(retry_after.subsec_nanos() > 0);
let mut response = Problem::too_many_requests("request rate limit exceeded")
.with_instance(request.uri().path().to_owned())
.with_request_id_opt(request_id)
.into_response();
if let Ok(value) = HeaderValue::from_str(&seconds.to_string()) {
response.headers_mut().insert("retry-after", value);
}
response
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use axum::http::{Request as HttpRequest, StatusCode};
use axum::middleware::from_fn_with_state;
use axum::routing::get;
use axum::Router;
use seiva_testing::FixedClock;
use tower::ServiceExt;
fn app(limiter: RateLimiter) -> Router {
Router::new()
.route("/", get(|| async { "ok" }))
.layer(from_fn_with_state(limiter, rate_limit))
}
async fn hit(app: &Router) -> StatusCode {
app.clone()
.oneshot(HttpRequest::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap()
.status()
}
#[tokio::test]
async fn allows_up_to_the_limit_then_429s() {
let clock = Arc::new(FixedClock::at_unix_secs(0));
let limiter = RateLimiter::with_clock(
RateLimit {
max_requests: 3,
window: Duration::from_secs(60),
},
clock.clone(),
);
let app = app(limiter);
assert_eq!(hit(&app).await, StatusCode::OK);
assert_eq!(hit(&app).await, StatusCode::OK);
assert_eq!(hit(&app).await, StatusCode::OK);
assert_eq!(hit(&app).await, StatusCode::TOO_MANY_REQUESTS);
}
#[tokio::test]
async fn window_rollover_restores_budget() {
let clock = Arc::new(FixedClock::at_unix_secs(0));
let limiter = RateLimiter::with_clock(
RateLimit {
max_requests: 1,
window: Duration::from_secs(60),
},
clock.clone(),
);
let app = app(limiter);
assert_eq!(hit(&app).await, StatusCode::OK);
assert_eq!(hit(&app).await, StatusCode::TOO_MANY_REQUESTS);
clock.advance(Duration::from_secs(61));
assert_eq!(hit(&app).await, StatusCode::OK);
}
#[tokio::test]
async fn too_many_requests_carries_retry_after() {
let clock = Arc::new(FixedClock::at_unix_secs(0));
let limiter = RateLimiter::with_clock(
RateLimit {
max_requests: 1,
window: Duration::from_secs(30),
},
clock.clone(),
);
let app = app(limiter);
assert_eq!(hit(&app).await, StatusCode::OK);
let res = app
.oneshot(HttpRequest::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
let retry_after: u64 = res.headers()["retry-after"]
.to_str()
.unwrap()
.parse()
.unwrap();
assert!(retry_after > 0 && retry_after <= 30);
}
#[test]
fn forwarded_client_ip_takes_the_rightmost_parseable_entry() {
let mut headers = HeaderMap::new();
headers.insert(
"x-forwarded-for",
HeaderValue::from_static("9.9.9.9, 203.0.113.7"),
);
assert_eq!(
forwarded_client_ip(&headers),
Some("203.0.113.7".parse().unwrap())
);
assert_eq!(forwarded_client_ip(&HeaderMap::new()), None);
}
#[test]
fn trusted_forwarded_for_keys_each_client_independently() {
let clock = Arc::new(FixedClock::at_unix_secs(0));
let limiter = RateLimiter::with_clock(
RateLimit {
max_requests: 1,
window: Duration::from_secs(60),
},
clock.clone(),
)
.trusting_forwarded_for(true);
let a: IpAddr = "203.0.113.1".parse().unwrap();
let b: IpAddr = "203.0.113.2".parse().unwrap();
assert!(limiter.check(a).is_ok());
assert!(limiter.check(a).is_err());
assert!(limiter.check(b).is_ok());
}
#[test]
fn the_client_table_is_bounded_under_a_flood_of_distinct_keys() {
let clock = Arc::new(FixedClock::at_unix_secs(0));
let limiter = RateLimiter::with_clock(RateLimit::default(), clock.clone());
for i in 0..(MAX_TRACKED_CLIENTS as u64 + 5_000) {
let octets = (i >> 24) as u8;
let ip = IpAddr::from([octets, (i >> 16) as u8, (i >> 8) as u8, i as u8]);
let _ = limiter.check(ip);
}
let tracked = limiter.windows.lock().unwrap().len();
assert!(
tracked <= MAX_TRACKED_CLIENTS,
"table must stay bounded, got {tracked}"
);
}
}