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_identity::Principal;
use seiva_ports::Clock;
use crate::problem::{Problem, ProblemResponse};
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, PartialEq, Eq, Hash)]
enum ClientKey {
Tenant { tenant: String, ip: IpAddr },
Ip(IpAddr),
}
impl From<IpAddr> for ClientKey {
fn from(ip: IpAddr) -> Self {
ClientKey::Ip(ip)
}
}
impl std::fmt::Display for ClientKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ClientKey::Tenant { tenant, ip } => write!(f, "t:{tenant}:{ip}"),
ClientKey::Ip(ip) => write!(f, "ip:{ip}"),
}
}
}
#[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<ClientKey, 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: ClientKey) -> 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) {
if let Some(oldest) = windows
.iter()
.min_by_key(|(_, w)| w.start)
.map(|(k, _)| k.clone())
{
windows.remove(&oldest);
}
}
}
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 is_rate_limit_exempt(path: &str) -> bool {
path == "/health/live" || path == "/health/ready"
}
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) -> ClientKey {
let ip = if trust_forwarded_for {
forwarded_client_ip(request.headers())
} else {
None
}
.or_else(|| {
request
.extensions()
.get::<ConnectInfo<SocketAddr>>()
.map(|ci| ci.0.ip())
})
.unwrap_or(UNKNOWN_PEER);
match request
.extensions()
.get::<Arc<Principal>>()
.and_then(|p| p.tenant.clone())
{
Some(tenant) => ClientKey::Tenant { tenant, ip },
None => ClientKey::Ip(ip),
}
}
pub async fn rate_limit(
State(limiter): State<RateLimiter>,
request: Request,
next: Next,
) -> Response {
if is_rate_limit_exempt(request.uri().path()) {
return next.run(request).await;
}
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();
rate_limited_response(retry_after, request.uri().path(), request_id)
}
}
}
fn rate_limited_response(
retry_after: Duration,
path: &str,
request_id: Option<String>,
) -> Response {
let seconds = retry_after.as_secs() + u64::from(retry_after.subsec_nanos() > 0);
let mut response = ProblemResponse(
Problem::too_many_requests("request rate limit exceeded")
.with_instance(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
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum StoreErrorPolicy {
#[default]
FailOpen,
FailClosed,
}
#[derive(Clone)]
pub struct DistributedRateLimit {
store: std::sync::Arc<dyn seiva_ports::RateLimitStore>,
limit: RateLimit,
trust_forwarded_for: bool,
on_store_error: StoreErrorPolicy,
}
impl DistributedRateLimit {
#[must_use]
pub fn new(store: std::sync::Arc<dyn seiva_ports::RateLimitStore>, limit: RateLimit) -> Self {
Self {
store,
limit,
trust_forwarded_for: false,
on_store_error: StoreErrorPolicy::default(),
}
}
#[must_use]
pub fn trusting_forwarded_for(mut self, trust: bool) -> Self {
self.trust_forwarded_for = trust;
self
}
#[must_use]
pub fn on_store_error(mut self, policy: StoreErrorPolicy) -> Self {
self.on_store_error = policy;
self
}
}
pub async fn rate_limit_with_store(
State(cfg): State<DistributedRateLimit>,
request: Request,
next: Next,
) -> Response {
if is_rate_limit_exempt(request.uri().path()) {
return next.run(request).await;
}
let key = client_key(&request, cfg.trust_forwarded_for).to_string();
match cfg
.store
.check(&key, cfg.limit.max_requests, cfg.limit.window)
.await
{
Ok(seiva_ports::RateLimitDecision::Permitted) => next.run(request).await,
Ok(seiva_ports::RateLimitDecision::Limited { retry_after }) => {
let request_id = request.extensions().request_id();
rate_limited_response(retry_after, request.uri().path(), request_id)
}
Err(error) => match cfg.on_store_error {
StoreErrorPolicy::FailOpen => {
tracing::error!(
target: "seiva::rate_limit", %error, policy = "fail_open",
"rate-limit store unavailable; serving UNTHROTTLED across all replicas",
);
next.run(request).await
}
StoreErrorPolicy::FailClosed => {
tracing::error!(
target: "seiva::rate_limit", %error, policy = "fail_closed",
"rate-limit store unavailable; shedding load (503)",
);
let request_id = request.extensions().request_id();
store_unavailable_response(request.uri().path(), request_id)
}
},
Ok(other) => match cfg.on_store_error {
StoreErrorPolicy::FailOpen => {
tracing::warn!(target: "seiva::rate_limit", ?other, "unhandled rate-limit decision; serving");
next.run(request).await
}
StoreErrorPolicy::FailClosed => {
tracing::warn!(target: "seiva::rate_limit", ?other, "unhandled rate-limit decision; shedding (503)");
let request_id = request.extensions().request_id();
store_unavailable_response(request.uri().path(), request_id)
}
},
}
}
fn store_unavailable_response(path: &str, request_id: Option<String>) -> Response {
let mut response = ProblemResponse(
Problem::new(
axum::http::StatusCode::SERVICE_UNAVAILABLE,
"rate limiter unavailable",
)
.with_detail("the shared rate-limit store is unavailable; retry shortly")
.with_instance(path.to_owned())
.with_request_id_opt(request_id),
)
.into_response();
response
.headers_mut()
.insert("retry-after", HeaderValue::from_static("1"));
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 store_backed_limiter_permits_up_to_the_limit_then_429s_and_exempts_health() {
use seiva_testing::InMemoryRateLimitStore;
let store = std::sync::Arc::new(InMemoryRateLimitStore::new());
let cfg = DistributedRateLimit::new(
store,
RateLimit {
max_requests: 2,
window: Duration::from_secs(60),
},
);
let app = Router::new()
.route("/", get(|| async { "ok" }))
.route("/health/ready", get(|| async { "ready" }))
.layer(from_fn_with_state(cfg, rate_limit_with_store));
let hit = |path: &'static str| {
let app = app.clone();
async move {
app.oneshot(
HttpRequest::builder()
.uri(path)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
.status()
}
};
assert_eq!(hit("/").await, StatusCode::OK);
assert_eq!(hit("/").await, StatusCode::OK);
assert_eq!(hit("/").await, StatusCode::TOO_MANY_REQUESTS);
assert_eq!(hit("/health/ready").await, StatusCode::OK);
assert_eq!(hit("/health/ready").await, StatusCode::OK);
}
#[tokio::test]
async fn health_probes_are_exempt_from_the_limit() {
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 = Router::new()
.route("/", get(|| async { "ok" }))
.route("/health/live", get(|| async { "live" }))
.route("/health/ready", get(|| async { "ready" }))
.layer(from_fn_with_state(limiter, rate_limit));
let probe = |path: &'static str| {
let app = app.clone();
async move {
app.oneshot(
HttpRequest::builder()
.uri(path)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
.status()
}
};
for _ in 0..5 {
assert_eq!(probe("/health/live").await, StatusCode::OK);
assert_eq!(probe("/health/ready").await, StatusCode::OK);
}
assert_eq!(probe("/").await, StatusCode::OK);
assert_eq!(probe("/").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.into()).is_ok());
assert!(limiter.check(a.into()).is_err());
assert!(limiter.check(b.into()).is_ok());
}
#[test]
fn tenants_sharing_an_ip_get_independent_budgets() {
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 ip: IpAddr = "203.0.113.9".parse().unwrap();
let acme = ClientKey::Tenant {
tenant: "acme".to_owned(),
ip,
};
let globex = ClientKey::Tenant {
tenant: "globex".to_owned(),
ip,
};
assert!(limiter.check(acme.clone()).is_ok());
assert!(limiter.check(acme).is_err());
assert!(limiter.check(globex).is_ok());
}
#[test]
fn a_saturated_table_evicts_the_oldest_rather_than_failing_open() {
let clock = Arc::new(FixedClock::at_unix_secs(0));
let limiter = RateLimiter::with_clock(
RateLimit {
max_requests: 1,
window: Duration::from_secs(3600),
},
clock.clone(),
);
for i in 0..(MAX_TRACKED_CLIENTS as u64) {
let ip = IpAddr::from([(i >> 24) as u8, (i >> 16) as u8, (i >> 8) as u8, i as u8]);
assert!(limiter.check(ip.into()).is_ok());
}
let fresh: IpAddr = "198.51.100.1".parse().unwrap();
assert!(limiter.check(fresh.into()).is_ok());
assert!(limiter.check(fresh.into()).is_err());
assert!(limiter.windows.lock().unwrap().len() <= MAX_TRACKED_CLIENTS);
}
#[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.into());
}
let tracked = limiter.windows.lock().unwrap().len();
assert!(
tracked <= MAX_TRACKED_CLIENTS,
"table must stay bounded, got {tracked}"
);
}
struct FailingStore;
#[async_trait::async_trait]
impl seiva_ports::RateLimitStore for FailingStore {
async fn check(
&self,
_key: &str,
_limit: u32,
_window: Duration,
) -> seiva_ports::PortResult<seiva_ports::RateLimitDecision> {
Err("rate-limit store unreachable".into())
}
}
fn store_app(cfg: DistributedRateLimit) -> Router {
Router::new()
.route("/", get(|| async { "ok" }))
.layer(from_fn_with_state(cfg, rate_limit_with_store))
}
async fn status_of(app: &Router) -> Response {
app.clone()
.oneshot(HttpRequest::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap()
}
#[tokio::test]
async fn store_error_fails_open_by_default() {
let cfg = DistributedRateLimit::new(
Arc::new(FailingStore),
RateLimit {
max_requests: 1,
window: Duration::from_secs(60),
},
);
assert_eq!(status_of(&store_app(cfg)).await.status(), StatusCode::OK);
}
#[tokio::test]
async fn store_error_fails_closed_with_503_when_configured() {
let cfg = DistributedRateLimit::new(
Arc::new(FailingStore),
RateLimit {
max_requests: 1,
window: Duration::from_secs(60),
},
)
.on_store_error(StoreErrorPolicy::FailClosed);
let res = status_of(&store_app(cfg)).await;
assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(
res.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok()),
Some("1"),
"a shed 503 must tell the load balancer when to retry"
);
}
}