Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Trusted proxy client IP

This example uses TrustedProxyClientIpKeyExtractor with an application-supplied peer policy. A trusted proxy must remove or overwrite every supported client-IP header before forwarding the request to the application.

cargo run --example trusted_proxy_client_ip --features axum,memory

The server listens on http://127.0.0.1:3001.

Complete source

use std::{
    error::Error,
    net::{IpAddr, SocketAddr},
    time::Duration,
};

use axum::{Router, routing::get};
use tower_rate_limiter::{FixedWindow, MemoryStore, RateLimitLayer, TrustedProxyClientIpKeyExtractor};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Replace this documentation address with application-owned proxy configuration. The proxy
    // must remove or overwrite every supported client-IP Header, and ingress must prevent clients
    // from bypassing it through an address accepted by this policy.
    let trusted_proxy: IpAddr = "192.0.2.10".parse()?;
    let key_extractor = TrustedProxyClientIpKeyExtractor::new(move |peer| peer == trusted_proxy);
    let limiter = RateLimitLayer::builder(key_extractor)
        .policy_name("client-ip-limit")
        .with_policy(FixedWindow::new(MemoryStore::new(), 100, Duration::from_secs(60))?)
        .build()?;
    let app = Router::new().route("/health", get(|| async { "ok" })).layer(limiter);

    let address: SocketAddr = "127.0.0.1:3001".parse()?;
    let listener = tokio::net::TcpListener::bind(address).await?;
    println!("listening on http://{address}");
    axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
    Ok(())
}

The example’s documentation address is a placeholder; replace it with application configuration for the actual proxy address or CIDR set. The policy checks the Axum ConnectInfo peer before the extractor accepts Forwarded, X-Forwarded-For, X-Real-IP, or CF-Connecting-IP. Untrusted peers use their socket IP even if they send those Headers. Missing peer information is rejected.

Parsing still does not authenticate Header contents. Every trusted proxy must sanitize all four supported Headers, and application ingress must prevent direct clients from connecting through an address accepted by the policy. The library does not load proxy configuration from environment variables.