use crate::context::Context;
use crate::error::Result;
use crate::http::Response;
use crate::middleware::{InboundAction, InboundMiddleware, OutboundMiddleware};
use async_trait::async_trait;
use dashmap::DashMap;
use serde_json::json;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Clone)]
struct RateLimitEntry {
count: u32,
window_start: u64,
}
#[derive(Clone)]
pub struct RateLimitMiddleware {
max_requests: u32,
window_seconds: u64,
storage: Arc<DashMap<String, RateLimitEntry>>,
excluded_paths: Vec<String>,
trust_proxy: bool,
}
impl RateLimitMiddleware {
pub fn new(max_requests: u32, window_seconds: u64) -> Self {
Self {
max_requests,
window_seconds,
storage: Arc::new(DashMap::new()),
excluded_paths: vec![
"/health".to_string(),
"/metrics".to_string(),
"/favicon.ico".to_string(),
],
trust_proxy: false,
}
}
pub fn default() -> Self {
Self::new(100, 60)
}
pub fn api() -> Self {
Self::new(60, 60)
}
pub fn auth() -> Self {
Self::new(5, 60)
}
pub fn exclude_paths(mut self, paths: Vec<&str>) -> Self {
self.excluded_paths = paths.into_iter().map(|s| s.to_string()).collect();
self
}
pub fn trust_proxy(mut self, trust: bool) -> Self {
self.trust_proxy = trust;
self
}
pub fn from_config() -> Self {
use crate::configuration::CONF;
let max_requests = CONF::get("middleware.rate_limit.max_requests").unwrap_or(100);
let window_seconds = CONF::get("middleware.rate_limit.window_seconds").unwrap_or(60);
let mut middleware = Self::new(max_requests, window_seconds);
if let Some(excluded) = CONF::get::<Vec<String>>("middleware.rate_limit.excluded_paths") {
middleware.excluded_paths = excluded;
}
if let Some(trust) = CONF::get("middleware.rate_limit.trust_proxy") {
middleware.trust_proxy = trust;
}
middleware
}
fn get_client_id(&self, ctx: &Context) -> String {
if self.trust_proxy {
ctx.req
.headers
.get("x-forwarded-for")
.and_then(|h| h.split(',').next())
.map(|s| s.trim().to_string())
.or_else(|| ctx.req.headers.get("x-real-ip").cloned())
.unwrap_or_else(|| ctx.ip())
} else {
ctx.ip()
}
}
fn is_excluded(&self, path: &str) -> bool {
self.excluded_paths.iter().any(|excluded| {
path == excluded
|| (path.starts_with(excluded)
&& path
.as_bytes()
.get(excluded.len())
.map(|b| *b == b'/')
.unwrap_or(false))
})
}
fn cleanup_old_entries(&self) {
let current_time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let cutoff = current_time.saturating_sub(self.window_seconds.saturating_mul(2));
self.storage.retain(|_, entry| entry.window_start > cutoff);
}
}
#[async_trait]
impl InboundMiddleware for RateLimitMiddleware {
async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
if self.is_excluded(ctx.req.path()) {
return Ok(InboundAction::Continue);
}
let client_id = self.get_client_id(ctx);
let current_time = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
if rand::random::<f32>() < 0.01 {
self.cleanup_old_entries();
}
let mut entry = self
.storage
.entry(client_id.clone())
.or_insert_with(|| RateLimitEntry {
count: 0,
window_start: current_time,
});
let elapsed = current_time.saturating_sub(entry.window_start);
if elapsed >= self.window_seconds {
entry.count = 0;
entry.window_start = current_time;
}
entry.count += 1;
if entry.count > self.max_requests {
log::warn!(
"Rate limit exceeded for client: {} ({}/{})",
client_id,
entry.count,
self.max_requests
);
let retry_after = self.window_seconds.saturating_sub(elapsed);
ctx.set_response(Response::new(hyper::StatusCode::TOO_MANY_REQUESTS)
.with_header("Content-Type", "application/json")
.with_header("Retry-After", &retry_after.to_string())
.with_header("X-RateLimit-Limit", &self.max_requests.to_string())
.with_header("X-RateLimit-Remaining", "0")
.with_header("X-RateLimit-Reset", &(entry.window_start + self.window_seconds).to_string())
.with_body(json!({
"error": "rate_limit_exceeded",
"message": format!("Rate limit exceeded. Maximum {} requests per {} seconds",
self.max_requests, self.window_seconds),
"retry_after": retry_after
}).to_string().into_bytes()));
return Ok(InboundAction::Stop);
}
let remaining = self.max_requests - entry.count;
let _ = ctx.set("rate_limit_limit", self.max_requests);
let _ = ctx.set("rate_limit_remaining", remaining);
let _ = ctx.set("rate_limit_reset", entry.window_start + self.window_seconds);
Ok(InboundAction::Continue)
}
fn name(&self) -> &'static str {
"rate_limit"
}
fn priority(&self) -> i32 {
-900 }
}
#[async_trait]
impl OutboundMiddleware for RateLimitMiddleware {
async fn process_response(&self, ctx: &mut Context) -> Result<()> {
let Some(&limit) = ctx.get::<u32>("rate_limit_limit") else {
return Ok(());
};
let Some(&remaining) = ctx.get::<u32>("rate_limit_remaining") else {
return Ok(());
};
let Some(&reset) = ctx.get::<u64>("rate_limit_reset") else {
return Ok(());
};
let Some(response) = ctx.res.as_mut() else {
return Ok(());
};
response
.headers
.push(("X-RateLimit-Limit".to_string(), limit.to_string()));
response
.headers
.push(("X-RateLimit-Remaining".to_string(), remaining.to_string()));
response
.headers
.push(("X-RateLimit-Reset".to_string(), reset.to_string()));
Ok(())
}
fn priority(&self) -> i32 {
-900
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::Request;
use crate::views::ViewEngine;
use std::sync::Arc;
#[test]
fn test_rate_limit_creation() {
let limiter = RateLimitMiddleware::default();
assert_eq!(limiter.max_requests, 100);
assert_eq!(limiter.window_seconds, 60);
assert!(!limiter.trust_proxy);
let api_limiter = RateLimitMiddleware::api();
assert_eq!(api_limiter.max_requests, 60);
let auth_limiter = RateLimitMiddleware::auth();
assert_eq!(auth_limiter.max_requests, 5);
}
#[test]
fn test_excluded_paths() {
let limiter = RateLimitMiddleware::default().exclude_paths(vec!["/public", "/static"]);
assert!(limiter.is_excluded("/public/file.js"));
assert!(limiter.is_excluded("/static/image.png"));
assert!(limiter.is_excluded("/public"));
assert!(!limiter.is_excluded("/publicity"));
assert!(!limiter.is_excluded("/api/users"));
}
#[tokio::test]
async fn client_id_ignores_proxy_headers_by_default() {
let limiter = RateLimitMiddleware::default();
let mut request = Request::default();
request
.headers
.insert("x-forwarded-for".to_string(), "203.0.113.10".to_string());
request
.headers
.insert("x-real-ip".to_string(), "198.51.100.7".to_string());
let views = Arc::new(ViewEngine::from_directory("views"));
let ctx = Context::new(request, views);
assert_eq!(limiter.get_client_id(&ctx), ctx.ip());
}
#[tokio::test]
async fn client_id_uses_proxy_headers_only_when_enabled() {
let limiter = RateLimitMiddleware::default().trust_proxy(true);
let mut request = Request::default();
request.headers.insert(
"x-forwarded-for".to_string(),
"203.0.113.10, 198.51.100.7".to_string(),
);
let views = Arc::new(ViewEngine::from_directory("views"));
let ctx = Context::new(request, views);
assert_eq!(limiter.get_client_id(&ctx), "203.0.113.10");
}
}