use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use axum::http::{HeaderMap, HeaderValue, Method};
use tower_http::cors::{AllowOrigin, Any, CorsLayer};
pub(crate) const DEFAULT_MAX_BODY_BYTES: usize = 1024 * 1024;
const MAX_CONFIGURABLE_BODY_BYTES: u64 = 8 * 1024 * 1024;
const DEFAULT_TIMEOUT_SECS: u64 = 30;
const DEFAULT_RATE_LIMIT: u32 = 60;
const DEFAULT_RATE_WINDOW_SECS: u64 = 60;
const MAX_WINDOW_SECS: u64 = 24 * 60 * 60;
const MAX_RATE_KEYS: usize = 10_000;
pub struct ServerConfig {
pub(crate) max_body_bytes: usize,
pub(crate) request_timeout: Duration,
pub(crate) cors: CorsPolicy,
pub(crate) rate_limit_requests: u32,
pub(crate) rate_limit_window: Duration,
pub(crate) trust_proxy: bool,
}
#[derive(Clone)]
pub(crate) enum CorsPolicy {
Localhost,
Allowlist(Vec<HeaderValue>),
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
max_body_bytes: DEFAULT_MAX_BODY_BYTES,
request_timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
cors: CorsPolicy::Localhost,
rate_limit_requests: DEFAULT_RATE_LIMIT,
rate_limit_window: Duration::from_secs(DEFAULT_RATE_WINDOW_SECS),
trust_proxy: false,
}
}
}
struct EnvSettings<'a> {
cors_origins: Option<&'a str>,
trusted_proxy: Option<&'a str>,
max_body_bytes: Option<&'a str>,
request_timeout_secs: Option<&'a str>,
rate_limit: Option<&'a str>,
rate_window_secs: Option<&'a str>,
}
impl ServerConfig {
pub fn from_env() -> Result<Self, String> {
let cors_origins = optional_var("BNSPELL_CORS_ORIGINS")?;
let trusted_proxy = optional_var("BNSPELL_TRUSTED_PROXY")?;
let max_body_bytes = optional_var("BNSPELL_MAX_BODY_BYTES")?;
let request_timeout_secs = optional_var("BNSPELL_REQUEST_TIMEOUT_SECS")?;
let rate_limit = optional_var("BNSPELL_RATE_LIMIT")?;
let rate_window_secs = optional_var("BNSPELL_RATE_WINDOW_SECS")?;
Self::from_settings(EnvSettings {
cors_origins: cors_origins.as_deref(),
trusted_proxy: trusted_proxy.as_deref(),
max_body_bytes: max_body_bytes.as_deref(),
request_timeout_secs: request_timeout_secs.as_deref(),
rate_limit: rate_limit.as_deref(),
rate_window_secs: rate_window_secs.as_deref(),
})
}
fn from_settings(settings: EnvSettings<'_>) -> Result<Self, String> {
let max_body = parse_u64(
"BNSPELL_MAX_BODY_BYTES",
settings.max_body_bytes,
DEFAULT_MAX_BODY_BYTES as u64,
)?;
if max_body == 0 {
return Err("BNSPELL_MAX_BODY_BYTES must be at least 1".to_string());
}
if max_body > MAX_CONFIGURABLE_BODY_BYTES {
return Err(format!(
"BNSPELL_MAX_BODY_BYTES must be at most {MAX_CONFIGURABLE_BODY_BYTES}"
));
}
let max_body_bytes = usize::try_from(max_body)
.map_err(|_| "BNSPELL_MAX_BODY_BYTES does not fit in usize".to_string())?;
let timeout_secs = parse_u64(
"BNSPELL_REQUEST_TIMEOUT_SECS",
settings.request_timeout_secs,
DEFAULT_TIMEOUT_SECS,
)?;
let rate_window_secs = parse_u64(
"BNSPELL_RATE_WINDOW_SECS",
settings.rate_window_secs,
DEFAULT_RATE_WINDOW_SECS,
)?;
let rate_limit = parse_u64(
"BNSPELL_RATE_LIMIT",
settings.rate_limit,
u64::from(DEFAULT_RATE_LIMIT),
)?;
let rate_limit_requests = u32::try_from(rate_limit)
.map_err(|_| format!("BNSPELL_RATE_LIMIT must be at most {}", u32::MAX))?;
Ok(Self {
max_body_bytes,
request_timeout: window_secs("BNSPELL_REQUEST_TIMEOUT_SECS", timeout_secs)?,
cors: parse_cors(settings.cors_origins)?,
rate_limit_requests,
rate_limit_window: window_secs("BNSPELL_RATE_WINDOW_SECS", rate_window_secs)?,
trust_proxy: parse_flag("BNSPELL_TRUSTED_PROXY", settings.trusted_proxy)?,
})
}
pub(crate) fn cors_layer(&self) -> CorsLayer {
let origin = match &self.cors {
CorsPolicy::Localhost => {
AllowOrigin::predicate(|origin, _| origin.to_str().is_ok_and(is_localhost_origin))
}
CorsPolicy::Allowlist(origins) => AllowOrigin::list(origins.clone()),
};
CorsLayer::new()
.allow_origin(origin)
.allow_methods([
Method::GET,
Method::HEAD,
Method::PUT,
Method::POST,
Method::DELETE,
Method::PATCH,
])
.allow_headers(Any)
}
pub(crate) fn rate_limiter(&self) -> RateLimiter {
RateLimiter {
max_requests: self.rate_limit_requests,
window: self.rate_limit_window,
trust_proxy: self.trust_proxy,
hits: Arc::new(Mutex::new(HashMap::new())),
}
}
}
#[derive(Clone)]
pub(crate) struct RateLimiter {
max_requests: u32,
window: Duration,
trust_proxy: bool,
hits: Arc<Mutex<HashMap<String, Window>>>,
}
struct Window {
start: Instant,
count: u32,
}
impl RateLimiter {
pub(crate) fn check(
&self,
path: &str,
headers: &HeaderMap,
peer: Option<IpAddr>,
) -> Result<(), u64> {
if self.max_requests == 0 || path == "/health" || path == "/api/health" {
return Ok(());
}
let key = client_key(headers, peer, self.trust_proxy);
let mut hits = self.hits.lock().unwrap_or_else(|err| err.into_inner());
let now = Instant::now();
if hits.len() >= MAX_RATE_KEYS {
let window = self.window;
hits.retain(|_, entry| now.saturating_duration_since(entry.start) < window);
}
if !hits.contains_key(&key) && hits.len() >= MAX_RATE_KEYS {
return Err(retry_after_secs(self.window));
}
let entry = hits.entry(key).or_insert(Window {
start: now,
count: 0,
});
if now.saturating_duration_since(entry.start) >= self.window {
entry.start = now;
entry.count = 0;
}
if entry.count >= self.max_requests {
let remaining = self
.window
.saturating_sub(now.saturating_duration_since(entry.start));
return Err(retry_after_secs(remaining));
}
entry.count += 1;
Ok(())
}
}
fn client_key(headers: &HeaderMap, peer: Option<IpAddr>, trust_proxy: bool) -> String {
let from_proxy = if trust_proxy {
forwarded_ip(headers)
} else {
None
};
match from_proxy.or(peer) {
Some(ip) => ip.to_string(),
None => "unknown".to_string(),
}
}
fn retry_after_secs(remaining: Duration) -> u64 {
let whole = remaining.as_secs();
if remaining.subsec_nanos() == 0 {
whole.max(1)
} else {
whole.saturating_add(1)
}
}
fn forwarded_ip(headers: &HeaderMap) -> Option<IpAddr> {
let value = headers.get("x-forwarded-for")?.to_str().ok()?;
value
.split(',')
.rev()
.map(str::trim)
.find_map(parse_ip_token)
}
fn parse_ip_token(token: &str) -> Option<IpAddr> {
let token = token.trim_matches(|ch| ch == '"' || ch == '[' || ch == ']');
if let Ok(ip) = token.parse::<IpAddr>() {
return Some(ip);
}
let (host, port) = token.rsplit_once(':')?;
if port.is_empty() || !port.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
host.parse().ok()
}
fn optional_var(name: &str) -> Result<Option<String>, String> {
match std::env::var(name) {
Ok(value) => Ok(Some(value)),
Err(std::env::VarError::NotPresent) => Ok(None),
Err(std::env::VarError::NotUnicode(_)) => Err(format!("{name} is not valid Unicode")),
}
}
fn parse_cors(value: Option<&str>) -> Result<CorsPolicy, String> {
let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
return Ok(CorsPolicy::Localhost);
};
let mut origins = Vec::new();
for entry in value.split(',') {
let entry = entry.trim();
if entry.is_empty() {
continue;
}
origins.push(parse_origin(entry)?);
}
if origins.is_empty() {
return Err("BNSPELL_CORS_ORIGINS is empty".to_string());
}
Ok(CorsPolicy::Allowlist(origins))
}
fn parse_origin(value: &str) -> Result<HeaderValue, String> {
if value.contains('*') {
return Err(
"BNSPELL_CORS_ORIGINS must list exact origins; a wildcard is not allowed".to_string(),
);
}
if !(value.starts_with("http://") || value.starts_with("https://")) {
return Err(format!("invalid BNSPELL_CORS_ORIGINS entry: {value}"));
}
let rest = value.split_once("://").map(|(_, rest)| rest).unwrap_or("");
if rest.is_empty()
|| rest.contains('/')
|| rest.contains('?')
|| rest.contains('#')
|| rest.contains('@')
|| rest.contains(' ')
{
return Err(format!("invalid BNSPELL_CORS_ORIGINS entry: {value}"));
}
HeaderValue::from_str(value).map_err(|_| format!("invalid BNSPELL_CORS_ORIGINS entry: {value}"))
}
fn is_localhost_origin(origin: &str) -> bool {
let Some(authority) = origin
.strip_prefix("http://")
.or_else(|| origin.strip_prefix("https://"))
else {
return false;
};
if authority.is_empty()
|| authority.contains('/')
|| authority.contains('@')
|| authority.contains('?')
|| authority.contains('#')
{
return false;
}
matches!(host_of(authority), "localhost" | "127.0.0.1" | "::1")
}
fn host_of(authority: &str) -> &str {
if let Some(rest) = authority.strip_prefix('[') {
let Some((host, after)) = rest.split_once(']') else {
return "";
};
if after.is_empty()
|| (after.starts_with(':')
&& !after[1..].is_empty()
&& after[1..].bytes().all(|byte| byte.is_ascii_digit()))
{
return host;
}
return "";
}
match authority.rsplit_once(':') {
Some((host, port))
if !host.is_empty()
&& !host.contains(':')
&& !port.is_empty()
&& port.bytes().all(|byte| byte.is_ascii_digit()) =>
{
host
}
_ => authority,
}
}
fn parse_flag(name: &str, value: Option<&str>) -> Result<bool, String> {
match value.map(str::trim) {
None | Some("") | Some("0") | Some("false") => Ok(false),
Some("1") | Some("true") => Ok(true),
Some(other) => Err(format!("invalid {name}: {other}")),
}
}
fn parse_u64(name: &str, value: Option<&str>, default: u64) -> Result<u64, String> {
match value.map(str::trim) {
None | Some("") => Ok(default),
Some(text) => text
.parse::<u64>()
.map_err(|_| format!("invalid {name}: {text}")),
}
}
fn window_secs(name: &str, value: u64) -> Result<Duration, String> {
if value == 0 {
return Err(format!("{name} must be at least 1"));
}
if value > MAX_WINDOW_SECS {
return Err(format!("{name} must be at most {MAX_WINDOW_SECS}"));
}
Ok(Duration::from_secs(value))
}
#[cfg(test)]
mod tests {
use super::{
ServerConfig, client_key, is_localhost_origin, parse_cors, parse_flag, parse_ip_token,
};
use axum::http::{HeaderMap, HeaderValue};
use std::net::IpAddr;
use std::time::Duration;
fn settings_default() -> ServerConfig {
ServerConfig::from_settings(super::EnvSettings {
cors_origins: None,
trusted_proxy: None,
max_body_bytes: None,
request_timeout_secs: None,
rate_limit: None,
rate_window_secs: None,
})
.unwrap()
}
#[test]
fn unset_env_matches_the_defaults() {
let config = settings_default();
assert_eq!(config.max_body_bytes, super::DEFAULT_MAX_BODY_BYTES);
assert_eq!(config.request_timeout, Duration::from_secs(30));
assert_eq!(config.rate_limit_requests, 60);
assert_eq!(config.rate_limit_window, Duration::from_secs(60));
assert!(!config.trust_proxy);
assert!(matches!(config.cors, super::CorsPolicy::Localhost));
}
#[test]
fn cors_allowlist_rejects_a_wildcard_and_a_path() {
assert!(parse_cors(Some("*")).is_err());
assert!(parse_cors(Some("https://example.com/app")).is_err());
assert!(parse_cors(Some("example.com")).is_err());
let policy = parse_cors(Some(" https://app.example.com, http://localhost:3000 ")).unwrap();
match policy {
super::CorsPolicy::Allowlist(origins) => {
assert_eq!(
origins,
vec![
HeaderValue::from_static("https://app.example.com"),
HeaderValue::from_static("http://localhost:3000"),
]
);
}
super::CorsPolicy::Localhost => panic!("expected an allowlist"),
}
}
#[test]
fn localhost_origins_allow_loopback_hosts_only() {
for origin in [
"http://localhost:3000",
"https://localhost",
"http://127.0.0.1:8787",
"http://[::1]:3000",
] {
assert!(is_localhost_origin(origin), "{origin}");
}
for origin in [
"https://hoppscotch.io",
"http://localhost.evil.com",
"http://evil.com@localhost",
"http://127.0.0.1.example.com",
"null",
] {
assert!(!is_localhost_origin(origin), "{origin}");
}
}
#[test]
fn numeric_settings_reject_zero_and_garbage() {
let err = ServerConfig::from_settings(super::EnvSettings {
cors_origins: None,
trusted_proxy: Some("yes"),
max_body_bytes: Some("0"),
request_timeout_secs: None,
rate_limit: None,
rate_window_secs: None,
});
assert!(err.is_err());
assert!(parse_flag("BNSPELL_TRUSTED_PROXY", Some("true")).unwrap());
assert!(!parse_flag("BNSPELL_TRUSTED_PROXY", Some("false")).unwrap());
let config = ServerConfig::from_settings(super::EnvSettings {
cors_origins: None,
trusted_proxy: Some("1"),
max_body_bytes: Some("4096"),
request_timeout_secs: Some("5"),
rate_limit: Some("0"),
rate_window_secs: Some("10"),
})
.unwrap();
assert!(config.trust_proxy);
assert_eq!(config.max_body_bytes, 4096);
assert_eq!(config.request_timeout, Duration::from_secs(5));
assert_eq!(config.rate_limit_requests, 0);
assert_eq!(config.rate_limit_window, Duration::from_secs(10));
}
#[test]
fn forwarded_for_is_the_rightmost_address_and_only_when_trusted() {
let mut headers = HeaderMap::new();
headers.insert(
"x-forwarded-for",
HeaderValue::from_static("9.9.9.9, 203.0.113.8"),
);
let peer: IpAddr = "198.51.100.4".parse().unwrap();
assert_eq!(client_key(&headers, Some(peer), false), "198.51.100.4");
assert_eq!(client_key(&headers, Some(peer), true), "203.0.113.8");
assert_eq!(
parse_ip_token("203.0.113.8:443").unwrap().to_string(),
"203.0.113.8"
);
assert_eq!(client_key(&HeaderMap::new(), None, false), "unknown");
}
#[test]
fn rate_limiter_resets_per_key_and_skips_health() {
let limiter = ServerConfig {
rate_limit_requests: 1,
trust_proxy: true,
..ServerConfig::default()
}
.rate_limiter();
let mut first = HeaderMap::new();
first.insert("x-forwarded-for", HeaderValue::from_static("203.0.113.1"));
let mut second = HeaderMap::new();
second.insert("x-forwarded-for", HeaderValue::from_static("203.0.113.2"));
assert!(limiter.check("/api/check", &first, None).is_ok());
assert!(limiter.check("/api/check", &first, None).is_err());
assert!(limiter.check("/health", &first, None).is_ok());
assert!(limiter.check("/api/health", &first, None).is_ok());
assert!(limiter.check("/api/suggest", &second, None).is_ok());
}
}