mirror of
https://github.com/truespar/sentio.git
synced 2026-11-23 16:05:43 +00:00
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.
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -36,6 +36,12 @@ impl FromRequestParts<AppState> for AuthContext {
|
||||
parts: &mut Parts,
|
||||
state: &AppState,
|
||||
) -> impl std::future::Future<Output = Result<Self, Self::Rejection>> + 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::<AuthContext>().cloned();
|
||||
|
||||
let pool = state.pool.clone();
|
||||
let auth_header = parts
|
||||
.headers
|
||||
@@ -44,6 +50,9 @@ impl FromRequestParts<AppState> 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<AppState> 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<AppState>,
|
||||
req: axum::extract::Request,
|
||||
next: axum::middleware::Next,
|
||||
) -> Result<axum::response::Response, ApiError> {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -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<IpAddr> {
|
||||
let peer = req
|
||||
.extensions()
|
||||
.get::<ConnectInfo<SocketAddr>>()
|
||||
.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<IpAddr> {
|
||||
let peer_is_proxy = trusted_proxies.iter().any(|p| {
|
||||
p.trim()
|
||||
.parse::<IpAddr>()
|
||||
.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::<IpAddr>().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<AppState>,
|
||||
req: Request,
|
||||
next: Next,
|
||||
) -> Result<Response, ApiError> {
|
||||
// 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::<crate::auth::AuthContext>() {
|
||||
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<AppState>,
|
||||
req: Request,
|
||||
next: Next,
|
||||
) -> Result<Response, ApiError> {
|
||||
let Some(auth) = req.extensions().get::<crate::auth::AuthContext>().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"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<AppState> = 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())
|
||||
|
||||
@@ -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::<std::net::SocketAddr>(),
|
||||
)
|
||||
.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(())
|
||||
|
||||
@@ -24,9 +24,15 @@ pub struct AppState {
|
||||
pub blob_store: Arc<S3BlobStore>,
|
||||
pub config: Arc<SentioConfig>,
|
||||
pub rate_limiter: Arc<KeyedRateLimiter>,
|
||||
/// Pre-auth limiter keyed by client IP; guards token brute force and
|
||||
/// unauthenticated endpoints.
|
||||
pub ip_rate_limiter: Arc<KeyedRateLimiter>,
|
||||
pub kv: Option<RedisPool>,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +82,14 @@ pub struct ServerConfig {
|
||||
pub xclient_enabled: bool,
|
||||
#[serde(default)]
|
||||
pub xclient_allowed_ips: Vec<String>,
|
||||
/// 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<String>,
|
||||
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)?;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user