use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use axum::body::Body;
use axum::extract::ConnectInfo;
use axum::http::{Request, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use subtle::ConstantTimeEq;
use tokio::sync::Mutex;
pub const MAX_RATE_LIMIT_ENTRIES: usize = 10_000;
pub const RATE_WINDOW: Duration = Duration::from_mins(1);
#[derive(Clone)]
pub struct AuthConfig {
pub token_hash: Option<blake3::Hash>,
pub require_auth: bool,
}
impl AuthConfig {
#[must_use]
pub fn new(token: Option<&str>, require_auth: bool) -> Self {
Self {
token_hash: token.map(|t| blake3::hash(t.as_bytes())),
require_auth,
}
}
}
#[derive(Clone, Debug)]
pub struct AuthIdentity {
pub authenticated: bool,
}
#[derive(Clone, Debug)]
pub struct Cidr {
addr: IpAddr,
prefix_len: u8,
}
impl Cidr {
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
let (addr_str, prefix_str) = s.split_once('/')?;
let addr: IpAddr = addr_str.parse().ok()?;
let prefix_len: u8 = prefix_str.parse().ok()?;
let max = match addr {
IpAddr::V4(_) => 32,
IpAddr::V6(_) => 128,
};
if prefix_len > max {
return None;
}
Some(Self { addr, prefix_len })
}
#[must_use]
pub fn contains(&self, ip: IpAddr) -> bool {
match (self.addr, ip) {
(IpAddr::V4(net), IpAddr::V4(candidate)) => {
if self.prefix_len == 0 {
return true;
}
let shift = 32 - u32::from(self.prefix_len);
u32::from(net) >> shift == u32::from(candidate) >> shift
}
(IpAddr::V6(net), IpAddr::V6(candidate)) => {
if self.prefix_len == 0 {
return true;
}
let shift = 128 - u32::from(self.prefix_len);
u128::from(net) >> shift == u128::from(candidate) >> shift
}
_ => false,
}
}
}
#[derive(Clone)]
pub struct RateLimitState {
pub limit: u32,
pub counters: Arc<Mutex<HashMap<IpAddr, (u32, Instant)>>>,
pub trusted_cidrs: Arc<Vec<Cidr>>,
}
impl RateLimitState {
#[must_use]
pub fn new(limit: u32, trusted_proxy_cidrs: &[String]) -> Self {
let parsed_cidrs: Vec<Cidr> = trusted_proxy_cidrs
.iter()
.filter_map(|s| {
let c = Cidr::parse(s);
if c.is_none() {
tracing::warn!(cidr = %s, "http-middleware: invalid trusted_proxy_cidr, ignoring");
}
c
})
.collect();
Self {
limit,
counters: Arc::new(Mutex::new(HashMap::new())),
trusted_cidrs: Arc::new(parsed_cidrs),
}
}
}
#[tracing::instrument(skip_all, name = "common.http_middleware.auth")]
pub async fn auth_middleware(
axum::extract::State(cfg): axum::extract::State<AuthConfig>,
mut req: Request<Body>,
next: Next,
) -> Response {
if let Some(expected_hash) = cfg.token_hash {
let auth_header = req
.headers()
.get("authorization")
.and_then(|v| v.to_str().ok());
let token = auth_header
.and_then(|v| v.strip_prefix("Bearer "))
.unwrap_or("");
let token_hash = blake3::hash(token.as_bytes());
if !bool::from(token_hash.as_bytes().ct_eq(expected_hash.as_bytes())) {
req.extensions_mut().insert(AuthIdentity {
authenticated: false,
});
return StatusCode::UNAUTHORIZED.into_response();
}
req.extensions_mut().insert(AuthIdentity {
authenticated: true,
});
} else {
if cfg.require_auth {
tracing::warn!(
"http-middleware: require_auth=true but no auth_token configured, rejecting request"
);
req.extensions_mut().insert(AuthIdentity {
authenticated: false,
});
return StatusCode::UNAUTHORIZED.into_response();
}
req.extensions_mut().insert(AuthIdentity {
authenticated: false,
});
}
next.run(req).await
}
#[tracing::instrument(skip_all, name = "common.http_middleware.rate_limit")]
pub async fn rate_limit_middleware(
axum::extract::State(state): axum::extract::State<RateLimitState>,
req: Request<Body>,
next: Next,
) -> Response {
if state.limit == 0 {
return next.run(req).await;
}
let peer_ip = req
.extensions()
.get::<ConnectInfo<std::net::SocketAddr>>()
.map_or(IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), |ci| ci.0.ip());
let ip = if !state.trusted_cidrs.is_empty()
&& state.trusted_cidrs.iter().any(|c| c.contains(peer_ip))
{
let xff_ip = req
.headers()
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|v| {
v.split(',')
.map(str::trim)
.filter_map(|s| s.parse::<IpAddr>().ok())
.rev()
.find(|ip| !state.trusted_cidrs.iter().any(|c| c.contains(*ip)))
});
xff_ip.unwrap_or(peer_ip)
} else {
peer_ip
};
let now = Instant::now();
let mut counters = state.counters.lock().await;
if counters.len() >= MAX_RATE_LIMIT_ENTRIES && !counters.contains_key(&ip) {
let before_eviction = counters.len();
counters.retain(|_, (_, ts)| now.duration_since(*ts) < RATE_WINDOW);
let after_eviction = counters.len();
if after_eviction >= MAX_RATE_LIMIT_ENTRIES {
tracing::warn!(
before = before_eviction,
after = after_eviction,
limit = MAX_RATE_LIMIT_ENTRIES,
"rate limiter at capacity after stale entry eviction, rejecting new IP"
);
return StatusCode::TOO_MANY_REQUESTS.into_response();
}
}
let entry = counters.entry(ip).or_insert((0, now));
if now.duration_since(entry.1) >= RATE_WINDOW {
*entry = (1, now);
} else {
entry.0 += 1;
if entry.0 > state.limit {
return StatusCode::TOO_MANY_REQUESTS.into_response();
}
}
drop(counters);
next.run(req).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cidr_ipv4_contains_in_range() {
let cidr = Cidr::parse("10.0.0.0/8").unwrap();
assert!(cidr.contains("10.1.2.3".parse().unwrap()));
assert!(cidr.contains("10.255.255.255".parse().unwrap()));
assert!(!cidr.contains("11.0.0.0".parse().unwrap()));
assert!(!cidr.contains("9.255.255.255".parse().unwrap()));
}
#[test]
fn cidr_ipv4_slash32_exact_host() {
let cidr = Cidr::parse("192.168.1.100/32").unwrap();
assert!(cidr.contains("192.168.1.100".parse().unwrap()));
assert!(!cidr.contains("192.168.1.101".parse().unwrap()));
}
#[test]
fn cidr_ipv4_slash0_matches_all() {
let cidr = Cidr::parse("0.0.0.0/0").unwrap();
assert!(cidr.contains("1.2.3.4".parse().unwrap()));
assert!(cidr.contains("255.255.255.255".parse().unwrap()));
}
#[test]
fn cidr_ipv6_contains_in_range() {
let cidr = Cidr::parse("::1/128").unwrap();
assert!(cidr.contains("::1".parse().unwrap()));
assert!(!cidr.contains("::2".parse().unwrap()));
}
#[test]
fn cidr_ipv4_v6_mismatch_returns_false() {
let cidr = Cidr::parse("10.0.0.0/8").unwrap();
assert!(!cidr.contains("::1".parse().unwrap()));
}
#[test]
fn cidr_parse_rejects_invalid() {
assert!(Cidr::parse("not-a-cidr").is_none());
assert!(Cidr::parse("10.0.0.0/33").is_none());
assert!(Cidr::parse("::1/129").is_none());
assert!(Cidr::parse("10.0.0.0/").is_none());
}
#[test]
fn auth_config_new_hashes_token() {
let cfg = AuthConfig::new(Some("secret"), false);
assert!(cfg.token_hash.is_some());
assert!(!cfg.require_auth);
let expected = blake3::hash(b"secret");
assert_eq!(cfg.token_hash.unwrap(), expected);
}
#[test]
fn auth_config_new_none_token() {
let cfg = AuthConfig::new(None, true);
assert!(cfg.token_hash.is_none());
assert!(cfg.require_auth);
}
#[test]
fn rate_limit_state_new_parses_cidrs() {
let state = RateLimitState::new(10, &["10.0.0.0/8".to_string(), "invalid".to_string()]);
assert_eq!(state.limit, 10);
assert_eq!(state.trusted_cidrs.len(), 1);
}
#[test]
fn bearer_ct_eq_is_constant_time() {
use std::time::Instant;
const ITERS: u32 = 100_000;
const MAX_RATIO: u128 = 10;
let expected_hash = blake3::hash(b"super-secret-gateway-token");
let candidates: &[&[u8]] = &[b"x", b"wrong_token_123", &[b'z'; 512]];
let mut times_ns: Vec<u128> = Vec::with_capacity(candidates.len());
for candidate in candidates {
let h = blake3::hash(candidate);
for _ in 0..1_000 {
let _ = h.as_bytes().ct_eq(expected_hash.as_bytes());
}
let start = Instant::now();
for _ in 0..ITERS {
let _ = h.as_bytes().ct_eq(expected_hash.as_bytes());
}
times_ns.push(start.elapsed().as_nanos() / u128::from(ITERS));
}
let min = *times_ns.iter().min().unwrap();
let max = *times_ns.iter().max().unwrap();
assert!(
min > 0 && max / min < MAX_RATIO,
"ct_eq timing ratio {max}/{min} exceeds {MAX_RATIO}×; times per iter: {times_ns:?} ns"
);
}
}