fix: resolve the client ip in one place and trust private ranges only on cloud (#12685)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-11-26 21:21:10 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 2af161fa1a
commit 0b11d3e9a6
3 changed files with 39 additions and 168 deletions
+28 -18
View File
@@ -1,5 +1,6 @@
//! The address a request comes from, for decisions that must not be spoofable (per-IP rate
//! limits, token IP allowlists).
//! limits) and for the address audit entries record (`request_origin`). Both read it here, so
//! they never disagree about one request.
//!
//! Forwarding headers are believed only when the TCP peer is in `TRUSTED_PROXIES`. Then either
//! `CLIENT_IP_HEADER` names the one header the edge in front writes authoritatively, or
@@ -14,21 +15,21 @@ use axum::extract::{ConnectInfo, FromRequestParts};
use axum::http::{request::Parts, HeaderMap, HeaderName};
use ipnet::IpNet;
/// Loopback, private and link-local networks: where a reverse proxy in front of Windmill
/// usually connects from. Anything else in front (a CDN, a public load balancer) must be listed
/// in `TRUSTED_PROXIES`, or its own address is taken as the client's. Job code on the same
/// network is trusted too, so a deployment where jobs can reach the server directly should list
/// its proxy's exact address instead.
const DEFAULT_TRUSTED_PROXIES: &[&str] = &[
"127.0.0.0/8",
"::1/128",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"169.254.0.0/16",
"fc00::/7",
"fe80::/10",
];
/// Loopback only on a self-hosted instance: it is often reached directly from a private network,
/// whose clients could otherwise name any address they like. A reverse proxy on a private
/// address must be listed in `TRUSTED_PROXIES`, or its own address is taken as the client's.
const DEFAULT_TRUSTED_PROXIES: &[&str] = &["127.0.0.0/8", "::1/128"];
/// Added on cloud, where every request arrives through our own load balancer.
const CLOUD_TRUSTED_PROXIES: &[&str] =
&["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"];
fn default_trusted_proxies(cloud_hosted: bool) -> String {
let mut nets = DEFAULT_TRUSTED_PROXIES.to_vec();
if cloud_hosted {
nets.extend(CLOUD_TRUSTED_PROXIES);
}
nets.join(",")
}
pub struct ClientIpConfig {
pub trusted: Vec<IpNet>,
@@ -42,7 +43,7 @@ pub struct ClientIpConfig {
pub static CLIENT_IP_CONFIG: LazyLock<ClientIpConfig> = LazyLock::new(|| {
let trusted = match std::env::var("TRUSTED_PROXIES") {
Ok(v) => parse_trusted_proxies(&v),
Err(_) => parse_trusted_proxies(&DEFAULT_TRUSTED_PROXIES.join(",")),
Err(_) => parse_trusted_proxies(&default_trusted_proxies(*crate::worker::CLOUD_HOSTED)),
};
let header = std::env::var("CLIENT_IP_HEADER")
.ok()
@@ -194,8 +195,17 @@ mod tests {
}
}
/// Cloud's default, which trusts the private ranges most cases here put a proxy on.
fn defaults() -> ClientIpConfig {
cfg(&DEFAULT_TRUSTED_PROXIES.join(","), None)
cfg(&default_trusted_proxies(true), None)
}
#[test]
fn self_hosted_default_trusts_only_loopback() {
let c = cfg(&default_trusted_proxies(false), None);
let h = headers(&[("x-forwarded-for", b"5.5.5.5")]);
assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("10.0.0.1"));
assert_eq!(resolve_client_ip(ip("127.0.0.1"), &h, &c), ip("5.5.5.5"));
}
#[test]
+4 -146
View File
@@ -2,13 +2,11 @@
//! recorded on the audit entries it writes.
use std::net::IpAddr;
use std::sync::{Arc, LazyLock};
use std::sync::Arc;
use http::HeaderMap;
use ipnet::IpNet;
use crate::utils::truncate_chars;
use crate::worker::CLOUD_HOSTED;
const USER_AGENT_MAX_CHARS: usize = 512;
@@ -33,46 +31,14 @@ pub fn current() -> Option<Arc<RequestOrigin>> {
REQUEST_ORIGIN.try_with(|o| o.clone()).ok()
}
/// The proxies whose forwarding headers are believed. `TRUSTED_PROXIES` (comma-separated
/// addresses or CIDRs, empty for none) replaces the default: loopback, plus the private
/// ranges on cloud, where every request arrives through our own load balancer. Private
/// ranges are not trusted by default elsewhere: a self-hosted instance is often reached
/// directly from a private network, and its clients could then name any address they like.
static TRUSTED_PROXIES: LazyLock<Vec<IpNet>> =
LazyLock::new(|| match std::env::var("TRUSTED_PROXIES") {
Ok(v) => parse_trusted_proxies(&v),
Err(_) => {
let mut nets = vec!["127.0.0.0/8", "::1/128"];
if *CLOUD_HOSTED {
nets.extend(["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]);
}
nets.into_iter().filter_map(|n| n.parse().ok()).collect()
}
});
fn parse_trusted_proxies(v: &str) -> Vec<IpNet> {
v.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.filter_map(|s| {
let parsed = s
.parse::<IpNet>()
.ok()
.or_else(|| s.parse::<IpAddr>().ok().map(IpNet::from));
if parsed.is_none() {
tracing::warn!("Ignoring invalid TRUSTED_PROXIES entry: {s}");
}
parsed
})
.collect()
}
impl RequestOrigin {
/// `peer` is the address the connection came from; `None` when the request did not arrive
/// over a socket, and then no header is believed either.
pub fn from_request(peer: Option<IpAddr>, headers: &HeaderMap) -> Self {
Self {
client_ip: peer.map(|p| client_ip(p, headers, &TRUSTED_PROXIES)),
client_ip: peer.map(|p| {
crate::client_ip::resolve_client_ip(p, headers, &crate::client_ip::CLIENT_IP_CONFIG)
}),
user_agent: headers
.get(http::header::USER_AGENT)
.and_then(|v| v.to_str().ok())
@@ -82,111 +48,3 @@ impl RequestOrigin {
}
}
}
fn parse_hop(s: &str) -> Option<IpAddr> {
let s = s.trim();
s.parse::<IpAddr>()
.ok()
.or_else(|| s.parse::<std::net::SocketAddr>().ok().map(|a| a.ip()))
.map(|ip| ip.to_canonical())
}
/// The first address that is not a trusted proxy, walking `X-Forwarded-For` back from the
/// peer: each trusted hop vouches for the address before it, an untrusted one for nothing,
/// so entries left of it are whatever the client wrote. `X-Real-IP` is read only when there
/// is no `X-Forwarded-For`.
fn client_ip(peer: IpAddr, headers: &HeaderMap, trusted: &[IpNet]) -> IpAddr {
let is_trusted = |ip: &IpAddr| trusted.iter().any(|n| n.contains(ip));
let mut current = peer.to_canonical();
if !is_trusted(&current) {
return current;
}
// Bytes that are not UTF-8 are kept as entries that fail to parse, so they stop the walk
// rather than vanish and let the client's own entries, or X-Real-IP, stand in.
let values: Vec<String> = headers
.get_all("x-forwarded-for")
.iter()
.map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned())
.collect();
let hops: Vec<&str> = values.iter().flat_map(|v| v.split(',')).collect();
if values.is_empty() {
if let Some(ip) = headers
.get("x-real-ip")
.and_then(|v| v.to_str().ok())
.and_then(parse_hop)
{
return ip;
}
return current;
}
for hop in hops.iter().rev() {
if !is_trusted(&current) {
break;
}
match parse_hop(hop) {
Some(ip) => current = ip,
None => break,
}
}
current
}
#[cfg(test)]
mod tests {
use super::*;
fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap {
let mut h = HeaderMap::new();
for (k, v) in pairs {
h.append(*k, v.parse().unwrap());
}
h
}
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
#[test]
fn forwarded_addresses_are_believed_only_through_trusted_hops() {
let trusted = parse_trusted_proxies("10.0.0.0/8, 127.0.0.1");
let xff = headers(&[("x-forwarded-for", "6.6.6.6, 1.2.3.4, 10.0.0.2")]);
// An untrusted peer's headers say nothing.
assert_eq!(client_ip(ip("8.8.8.8"), &xff, &trusted), ip("8.8.8.8"));
// Trusted peer and trusted hop: the client is the first untrusted address, and the
// entry the client itself wrote left of it is ignored.
assert_eq!(client_ip(ip("10.0.0.1"), &xff, &trusted), ip("1.2.3.4"));
// Every hop trusted: the leftmost one.
let all_trusted = headers(&[("x-forwarded-for", "10.1.1.1, 10.0.0.2")]);
assert_eq!(
client_ip(ip("127.0.0.1"), &all_trusted, &trusted),
ip("10.1.1.1")
);
// An unparseable hop stops the walk at the last address vouched for.
let garbage = headers(&[("x-forwarded-for", "1.2.3.4, unknown")]);
assert_eq!(
client_ip(ip("10.0.0.1"), &garbage, &trusted),
ip("10.0.0.1")
);
// A hop that is not UTF-8 stops the walk too, and does not let X-Real-IP in.
let mut binary = headers(&[("x-real-ip", "5.5.5.5")]);
binary.append(
"x-forwarded-for",
http::HeaderValue::from_bytes(b"\x80, 1.2.3.4").unwrap(),
);
assert_eq!(client_ip(ip("10.0.0.1"), &binary, &trusted), ip("1.2.3.4"));
let mut binary_last = headers(&[("x-real-ip", "5.5.5.5")]);
binary_last.append(
"x-forwarded-for",
http::HeaderValue::from_bytes(b"1.2.3.4, \x80").unwrap(),
);
assert_eq!(client_ip(ip("10.0.0.1"), &binary_last, &trusted), ip("10.0.0.1"));
// X-Real-IP, only from a trusted peer and only without X-Forwarded-For.
let real = headers(&[("x-real-ip", "5.5.5.5")]);
assert_eq!(client_ip(ip("10.0.0.1"), &real, &trusted), ip("5.5.5.5"));
assert_eq!(client_ip(ip("8.8.8.8"), &real, &trusted), ip("8.8.8.8"));
// Nothing trusted.
assert_eq!(client_ip(ip("10.0.0.1"), &xff, &[]), ip("10.0.0.1"));
}
}
+7 -4
View File
@@ -234,12 +234,15 @@ Symbols, not line numbers, are cited: they drift less.
`"true"` enables it when set.
- **The client IP** (`windmill-common/src/client_ip.rs`, the `ClientIp` extractor) is the TCP
peer unless that peer is in `TRUSTED_PROXIES` (comma-separated CIDRs; unset means loopback,
private and link-local ranges; `none` trusts nothing). Behind a trusted peer, `X-Forwarded-For`
plus the private ranges on cloud; empty or `none` trusts nothing). Audit entries record the
same address (`request_origin.rs` calls it), so a login refusal and its audit row agree. A
self-hosted instance behind a reverse proxy on a private address must list that proxy, or
the proxy is every request's client: trusting private ranges by default would let anyone on
the network in front name any address. Behind a trusted peer, `X-Forwarded-For`
is read from the right up to the first untrusted hop, or, with `CLIENT_IP_HEADER` set, only that
header (`CloudFront-Viewer-Address`, `CF-Connecting-IP`, an nginx `X-Real-IP`). `X-Real-IP` is
never read implicitly: Caddy and most ingresses pass a client's own through. A CDN in front of
the load balancer (CloudFront on app.windmill.dev) needs `CLIENT_IP_HEADER` or its ranges in
`TRUSTED_PROXIES`, or its edge address is the client. The private-range default also trusts
job containers that can reach the server directly; such a deployment should list its proxy's
exact address. Only the main API server carries the peer: a router called without connect
`TRUSTED_PROXIES`, or its edge address is the client. On cloud, the private-range default
also trusts job containers that can reach the server directly. Only the main API server carries the peer: a router called without connect
info (tests, internal dispatch) sees `None`, and per-IP decisions skip or refuse it.