use std::{
collections::HashMap,
net::IpAddr,
sync::{
Mutex,
atomic::{AtomicBool, Ordering},
},
time::{Duration, Instant},
};
use actix_web::{
Error, HttpResponse,
body::{EitherBody, MessageBody},
dev::{ServiceRequest, ServiceResponse},
middleware::Next,
web,
};
use authr_core::config::RateLimitConfig;
const MEMORY_STORE_MAX_ENTRIES: usize = 100_000;
const NO_TRUSTED_IP_KEY: &str = "no-trusted-ip";
static IP_WARNING_LOGGED: AtomicBool = AtomicBool::new(false);
#[derive(Debug, Clone, Copy)]
struct ResolvedRateLimitRule {
window: Duration,
max: u32,
}
#[derive(Debug, Clone)]
struct RateLimitEntry {
count: u32,
last_request: Instant,
window: Duration,
}
pub struct RateLimiter {
config: RateLimitConfig,
base_path: String,
entries: Mutex<HashMap<String, RateLimitEntry>>,
}
impl RateLimiter {
pub fn new(config: RateLimitConfig, base_path: impl Into<String>) -> Self {
Self {
config,
base_path: normalize_base_path(&base_path.into()),
entries: Mutex::new(HashMap::new()),
}
}
pub fn enabled(&self) -> bool {
self.config.enabled
}
#[tracing::instrument(target = "middleware::rate_limit::check", skip_all, err)]
pub fn check(
&self,
ip: Option<IpAddr>,
request_path: &str,
) -> Result<Option<u64>, &'static str> {
let path = self.normalize_request_path(request_path);
let rule = self.rule_for_path(&path)?;
let ip = match ip {
Some(ip) => ip.to_string(),
None => {
if !IP_WARNING_LOGGED.swap(true, Ordering::Relaxed) {
tracing::warn!(
"Could not determine client IP for rate limiting. \
Requests without a peer IP will share a per-route bucket. \
Configure trusted-proxy support when running behind a reverse proxy."
);
}
NO_TRUSTED_IP_KEY.to_owned()
}
};
let key = format!("{ip}:{path}");
self.consume(&key, rule)
}
fn rule_for_path(&self, path: &str) -> Result<ResolvedRateLimitRule, &'static str> {
let window = self
.config
.window
.to_std()
.map_err(|_| "Rate-limit window must be positive")?;
if window.is_zero() {
return Err("Rate-limit window must be positive");
}
if self.config.max == 0 {
return Err("Rate-limit maximum must be greater than zero");
}
let custom_rule = self
.config
.custom_rules
.iter()
.filter_map(|(pattern, rule)| {
let pattern = normalize_path(pattern);
matches_path_or_subpath(path, &pattern).then_some((pattern.len(), rule))
})
.max_by_key(|(length, _)| *length);
if let Some((_, rule)) = custom_rule {
return Ok(ResolvedRateLimitRule {
window: rule
.window
.to_std()
.map_err(|_| "Rate-limit window must be positive")?,
max: rule.max,
});
}
let mut rule = ResolvedRateLimitRule {
window,
max: self.config.max,
};
if matches_path_or_subpath(path, "/sign-in")
|| matches_path_or_subpath(path, "/sign-up")
|| matches_path_or_subpath(path, "/change-password")
|| matches_path_or_subpath(path, "/change-email")
{
rule = ResolvedRateLimitRule {
window: Duration::from_secs(10),
max: 3,
};
}
if matches_path_or_subpath(path, "/request-password-reset")
|| matches_path_or_subpath(path, "/send-verification-email")
|| matches_path_or_subpath(path, "/forget-password")
|| matches_path_or_subpath(path, "/email-otp/send-verification-otp")
|| matches_path_or_subpath(path, "/email-otp/request-password-reset")
{
rule = ResolvedRateLimitRule {
window: Duration::from_secs(60),
max: 3,
};
}
if matches_path_or_subpath(path, "/verify-email") {
rule = ResolvedRateLimitRule {
window: Duration::from_secs(60),
max: 5,
};
}
if matches_path_or_subpath(path, "/callback") {
rule = ResolvedRateLimitRule {
window: Duration::from_secs(10),
max: 10,
};
}
Ok(rule)
}
fn consume(&self, key: &str, rule: ResolvedRateLimitRule) -> Result<Option<u64>, &'static str> {
let now = Instant::now();
let mut entries = self
.entries
.lock()
.map_err(|_| "Rate-limit storage lock is poisoned")?;
prune_expired(&mut entries, now);
match entries.get_mut(key) {
None => {
if entries.len() >= MEMORY_STORE_MAX_ENTRIES {
evict_oldest(&mut entries);
}
entries.insert(
key.to_owned(),
RateLimitEntry {
count: 1,
last_request: now,
window: rule.window,
},
);
Ok(None)
}
Some(entry) => {
let elapsed = now.duration_since(entry.last_request);
if elapsed >= rule.window {
entry.count = 1;
entry.last_request = now;
entry.window = rule.window;
return Ok(None);
}
if entry.count >= rule.max {
return Ok(Some(retry_after(entry.last_request, rule.window, now)));
}
entry.count += 1;
entry.last_request = now;
entry.window = rule.window;
Ok(None)
}
}
}
fn normalize_request_path(&self, request_path: &str) -> String {
let path = request_path.split('?').next().unwrap_or(request_path);
let path = normalize_path(path);
if self.base_path.is_empty() {
return path;
}
if path == self.base_path {
return "/".to_owned();
}
if let Some(relative) = path.strip_prefix(&self.base_path)
&& relative.starts_with('/')
{
return relative.to_owned();
}
path
}
}
#[tracing::instrument(target = "middleware::rate_limit::rate_limit", skip_all, err)]
pub async fn rate_limit<B>(
req: ServiceRequest,
next: Next<B>,
) -> Result<ServiceResponse<EitherBody<B>>, Error>
where
B: MessageBody + 'static,
{
let Some(limiter) = req.app_data::<web::Data<RateLimiter>>().cloned() else {
tracing::error!("RateLimiter is missing from application data");
return Ok(req
.into_response(HttpResponse::InternalServerError().finish())
.map_into_right_body());
};
if !limiter.enabled() {
return next
.call(req)
.await
.map(ServiceResponse::map_into_left_body);
}
let ip = req.peer_addr().map(|address| address.ip());
let path = req.path().to_owned();
match limiter.check(ip, &path) {
Ok(None) => next
.call(req)
.await
.map(ServiceResponse::map_into_left_body),
Ok(Some(retry_after)) => {
tracing::debug!(retry_after, "Request rejected by rate limiter");
let response = HttpResponse::TooManyRequests()
.insert_header(("Retry-After", retry_after.to_string()))
.json(serde_json::json!({
"message": "Too many requests. Please try again later."
}));
Ok(req.into_response(response).map_into_right_body())
}
Err(error) => {
tracing::error!(error, "Rate limiter failed");
Ok(req
.into_response(HttpResponse::InternalServerError().finish())
.map_into_right_body())
}
}
}
fn prune_expired(entries: &mut HashMap<String, RateLimitEntry>, now: Instant) {
entries.retain(|_, entry| now.duration_since(entry.last_request) < entry.window);
}
fn evict_oldest(entries: &mut HashMap<String, RateLimitEntry>) {
if let Some(oldest_key) = entries
.iter()
.min_by_key(|(_, entry)| entry.last_request)
.map(|(key, _)| key.clone())
{
entries.remove(&oldest_key);
}
}
fn retry_after(last_request: Instant, window: Duration, now: Instant) -> u64 {
let remaining = window.saturating_sub(now.duration_since(last_request));
remaining
.as_secs()
.saturating_add(u64::from(remaining.subsec_nanos() > 0))
.max(1)
}
fn matches_path_or_subpath(path: &str, prefix: &str) -> bool {
path == prefix
|| path
.strip_prefix(prefix)
.is_some_and(|suffix| suffix.starts_with('/'))
}
fn normalize_base_path(path: &str) -> String {
if path.is_empty() || path == "/" {
return String::new();
}
normalize_path(path)
}
fn normalize_path(path: &str) -> String {
let path = if path.starts_with('/') {
path.to_owned()
} else {
format!("/{path}")
};
if path.len() > 1 {
path.trim_end_matches('/').to_owned()
} else {
path
}
}