From cbc6cadf6d4db32cd80471eaaf040a20f10c995f Mon Sep 17 00:00:00 2001 From: mrorigo Date: Mon, 24 Aug 2026 19:20:07 +0200 Subject: [PATCH] Rate limit unauthenticated API requests by client IP rate_limit_middleware was never wired into the router, and it keyed only on the AuthContext extension - which no middleware ever inserted, since authentication happens in the handler extractor. So nothing was rate limited at all. The router now layers three stages on authenticated routes: an IP-keyed pre-auth limiter (120 req/min per address) that meters token guessing and abuse of public endpoints, then auth middleware that resolves the bearer token once and publishes the context as a request extension (handlers reuse it instead of repeating the DB lookup), and finally the per-tenant limiter reading that context. Health, docs, and tracking endpoints stay outside the auth layer. Client IPs come from the socket peer; when the peer is a configured trusted proxy (SERVER__API_TRUSTED_PROXIES), the X-Forwarded-For origin is used instead. A direct client cannot spoof the header past the limiter. --- config/default.toml | 4 + crates/sentio-api/src/auth.rs | 31 ++++++ crates/sentio-api/src/middleware.rs | 142 +++++++++++++++++++++++++--- crates/sentio-api/src/routes/mod.rs | 27 +++++- crates/sentio-api/src/server.rs | 17 ++-- crates/sentio-api/src/state.rs | 9 ++ crates/sentio-core/src/config.rs | 12 +++ 7 files changed, 219 insertions(+), 23 deletions(-) diff --git a/config/default.toml b/config/default.toml index 199bd86..e037d8a 100644 --- a/config/default.toml +++ b/config/default.toml @@ -13,6 +13,10 @@ max_connections = 10000 proxy_protocol = false xclient_enabled = false xclient_allowed_ips = [] +# IPs allowed to set X-Forwarded-For on API requests (pre-auth rate limiting +# keys on the forwarded origin for these peers). Leave empty when the API is +# reached directly; add your load balancer's IP when running behind an L7 proxy. +api_trusted_proxies = [] shutdown_drain_secs = 30 shutdown_force_secs = 60 max_api_body_size_mb = 50 diff --git a/crates/sentio-api/src/auth.rs b/crates/sentio-api/src/auth.rs index bd1397e..f53f603 100644 --- a/crates/sentio-api/src/auth.rs +++ b/crates/sentio-api/src/auth.rs @@ -36,6 +36,12 @@ impl FromRequestParts for AuthContext { parts: &mut Parts, state: &AppState, ) -> impl std::future::Future> + Send { + // When the auth middleware has already resolved the context, reuse + // it instead of repeating the database lookup. + // When the auth middleware has already resolved the context, reuse + // it instead of repeating the database lookup. + let cached = parts.extensions.get::().cloned(); + let pool = state.pool.clone(); let auth_header = parts .headers @@ -44,6 +50,9 @@ impl FromRequestParts for AuthContext { .map(|s| s.to_string()); async move { + if let Some(ctx) = cached { + return Ok(ctx); + } let auth_header = auth_header.ok_or_else(|| ApiError::Auth("missing authorization header".into()))?; @@ -87,3 +96,25 @@ impl FromRequestParts for AuthContext { } } } + +// ────────────────────────────────────────────────────────────────────────────── +// Auth middleware +// ────────────────────────────────────────────────────────────────────────────── + +/// Resolve the bearer token once per request and publish the resulting +/// `AuthContext` as a request extension, so downstream middleware (per-tenant +/// rate limiting) and handlers share a single database lookup. +/// +/// Applied only to authenticated route groups - public endpoints such as +/// `/health`, `/docs`, and `/track` are mounted outside this layer. +pub async fn auth_middleware( + axum::extract::State(state): axum::extract::State, + req: axum::extract::Request, + next: axum::middleware::Next, +) -> Result { + let (mut parts, body) = req.into_parts(); + let ctx = AuthContext::from_request_parts(&mut parts, &state).await?; + parts.extensions.insert(ctx); + let req = axum::http::Request::from_parts(parts, body); + Ok(next.run(req).await) +} diff --git a/crates/sentio-api/src/middleware.rs b/crates/sentio-api/src/middleware.rs index 401ae9b..d7122f5 100644 --- a/crates/sentio-api/src/middleware.rs +++ b/crates/sentio-api/src/middleware.rs @@ -1,4 +1,6 @@ -use axum::extract::Request; +use std::net::{IpAddr, SocketAddr}; + +use axum::extract::{ConnectInfo, Request}; use axum::http::HeaderValue; use axum::middleware::Next; use axum::response::Response; @@ -22,24 +24,142 @@ impl MakeRequestId for UuidRequestId { } // ────────────────────────────────────────────────────────────────────────────── -// Per-tenant rate limiting middleware +// Rate limiting // ────────────────────────────────────────────────────────────────────────────── -pub async fn rate_limit_middleware( +/// Resolve the client IP for rate limiting: the socket peer, unless the peer +/// is a trusted proxy in which case the X-Forwarded-For origin is used. +pub fn client_ip(state: &AppState, req: &Request) -> Option { + let peer = req + .extensions() + .get::>() + .map(|ConnectInfo(addr)| addr.ip())?; + + let forwarded = req + .headers() + .get("x-forwarded-for") + .and_then(|v| v.to_str().ok()); + + resolve_client_ip(peer, forwarded, &state.config.server.api_trusted_proxies) +} + +/// Pure decision logic behind [`client_ip`]: trust X-Forwarded-For only when +/// the socket peer is an explicitly configured proxy. +fn resolve_client_ip( + peer: IpAddr, + forwarded: Option<&str>, + trusted_proxies: &[String], +) -> Option { + let peer_is_proxy = trusted_proxies.iter().any(|p| { + p.trim() + .parse::() + .map(|proxy| proxy == peer) + .unwrap_or(false) + }); + + if peer_is_proxy { + if let Some(origin) = forwarded + .and_then(|chain| chain.split(',').next()) + .and_then(|ip| ip.trim().parse::().ok()) + { + return Some(origin); + } + } + + Some(peer) +} + +/// Pre-auth limit keyed by client IP. Runs outermost so unauthenticated +/// traffic - including token guessing - is metered. +pub async fn ip_rate_limit_middleware( state: axum::extract::State, req: Request, next: Next, ) -> Result { - // Rate limiting is keyed by tenant_id from the auth context. - // If no auth context is set (e.g. before auth middleware), skip rate limiting. - if let Some(auth) = req.extensions().get::() { - let key = auth.tenant_id.to_string(); - if state.rate_limiter.check_key(&key).is_err() { - return Err(ApiError::RateLimit(format!( - "rate limit exceeded for tenant {key}" - ))); + if let Some(ip) = client_ip(&state, &req) { + let key = format!("ip:{ip}"); + if state.ip_rate_limiter.check_key(&key).is_err() { + return Err(ApiError::RateLimit(format!("rate limit exceeded for {ip}"))); } } Ok(next.run(req).await) } + +/// Per-tenant limit for authenticated traffic. Requires the auth middleware +/// to have inserted an `AuthContext` extension first; requests that fail +/// authentication are stopped there and never reach this limiter. +pub async fn tenant_rate_limit_middleware( + state: axum::extract::State, + req: Request, + next: Next, +) -> Result { + let Some(auth) = req.extensions().get::().cloned() else { + tracing::error!("tenant rate limit ran without AuthContext - auth middleware missing"); + return Ok(next.run(req).await); + }; + + let key = auth.tenant_id.to_string(); + if state.rate_limiter.check_key(&key).is_err() { + return Err(ApiError::RateLimit(format!( + "rate limit exceeded for tenant {key}" + ))); + } + + Ok(next.run(req).await) +} + +#[cfg(test)] +mod tests { + use super::resolve_client_ip; + use std::net::IpAddr; + + fn ip(s: &str) -> IpAddr { + s.parse().unwrap() + } + + #[test] + fn uses_peer_address_without_proxies() { + assert_eq!( + resolve_client_ip(ip("203.0.113.7"), Some("198.51.100.9"), &[]), + Some(ip("203.0.113.7")) + ); + } + + #[test] + fn ignores_spoofed_forwarded_header_from_untrusted_peer() { + // A direct client cannot mint an X-Forwarded-For origin. + assert_eq!( + resolve_client_ip( + ip("203.0.113.7"), + Some("1.2.3.4"), + &["10.0.0.1".to_string()] + ), + Some(ip("203.0.113.7")) + ); + } + + #[test] + fn trusts_forwarded_origin_only_via_configured_proxy() { + assert_eq!( + resolve_client_ip( + ip("10.0.0.1"), + Some("198.51.100.9, 10.0.0.1"), + &["10.0.0.1".to_string()] + ), + Some(ip("198.51.100.9")) + ); + } + + #[test] + fn falls_back_to_proxy_address_when_header_missing_or_invalid() { + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), None, &["10.0.0.1".to_string()]), + Some(ip("10.0.0.1")) + ); + assert_eq!( + resolve_client_ip(ip("10.0.0.1"), Some("not-an-ip"), &["10.0.0.1".to_string()]), + Some(ip("10.0.0.1")) + ); + } +} diff --git a/crates/sentio-api/src/routes/mod.rs b/crates/sentio-api/src/routes/mod.rs index 22cb618..d638997 100644 --- a/crates/sentio-api/src/routes/mod.rs +++ b/crates/sentio-api/src/routes/mod.rs @@ -271,11 +271,7 @@ pub fn router(state: AppState) -> Router { .route("/summary", get(errors::error_summary)) .route("/{id}", get(errors::get_error)); - Router::new() - .route("/openapi.json", get(|| async { Json(ApiDoc::openapi()) })) - // Custom page + embedded bundle so /docs works without a CDN. - .merge(Scalar::with_url("/docs", ApiDoc::openapi()).custom_html(docs::SCALAR_HTML)) - .route(docs::SCALAR_JS_PATH, get(docs::scalar_js)) + let authenticated_routes: Router = Router::new() .nest("/v1/messages", messages_router) .nest("/v1/domains", domains_router) .nest("/v1/webhooks", webhooks_router) @@ -291,8 +287,29 @@ pub fn router(state: AppState) -> Router { .nest("/v1/oauth", oauth_router) .nest("/v1/admin/abuse", abuse_router) .nest("/v1/admin/errors", errors_router) + // Request order: auth resolves the bearer token once, then the + // per-tenant limiter reads the resulting context. + .layer(axum::middleware::from_fn_with_state( + state.clone(), + crate::middleware::tenant_rate_limit_middleware, + )) + .layer(axum::middleware::from_fn_with_state( + state.clone(), + crate::auth::auth_middleware, + )); + + Router::new() + .route("/openapi.json", get(|| async { Json(ApiDoc::openapi()) })) + // Custom page + embedded bundle so /docs works without a CDN. + .merge(Scalar::with_url("/docs", ApiDoc::openapi()).custom_html(docs::SCALAR_HTML)) + .route(docs::SCALAR_JS_PATH, get(docs::scalar_js)) + .merge(authenticated_routes) .nest("/health", health_router) .nest("/track", tracking_router) + .layer(axum::middleware::from_fn_with_state( + state.clone(), + crate::middleware::ip_rate_limit_middleware, + )) .layer(DefaultBodyLimit::max(max_body_bytes)) .layer(TraceLayer::new_for_http()) .layer(PropagateRequestIdLayer::x_request_id()) diff --git a/crates/sentio-api/src/server.rs b/crates/sentio-api/src/server.rs index e853ebc..c2011e4 100644 --- a/crates/sentio-api/src/server.rs +++ b/crates/sentio-api/src/server.rs @@ -26,13 +26,16 @@ pub async fn start( tracing::info!(%addr, "API server listening"); - axum::serve(listener, app) - .with_graceful_shutdown(async move { - let _ = shutdown_rx.wait_for(|v| *v).await; - tracing::info!("API server shutting down"); - }) - .await - .map_err(|e| SentioError::Internal(format!("API server error: {e}")))?; + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .with_graceful_shutdown(async move { + let _ = shutdown_rx.wait_for(|v| *v).await; + tracing::info!("API server shutting down"); + }) + .await + .map_err(|e| SentioError::Internal(format!("API server error: {e}")))?; tracing::info!("API server stopped"); Ok(()) diff --git a/crates/sentio-api/src/state.rs b/crates/sentio-api/src/state.rs index c5b46f6..cc47922 100644 --- a/crates/sentio-api/src/state.rs +++ b/crates/sentio-api/src/state.rs @@ -24,9 +24,15 @@ pub struct AppState { pub blob_store: Arc, pub config: Arc, pub rate_limiter: Arc, + /// Pre-auth limiter keyed by client IP; guards token brute force and + /// unauthenticated endpoints. + pub ip_rate_limiter: Arc, pub kv: Option, } +/// Requests allowed per client IP per minute before authentication. +const IP_LIMIT_PER_MINUTE: u32 = 120; + impl AppState { pub fn new( pool: PgPool, @@ -36,6 +42,8 @@ impl AppState { ) -> Self { let quota = Quota::per_minute(NonZeroU32::new(600).unwrap()); let rate_limiter = RateLimiter::dashmap(quota); + let ip_quota = Quota::per_minute(NonZeroU32::new(IP_LIMIT_PER_MINUTE).unwrap()); + let ip_rate_limiter = RateLimiter::dashmap(ip_quota); Self { pool, @@ -43,6 +51,7 @@ impl AppState { blob_store: Arc::new(blob_store), config: Arc::new(config), rate_limiter: Arc::new(rate_limiter), + ip_rate_limiter: Arc::new(ip_rate_limiter), kv: None, } } diff --git a/crates/sentio-core/src/config.rs b/crates/sentio-core/src/config.rs index f33a365..52db220 100644 --- a/crates/sentio-core/src/config.rs +++ b/crates/sentio-core/src/config.rs @@ -82,6 +82,14 @@ pub struct ServerConfig { pub xclient_enabled: bool, #[serde(default)] pub xclient_allowed_ips: Vec, + /// Proxy IPs trusted to set X-Forwarded-For on API requests. + /// + /// Empty (default) means clients are reached directly and the socket + /// peer address is used for pre-auth rate limiting. Add your load + /// balancer's IP here when the API runs behind an L7 proxy, otherwise + /// every request shares the proxy's single rate-limit bucket. + #[serde(default)] + pub api_trusted_proxies: Vec, pub shutdown_drain_secs: u64, pub shutdown_force_secs: u64, /// Maximum API request body size in megabytes. @@ -128,6 +136,7 @@ impl Default for ServerConfig { proxy_protocol: false, xclient_enabled: false, xclient_allowed_ips: Vec::new(), + api_trusted_proxies: Vec::new(), shutdown_drain_secs: 30, shutdown_force_secs: 60, max_api_body_size_mb: 50, @@ -1087,6 +1096,9 @@ fn apply_single_override( ["SERVER", "XCLIENT_ALLOWED_IPS"] => { config.server.xclient_allowed_ips = parse_csv(value); } + ["SERVER", "API_TRUSTED_PROXIES"] => { + config.server.api_trusted_proxies = parse_csv(value); + } ["SERVER", "SHUTDOWN_DRAIN_SECS"] => { config.server.shutdown_drain_secs = parse_env(full_key, value)?; }