use crate::domain::services::rate_limiting_service::RateLimitingService;
use crate::infrastructure::security::secure_ip::{get_secure_client_ip, TrustedProxyConfig};
use axum::{body::Body, extract::Request, http::StatusCode, middleware::Next, response::Response};
use limiteron::sync::SyncFixedWindowLimiter;
use log::{debug, warn};
use std::sync::Arc;
use std::time::Duration;
const DEFAULT_IP_RATE_LIMIT: u64 = 10;
const IP_RATE_LIMIT_WINDOW_SECS: u64 = 60;
pub(crate) static RATE_LIMIT_FAIL_OPEN: once_cell::sync::Lazy<bool> =
once_cell::sync::Lazy::new(|| {
std::env::var("RATE_LIMIT_FAIL_OPEN")
.map(|v| v.eq_ignore_ascii_case("true") || v == "1")
.unwrap_or(false)
});
#[derive(Clone)]
pub struct RateLimiter {
inner: Arc<SyncFixedWindowLimiter>,
limit: u64,
}
impl RateLimiter {
pub fn new(limit: u64) -> Self {
Self::with_window(limit, 60)
}
pub fn new_for_ip_limit(limit: u64) -> Self {
Self::with_window(limit, IP_RATE_LIMIT_WINDOW_SECS)
}
fn with_window(limit: u64, window_seconds: u64) -> Self {
Self {
inner: Arc::new(SyncFixedWindowLimiter::new(
limit.max(1),
Duration::from_secs(window_seconds.max(1)),
)),
limit,
}
}
pub fn check_rate_limit(&self, key: &str) -> bool {
self.inner.check(key).is_ok()
}
pub fn get_status(&self, key: &str) -> (u64, u64) {
self.inner.peek(key).unwrap_or((0, self.limit))
}
pub fn cleanup_expired(&self) {}
}
#[derive(Clone)]
pub struct RateLimitMiddleware {
#[allow(dead_code)]
rate_limiting_service: Arc<dyn RateLimitingService>,
}
impl RateLimitMiddleware {
pub fn new(rate_limiting_service: Arc<dyn RateLimitingService>) -> Self {
Self {
rate_limiting_service,
}
}
}
fn get_client_ip(req: &Request, trusted: &TrustedProxyConfig) -> String {
get_secure_client_ip(req, trusted)
}
fn apply_ip_rate_limit_for(
limiter: &RateLimiter,
client_ip: &str,
limit: u64,
category: &str,
) -> Result<(), Box<Response>> {
if !limiter.check_rate_limit(client_ip) {
let (current, _) = limiter.get_status(client_ip);
warn!(
"IP rate limit exceeded ({}) for {}: {}/{} requests in {} seconds",
category, client_ip, current, limit, IP_RATE_LIMIT_WINDOW_SECS
);
let body = serde_json::json!({
"error": "Rate limit exceeded",
"message": format!(
"Requests from this IP are limited to {} per minute ({}).",
limit, category
),
"retry_after_seconds": IP_RATE_LIMIT_WINDOW_SECS
});
let json_body = serde_json::to_string(&body).unwrap_or_else(|_| {
r#"{"error":"Rate limit exceeded","message":"Too many requests"}"#.to_string()
});
let mut response = Response::new(Body::from(json_body));
*response.status_mut() = StatusCode::TOO_MANY_REQUESTS;
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("application/json"),
);
response.headers_mut().insert(
"Retry-After",
axum::http::HeaderValue::from(IP_RATE_LIMIT_WINDOW_SECS),
);
return Err(Box::new(response));
}
debug!(
"IP rate limit check passed for {} ({})",
client_ip, category
);
Ok(())
}
#[derive(Clone)]
pub struct RateLimitRuntimeConfig {
pub enabled: bool,
pub anon_limit: u64,
pub auth_limit: u64,
pub anon_limiter: Arc<RateLimiter>,
pub auth_limiter: Arc<RateLimiter>,
pub trusted_proxies: TrustedProxyConfig,
pub cors_allowed_origins: Vec<String>,
}
impl Default for RateLimitRuntimeConfig {
fn default() -> Self {
let anon_limit = DEFAULT_IP_RATE_LIMIT;
let auth_limit = DEFAULT_AUTH_IP_RATE_LIMIT;
Self {
enabled: true,
anon_limit,
auth_limit,
anon_limiter: Arc::new(RateLimiter::new_for_ip_limit(anon_limit)),
auth_limiter: Arc::new(RateLimiter::new_for_ip_limit(auth_limit)),
trusted_proxies: TrustedProxyConfig::default(),
cors_allowed_origins: vec!["*".to_string()],
}
}
}
impl RateLimitRuntimeConfig {
pub fn from_settings(settings: &crate::config::settings::Settings) -> Self {
let anon_limit = settings.rate_limiting.anon_ip_rpm.max(1) as u64;
let auth_limit = settings.rate_limiting.auth_ip_rpm.max(1) as u64;
Self {
enabled: settings.rate_limiting.enabled,
anon_limit,
auth_limit,
anon_limiter: Arc::new(RateLimiter::new_for_ip_limit(anon_limit)),
auth_limiter: Arc::new(RateLimiter::new_for_ip_limit(auth_limit)),
trusted_proxies: TrustedProxyConfig::from_settings(
settings.trusted_proxies.enabled,
settings.trusted_proxies.proxies.clone(),
),
cors_allowed_origins: settings.cors.allowed_origins_list(),
}
}
}
const DEFAULT_AUTH_IP_RATE_LIMIT: u64 = 600;
fn has_bearer_credentials(req: &Request) -> bool {
req.headers()
.get(axum::http::header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
.map(|token| !token.trim().is_empty())
.unwrap_or(false)
}
fn is_rate_limit_exempt(path: &str) -> bool {
crate::presentation::middleware::is_public_endpoint(path)
}
pub async fn rate_limit_middleware(
req: Request,
next: Next,
config: &RateLimitRuntimeConfig,
) -> Response {
let path = req.uri().path();
if req.method() == axum::http::Method::OPTIONS {
return next.run(req).await;
}
if !config.enabled {
debug!("Rate limiting disabled by [rate_limiting].enabled=false");
return next.run(req).await;
}
if is_rate_limit_exempt(path) {
debug!("Public endpoint {}, skipping rate limit", path);
return next.run(req).await;
}
let client_ip = get_client_ip(&req, &config.trusted_proxies);
let result = if has_bearer_credentials(&req) {
apply_ip_rate_limit_for(
&config.auth_limiter,
&client_ip,
config.auth_limit,
"bearer-credentials",
)
} else {
apply_ip_rate_limit_for(
&config.anon_limiter,
&client_ip,
config.anon_limit,
"anonymous",
)
};
match result {
Ok(()) => next.run(req).await,
Err(mut response) => {
apply_429_cors_headers(&mut response, &req, &config.cors_allowed_origins);
*response
}
}
}
fn apply_429_cors_headers(response: &mut Response, req: &Request, allowed_origins: &[String]) {
use axum::http::header::{
HeaderValue, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, ORIGIN, VARY,
};
response.headers_mut().insert(
ACCESS_CONTROL_EXPOSE_HEADERS,
HeaderValue::from_static("Retry-After"),
);
let wildcard = allowed_origins.is_empty() || allowed_origins.iter().any(|o| o == "*");
if wildcard {
response
.headers_mut()
.insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
return;
}
response
.headers_mut()
.insert(VARY, HeaderValue::from_static("Origin"));
let Some(origin) = req.headers().get(ORIGIN).and_then(|v| v.to_str().ok()) else {
return;
};
if allowed_origins.iter().any(|allowed| allowed == origin) {
if let Ok(value) = HeaderValue::from_str(origin) {
response
.headers_mut()
.insert(ACCESS_CONTROL_ALLOW_ORIGIN, value);
}
}
}
pub async fn rate_limit_layer(
axum::extract::State(config): axum::extract::State<Arc<RateLimitRuntimeConfig>>,
req: Request,
next: Next,
) -> Response {
rate_limit_middleware(req, next, &config).await
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::header;
#[test]
fn test_rate_limiter_allows_under_limit() {
let limiter = RateLimiter::new_for_ip_limit(5);
let key = "test-ip";
for _ in 0..5 {
assert!(limiter.check_rate_limit(key));
}
}
#[test]
fn test_rate_limiter_blocks_over_limit() {
let limiter = RateLimiter::new_for_ip_limit(3);
let key = "test-ip-2";
assert!(limiter.check_rate_limit(key));
assert!(limiter.check_rate_limit(key));
assert!(limiter.check_rate_limit(key));
assert!(!limiter.check_rate_limit(key));
}
#[test]
fn test_get_client_ip_from_forwarded() {
let req = Request::builder()
.header("X-Forwarded-For", "192.168.1.1, 10.0.0.1")
.body(Body::empty())
.unwrap();
let ip = get_client_ip(&req, &TrustedProxyConfig::default());
assert_eq!(ip, "unknown");
}
#[test]
fn test_get_client_ip_from_real_ip() {
let req = Request::builder()
.header("X-Real-IP", "192.168.1.2")
.body(Body::empty())
.unwrap();
let ip = get_client_ip(&req, &TrustedProxyConfig::default());
assert_eq!(ip, "unknown");
}
#[test]
fn test_get_client_ip_unknown() {
let req = Request::builder().body(Body::empty()).unwrap();
let ip = get_client_ip(&req, &TrustedProxyConfig::default());
assert_eq!(ip, "unknown");
}
#[test]
fn test_get_client_ip_with_trusted_proxy() {
use axum::extract::ConnectInfo;
use std::net::SocketAddr;
let socket_addr: SocketAddr = "10.0.0.1:8080".parse().unwrap();
let mut req = Request::builder()
.header("X-Forwarded-For", "203.0.113.1, 10.0.0.1")
.body(Body::empty())
.unwrap();
req.extensions_mut().insert(ConnectInfo(socket_addr));
let ip = get_client_ip(&req, &TrustedProxyConfig::default());
assert_eq!(ip, "203.0.113.1");
}
#[test]
fn test_get_client_ip_untrusted_proxy_rejected() {
use axum::extract::ConnectInfo;
use std::net::SocketAddr;
let socket_addr: SocketAddr = "8.8.8.8:8080".parse().unwrap();
let mut req = Request::builder()
.header("X-Forwarded-For", "203.0.113.1, 8.8.8.8")
.body(Body::empty())
.unwrap();
req.extensions_mut().insert(ConnectInfo(socket_addr));
let ip = get_client_ip(&req, &TrustedProxyConfig::default());
assert_eq!(ip, "8.8.8.8");
}
#[test]
fn test_rate_limiter_new() {
let limiter = RateLimiter::new(100);
let (count, remaining) = limiter.get_status("fresh-key-new");
assert_eq!(count, 0);
assert_eq!(remaining, 100);
}
#[test]
fn test_get_status_no_record() {
let limiter = RateLimiter::new_for_ip_limit(10);
let (count, remaining) = limiter.get_status("nonexistent-key");
assert_eq!(count, 0);
assert_eq!(remaining, 10);
}
#[test]
fn test_get_status_with_count() {
let limiter = RateLimiter::new_for_ip_limit(10);
let key = "status-key-1";
limiter.check_rate_limit(key);
limiter.check_rate_limit(key);
limiter.check_rate_limit(key);
let (count, remaining) = limiter.get_status(key);
assert_eq!(count, 3);
assert_eq!(remaining, 7);
}
#[test]
fn test_get_status_at_limit() {
let limiter = RateLimiter::new_for_ip_limit(3);
let key = "status-key-2";
for _ in 0..3 {
limiter.check_rate_limit(key);
}
let (count, remaining) = limiter.get_status(key);
assert_eq!(count, 3);
assert_eq!(remaining, 0);
}
#[test]
fn test_get_status_count_exceeds_limit_saturating() {
let limiter = RateLimiter::new_for_ip_limit(1);
let key = "status-key-3";
limiter.check_rate_limit(key); limiter.check_rate_limit(key); let (count, _remaining) = limiter.get_status(key);
assert_eq!(count, 1);
}
#[test]
fn test_cleanup_expired_keeps_recent_entries() {
let limiter = RateLimiter::new_for_ip_limit(10);
let key = "cleanup-recent";
limiter.check_rate_limit(key);
limiter.cleanup_expired();
let (count, _) = limiter.get_status(key);
assert_eq!(count, 1);
}
#[test]
fn test_cleanup_expired_empty_map() {
let limiter = RateLimiter::new_for_ip_limit(10);
limiter.cleanup_expired();
}
#[test]
fn test_rate_limiter_different_keys_independent() {
let limiter = RateLimiter::new_for_ip_limit(2);
assert!(limiter.check_rate_limit("key-a"));
assert!(limiter.check_rate_limit("key-b"));
assert!(limiter.check_rate_limit("key-a"));
assert!(!limiter.check_rate_limit("key-a"));
assert!(limiter.check_rate_limit("key-b"));
}
#[test]
fn test_rate_limiter_window_reset_logic() {
let limiter = RateLimiter::new_for_ip_limit(2);
let key = "reset-key";
assert!(limiter.check_rate_limit(key));
assert!(limiter.check_rate_limit(key));
assert!(!limiter.check_rate_limit(key));
let (count, remaining) = limiter.get_status(key);
assert_eq!(count, 2);
assert_eq!(remaining, 0);
}
#[test]
fn test_apply_ip_rate_limit_allows() {
let limiter = RateLimiter::new_for_ip_limit(DEFAULT_IP_RATE_LIMIT);
let result =
apply_ip_rate_limit_for(&limiter, "198.51.100.1", DEFAULT_IP_RATE_LIMIT, "anonymous");
assert!(result.is_ok());
}
#[test]
fn test_apply_ip_rate_limit_blocks_after_exceeding() {
let limiter = RateLimiter::new_for_ip_limit(DEFAULT_IP_RATE_LIMIT);
let unique_ip = "198.51.100.2";
for _ in 0..10 {
assert!(
apply_ip_rate_limit_for(&limiter, unique_ip, DEFAULT_IP_RATE_LIMIT, "anonymous")
.is_ok(),
"First 10 requests should be allowed"
);
}
let result =
apply_ip_rate_limit_for(&limiter, unique_ip, DEFAULT_IP_RATE_LIMIT, "anonymous");
assert!(result.is_err(), "11th request should be blocked");
let response = *result.unwrap_err();
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
assert!(response.headers().contains_key("Retry-After"));
assert_eq!(
response.headers().get(header::CONTENT_TYPE).unwrap(),
"application/json"
);
}
async fn test_middleware_wrapper(
axum::extract::State(state): axum::extract::State<Arc<RateLimitRuntimeConfig>>,
req: Request,
next: Next,
) -> Response {
rate_limit_middleware(req, next, &state).await
}
#[test]
fn test_is_rate_limit_exempt_paths() {
assert!(is_rate_limit_exempt("/health"));
assert!(is_rate_limit_exempt("/health/live"));
assert!(is_rate_limit_exempt("/health/ready"));
assert!(is_rate_limit_exempt("/ready"));
assert!(is_rate_limit_exempt("/v1/version"));
assert!(is_rate_limit_exempt("/metrics"));
assert!(!is_rate_limit_exempt("/v1/scrape"));
}
#[tokio::test]
async fn test_middleware_health_live_skips_rate_limit() {
use axum::routing::get;
use tower::ServiceExt;
let state = Arc::new(RateLimitRuntimeConfig::default());
let app = axum::Router::new()
.route("/health/live", get(|| async { "OK" }))
.layer(axum::middleware::from_fn_with_state(
state,
test_middleware_wrapper,
));
let response = app
.oneshot(
Request::builder()
.uri("/health/live")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_middleware_public_endpoint_skips_rate_limit() {
use axum::routing::get;
use tower::ServiceExt;
let state = Arc::new(RateLimitRuntimeConfig::default());
let app = axum::Router::new()
.route("/health", get(|| async { "OK" }))
.layer(axum::middleware::from_fn_with_state(
state,
test_middleware_wrapper,
));
let response = app
.oneshot(
Request::builder()
.uri("/health")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_middleware_metrics_endpoint_skips_rate_limit() {
use axum::routing::get;
use tower::ServiceExt;
let state = Arc::new(RateLimitRuntimeConfig::default());
let app = axum::Router::new()
.route("/metrics", get(|| async { "metrics" }))
.layer(axum::middleware::from_fn_with_state(
state,
test_middleware_wrapper,
));
let response = app
.oneshot(
Request::builder()
.uri("/metrics")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn test_middleware_no_bearer_token_ip_limit_passes() {
use axum::routing::get;
use tower::ServiceExt;
let state = Arc::new(RateLimitRuntimeConfig::default());
let app = axum::Router::new()
.route("/v1/test", get(|| async { "OK" }))
.layer(axum::middleware::from_fn_with_state(
state,
test_middleware_wrapper,
));
let response = app
.oneshot(
Request::builder()
.uri("/v1/test")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[test]
fn test_429_cors_wildcard_and_allowlist() {
let req = Request::builder()
.uri("/v1/tasks")
.header("origin", "https://app.example")
.body(Body::empty())
.unwrap();
let mut response = Response::new(Body::from("{}"));
apply_429_cors_headers(&mut response, &req, &["*".to_string()]);
assert_eq!(
response
.headers()
.get("access-control-allow-origin")
.unwrap(),
"*"
);
assert_eq!(
response
.headers()
.get("access-control-expose-headers")
.unwrap(),
"Retry-After"
);
let mut response = Response::new(Body::from("{}"));
apply_429_cors_headers(&mut response, &req, &["https://app.example".to_string()]);
assert_eq!(
response
.headers()
.get("access-control-allow-origin")
.unwrap(),
"https://app.example"
);
assert_eq!(response.headers().get("vary").unwrap(), "Origin");
let mut response = Response::new(Body::from("{}"));
apply_429_cors_headers(&mut response, &req, &["https://other.example".to_string()]);
assert!(response
.headers()
.get("access-control-allow-origin")
.is_none());
}
}