feat: make client IP trust settable from the instance settings (#12755)

* feat: make client IP trust settable from the instance settings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep the space before the allowlist clause on the client ip warning

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: reload client ip trust on mcp servers and address review nits

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: let an empty CLIENT_IP_HEADER fix the default and keep private trust when adding a proxy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: warn on token ip allowlists only when no trusted proxies are configured

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: warn while a whole private range is trusted, not only when nothing is set

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: narrow trusted proxies to the listed ones from the private-range warning

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep subnets inside a private range when narrowing trusted proxies

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: show a saved client ip value the environment overrides

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: serialize client ip reloads and retry a failed settings read

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: clear trust_cloudflare on empty, validate non-text client ip values, read diagnostics from one trust

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-11-30 08:58:54 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent dd1e046397
commit de14e74ec0
13 changed files with 1072 additions and 121 deletions
+19
View File
@@ -1619,6 +1619,22 @@ Windmill Community Edition {GIT_VERSION}
// internal url so the workers get past that oneshot before it builds its router.
// Ordering `server_f` first makes them wait out the whole build instead.
if mcp_mode {
// No monitor loop delivers setting changes here, and the MCP server enforces token IP
// allowlists too: a proxy the main API stopped trusting must not stay trusted here.
if let Some(db) = conn.as_sql() {
let db = db.clone();
let mut killpill_rx = killpill_tx.subscribe();
tokio::spawn(async move {
loop {
tokio::select! {
_ = killpill_rx.recv() => return,
_ = tokio::time::sleep(Duration::from_secs(*LISTEN_NEW_EVENTS_INTERVAL_SEC)) => {
windmill_common::client_ip::reload(&db).await;
}
}
}
});
}
futures::try_join!(workers_f, server_f)?;
} else {
futures::try_join!(
@@ -2078,6 +2094,9 @@ async fn process_notify_event(
REQUIRE_TOTP_SETTING => {
load_require_totp(db).await;
}
k if windmill_common::client_ip::SETTING_KEYS.contains(&k) => {
windmill_common::client_ip::reload(db).await;
}
windmill_common::global_settings::WORKSPACE_ROLES_SETTING => {
windmill_common::roles::invalidate_all_roles_cache();
}
+3
View File
@@ -317,6 +317,9 @@ pub async fn initial_load(
false,
|v| async move { apply_mcp_external_idp(v) },
);
// Every mode: a worker's API is served too, and the trust must be in place before the
// server accepts requests.
pass.action(windmill_common::client_ip::reload(db));
pass.setting(API_BASE_URL_SETTING, false, |v| async move {
apply_api_base_url(v)
});
+19
View File
@@ -150,6 +150,7 @@ pub fn global_service() -> Router {
.route("/local", get(get_local_settings))
.route("/envs", get(get_local_settings))
.route("/client_ip_diagnostics", get(client_ip_diagnostics))
.route("/client_ip_trust", get(client_ip_trust))
.route(
"/global/{key}",
post(set_global_setting).get(get_global_setting),
@@ -817,6 +818,15 @@ async fn client_ip_diagnostics(
)))
}
/// Whether a whole private range is trusted as proxies, for whoever is restricting a token to IP
/// addresses: a host on that network can then claim an allowed one. Any signed-in user, not
/// anonymous callers, who would learn whether forwarding headers from inside are believed.
async fn client_ip_trust(_authed: ApiAuthed) -> Json<serde_json::Value> {
Json(serde_json::json!({
"private_ranges_trusted": windmill_common::client_ip::private_ranges_trusted()
}))
}
#[derive(serde::Deserialize)]
pub struct Value {
pub value: Option<serde_json::Value>,
@@ -1021,6 +1031,11 @@ async fn run_setting_post_write_hook(db: &DB, key: &str) -> error::Result<()> {
if key == WORKSPACE_ROLES_SETTING {
windmill_common::roles::after_instance_roles_write(db).await?;
}
// The other servers apply it on the settings change event; this one at once, so the page
// that saved it reads the new trust back.
if windmill_common::client_ip::SETTING_KEYS.contains(&key) {
windmill_common::client_ip::reload(db).await;
}
Ok(())
}
@@ -1032,6 +1047,10 @@ async fn run_setting_pre_write_hook(
value: &serde_json::Value,
) -> error::Result<()> {
match key {
k if windmill_common::client_ip::SETTING_KEYS.contains(&k) => {
windmill_common::client_ip::validate_setting(k, value)
.map_err(|e| error::Error::BadRequest(format!("{k}: {e}")))?;
}
#[cfg(feature = "oauth2")]
windmill_common::global_settings::OAUTH_SETTING => {
let previous = windmill_common::global_settings::load_value_from_global_settings(
+59
View File
@@ -2287,6 +2287,29 @@ paths:
application/json:
schema: {}
/settings/client_ip_trust:
get:
summary: whether a whole private range is trusted as proxies
description: |
Any signed-in user. True while a whole private range is trusted as proxies (the default
with nothing configured, `private`, or a range such as 10.0.0.0/8): a host on the
instance's private network can then claim an address a token's allowlist accepts.
operationId: getClientIpTrust
tags:
- setting
responses:
"200":
description: whether a whole private range is trusted as proxies
content:
application/json:
schema:
type: object
properties:
private_ranges_trusted:
type: boolean
required:
- private_ranges_trusted
/settings/client_ip_diagnostics:
get:
summary: what the server believes about the caller's client IP and the proxies it has seen
@@ -35198,6 +35221,9 @@ components:
description: as token IP allowlists see it
trusted_proxies_set:
type: boolean
private_ranges_trusted:
type: boolean
description: a whole private range is trusted, so any host on the private network can name its own client address
client_ip_header:
type: string
nullable: true
@@ -35208,6 +35234,37 @@ components:
allOf:
- $ref: "#/components/schemas/ClientIpTrustView"
nullable: true
configuration:
description: what the trust is built from; a value whose environment variable is set cannot be changed from the settings
type: object
properties:
trusted_proxies:
type: object
properties:
value:
type: string
nullable: true
from_env:
type: boolean
required: [from_env]
trust_cloudflare:
type: object
properties:
value:
type: boolean
from_env:
type: boolean
required: [value, from_env]
client_ip_header:
type: object
properties:
value:
type: string
nullable: true
from_env:
type: boolean
required: [from_env]
required: [trusted_proxies, trust_cloudflare, client_ip_header]
forwarders:
type: array
items:
@@ -35230,6 +35287,8 @@ components:
- requests
required:
- trusted_proxies_set
- private_ranges_trusted
- configuration
- enforced
- forwarders
+488 -90
View File
@@ -65,6 +65,17 @@ const CLOUDFLARE: &[&str] = &[
const HOST_REFRESH: Duration = Duration::from_secs(15);
/// The global settings the trust is built from. Each is overridden by its environment variable
/// (`TRUSTED_PROXIES`, `TRUST_CLOUDFLARE`, `CLIENT_IP_HEADER`) when that is set.
pub const TRUSTED_PROXIES_SETTING: &str = "trusted_proxies";
pub const TRUST_CLOUDFLARE_SETTING: &str = "trust_cloudflare";
pub const CLIENT_IP_HEADER_SETTING: &str = "client_ip_header";
pub const SETTING_KEYS: &[&str] = &[
TRUSTED_PROXIES_SETTING,
TRUST_CLOUDFLARE_SETTING,
CLIENT_IP_HEADER_SETTING,
];
pub struct ClientIpConfig {
trusted: Vec<IpNet>,
/// Hostnames in `TRUSTED_PROXIES` (a compose service such as `caddy`), re-resolved every
@@ -79,8 +90,12 @@ pub struct ClientIpConfig {
static CLOUDFLARE_NETS: LazyLock<Vec<IpNet>> = LazyLock::new(|| nets(CLOUDFLARE).collect());
impl ClientIpConfig {
fn new(trusted_proxies: &str, cloudflare: bool, header: Option<HeaderName>) -> Self {
let (mut trusted, hosts) = parse_trusted_proxies(trusted_proxies);
fn new(
mut trusted: Vec<IpNet>,
hosts: Vec<String>,
cloudflare: bool,
header: Option<HeaderName>,
) -> Self {
if cloudflare {
trusted.extend(nets(CLOUDFLARE));
}
@@ -109,33 +124,111 @@ impl ClientIpConfig {
}
}
/// A value the trust is built from, and whether its environment variable set it, which makes
/// the setting read-only on the Client IP page.
#[derive(Serialize, Clone, Debug, PartialEq, Eq)]
pub struct Configured<T> {
pub value: T,
pub from_env: bool,
}
#[derive(Serialize, Clone, Debug, PartialEq, Eq)]
pub struct ClientIpConfiguration {
pub trusted_proxies: Configured<Option<String>>,
pub trust_cloudflare: Configured<bool>,
pub client_ip_header: Configured<Option<String>>,
}
pub struct ClientIpSettings {
enforced: ClientIpConfig,
/// `None` when it is the enforced view.
attributed: Option<ClientIpConfig>,
trusted_proxies_set: bool,
/// A whole private range is trusted (the default, `private`, or e.g. `10.0.0.0/8`): any host
/// on that network can then name its own client address. Listing the proxies themselves is
/// what closes it, not setting some value.
private_ranges_trusted: bool,
configuration: ClientIpConfiguration,
}
impl ClientIpSettings {
#[cfg(test)]
fn new(trusted_proxies: Option<&str>, cloudflare: bool, header: Option<HeaderName>) -> Self {
let configuration = ClientIpConfiguration {
trusted_proxies: Configured { value: trusted_proxies.map(str::to_string), from_env: true },
trust_cloudflare: Configured { value: cloudflare, from_env: true },
client_ip_header: Configured {
value: header.as_ref().map(|h| h.to_string()),
from_env: true,
},
};
Self::build(trusted_proxies, false, cloudflare, header, configuration)
}
/// `strict` (a stored setting rather than an environment variable) also drops the entries
/// [`validate_trusted_proxies`] refuses, should one reach the database without the check.
fn build(
trusted_proxies: Option<&str>,
strict: bool,
cloudflare: bool,
header: Option<HeaderName>,
configuration: ClientIpConfiguration,
) -> Self {
// The accepted risk the module doc describes: never a public range here, and an explicit
// list always replaces this default rather than adding to it.
let list = match trusted_proxies {
Some(v) => v.to_string(),
None => [LOOPBACK, PRIVATE].concat().join(","),
let (trusted, hosts) = match trusted_proxies {
Some(v) => {
let p = parse_trusted_proxies(v, strict);
let source = if strict { "trusted_proxies setting" } else { "TRUSTED_PROXIES" };
for e in &p.errors {
tracing::error!("{source}: ignoring {e}");
}
(p.trusted, p.hosts)
}
None => (nets(LOOPBACK).chain(nets(PRIVATE)).collect(), vec![]),
};
// Cloudflare never reaches the enforced view: a Worker sending to an origin outside a
// Cloudflare zone comes from the same ranges and may set CF-Connecting-IP itself, so only
// the origin's own proof of the zone (e.g. authenticated origin pulls) could vouch for it.
let enforced = ClientIpConfig::new(&list, false, header.clone());
let attributed = cloudflare.then(|| ClientIpConfig::new(&list, true, header));
let private_ranges_trusted =
nets(PRIVATE).any(|p| trusted.iter().any(|t| t.contains(&p)));
let enforced = ClientIpConfig::new(trusted.clone(), hosts.clone(), false, header.clone());
let attributed = cloudflare.then(|| ClientIpConfig::new(trusted, hosts, true, header));
Self {
enforced,
attributed,
trusted_proxies_set: trusted_proxies.is_some(),
private_ranges_trusted,
configuration,
}
}
/// Each value from its environment variable when that is set, else from its global setting.
fn from_env_and_stored(stored: &Stored) -> Self {
let env = &*ENV;
let (trusted_proxies, tp_env) = match &env.trusted_proxies {
Some(v) => (Some(v.clone()), true),
None => (stored.trusted_proxies.clone(), false),
};
let (cloudflare, cf_env) = match env.trust_cloudflare {
Some(v) => (v, true),
None => (stored.trust_cloudflare, false),
};
let (header, h_env) = match &env.header {
Some(h) => (h.clone(), true),
None => (stored.header.clone(), false),
};
let configuration = ClientIpConfiguration {
trusted_proxies: Configured { value: trusted_proxies.clone(), from_env: tp_env },
trust_cloudflare: Configured { value: cloudflare, from_env: cf_env },
client_ip_header: Configured {
value: header.as_ref().map(|h| h.to_string()),
from_env: h_env,
},
};
Self::build(trusted_proxies.as_deref(), !tp_env, cloudflare, header, configuration)
}
pub fn enforced(&self) -> &ClientIpConfig {
&self.enforced
}
@@ -143,6 +236,52 @@ impl ClientIpSettings {
pub fn attributed(&self) -> &ClientIpConfig {
self.attributed.as_ref().unwrap_or(&self.enforced)
}
fn configs(&self) -> impl Iterator<Item = &ClientIpConfig> {
[Some(&self.enforced), self.attributed.as_ref()]
.into_iter()
.flatten()
}
fn describe(&self) -> String {
let describe = |c: &ClientIpConfig| {
let mut parts: Vec<String> = c
.trusted
.iter()
.filter(|n| !c.cloudflare || !CLOUDFLARE_NETS.contains(n))
.map(|n| n.to_string())
.collect();
parts.extend(c.hosts.iter().cloned());
if c.cloudflare {
parts.push("Cloudflare".to_string());
}
if parts.is_empty() {
"no proxy".to_string()
} else {
parts.join(", ")
}
};
let header = match &self.enforced.header {
Some(h) => format!(", reading the client from {h}"),
None => String::new(),
};
match &self.attributed {
None => format!("trusting {} as proxies{header}", describe(&self.enforced)),
Some(a) => format!(
"trusting {} as proxies for audit entries and login rate limits, {} for token IP \
allowlists{header}",
describe(a),
describe(&self.enforced)
),
}
}
}
/// The environment variables, read once: they outrank the global settings for good.
struct EnvInputs {
trusted_proxies: Option<String>,
trust_cloudflare: Option<bool>,
header: Option<Option<HeaderName>>,
}
/// `TRUSTED_PROXIES`: comma-separated IPs, CIDRs, hostnames and `private` (loopback plus the
@@ -151,26 +290,70 @@ impl ClientIpSettings {
/// `CLIENT_IP_HEADER`: a header such as `CloudFront-Viewer-Address`, `CF-Connecting-IP` or
/// `X-Real-IP` that the trusted edge overwrites on every request, read instead of
/// `X-Forwarded-For`.
pub static CLIENT_IP_SETTINGS: LazyLock<ClientIpSettings> = LazyLock::new(|| {
let header = std::env::var("CLIENT_IP_HEADER")
static ENV: LazyLock<EnvInputs> = LazyLock::new(|| EnvInputs {
trusted_proxies: std::env::var("TRUSTED_PROXIES").ok(),
trust_cloudflare: std::env::var("TRUST_CLOUDFLARE")
.ok()
.filter(|v| !v.trim().is_empty())
.and_then(|v| match HeaderName::try_from(v.trim()) {
Ok(h) => Some(h),
Err(_) => {
tracing::error!("CLIENT_IP_HEADER: {v:?} is not a header name, ignoring it");
None
}
});
let cloudflare = std::env::var("TRUST_CLOUDFLARE")
.is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "true" | "1" | "yes"));
ClientIpSettings::new(
std::env::var("TRUSTED_PROXIES").ok().as_deref(),
cloudflare,
header,
)
.map(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "true" | "1" | "yes")),
// Set but empty or unreadable still fixes it, to X-Forwarded-For: the stored setting never
// takes over from a variable that is set.
header: std::env::var("CLIENT_IP_HEADER").ok().map(|v| {
if v.trim().is_empty() {
return None;
}
HeaderName::try_from(v.trim())
.map_err(|_| {
tracing::error!("CLIENT_IP_HEADER: {v:?} is not a header name, ignoring it")
})
.ok()
}),
});
/// The global settings' values, as stored.
#[derive(Default)]
struct Stored {
trusted_proxies: Option<String>,
trust_cloudflare: bool,
header: Option<HeaderName>,
}
impl Stored {
fn from_values(
trusted_proxies: Option<&serde_json::Value>,
trust_cloudflare: Option<&serde_json::Value>,
header: Option<&serde_json::Value>,
) -> Self {
let text = |v: Option<&serde_json::Value>| {
v.and_then(|v| v.as_str())
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
};
Stored {
trusted_proxies: text(trusted_proxies),
trust_cloudflare: trust_cloudflare.and_then(|v| v.as_bool()).unwrap_or(false),
header: text(header).and_then(|h| match parse_client_ip_header(&h) {
Ok(h) => Some(h),
Err(e) => {
tracing::error!("client_ip_header setting: {e}, ignoring it");
None
}
}),
}
}
}
/// Swapped whole when a setting changes ([`apply_stored`]), so a request reads one consistent
/// trust. Until the settings are first read it holds the environment variables alone.
static CLIENT_IP_SETTINGS: LazyLock<ArcSwap<ClientIpSettings>> = LazyLock::new(|| {
ArcSwap::from_pointee(ClientIpSettings::from_env_and_stored(&Stored::default()))
});
/// The trust in force now.
pub fn current() -> arc_swap::Guard<Arc<ClientIpSettings>> {
CLIENT_IP_SETTINGS.load()
}
fn nets(list: &'static [&'static str]) -> impl Iterator<Item = IpNet> {
list.iter()
.map(|s| s.parse().expect("valid built-in network"))
@@ -187,27 +370,100 @@ fn is_hostname(s: &str) -> bool {
})
}
fn parse_trusted_proxies(v: &str) -> (Vec<IpNet>, Vec<String>) {
let (mut trusted, mut hosts) = (vec![], vec![]);
struct ParsedProxies {
trusted: Vec<IpNet>,
hosts: Vec<String>,
/// The entries left out, each with why.
errors: Vec<String>,
}
/// `strict` also refuses what would trust far more than a proxy: every address, or a range
/// overlapping Cloudflare's, which any Cloudflare customer's Worker sends from and which
/// `TRUST_CLOUDFLARE` admits to the attributed view only.
fn parse_trusted_proxies(v: &str, strict: bool) -> ParsedProxies {
let mut p = ParsedProxies { trusted: vec![], hosts: vec![], errors: vec![] };
if v.trim().eq_ignore_ascii_case("none") {
return (trusted, hosts);
return p;
}
for s in v.split(',').map(str::trim).filter(|s| !s.is_empty()) {
if s.eq_ignore_ascii_case("private") {
trusted.extend(nets(LOOPBACK).chain(nets(PRIVATE)));
p.trusted.extend(nets(LOOPBACK).chain(nets(PRIVATE)));
} else if let Some(net) = s
.parse::<IpNet>()
.ok()
.or_else(|| s.parse::<IpAddr>().ok().map(IpNet::from))
{
trusted.push(net);
} else if is_hostname(s) {
hosts.push(s.to_ascii_lowercase());
if strict && net.prefix_len() == 0 {
p.errors.push(format!(
"{s:?}: it trusts every address, so any client could name its own"
));
} else if let Some(cf) = strict
.then(|| {
CLOUDFLARE_NETS
.iter()
.find(|cf| cf.contains(&net.network()) || net.contains(&cf.network()))
})
.flatten()
{
p.errors.push(format!(
"{s:?}: it overlaps Cloudflare's range {cf}, which any Cloudflare customer's \
Worker sends from; trust Cloudflare with TRUST_CLOUDFLARE instead"
));
} else {
p.trusted.push(net);
}
} else if strict && s.eq_ignore_ascii_case("none") {
p.errors
.push("\"none\": it trusts no proxy only on its own, not among other entries".into());
} else if is_hostname(s)
&& !(strict
&& s.rsplit('.')
.next()
.is_some_and(|l| l.chars().all(|c| c.is_ascii_digit())))
{
p.hosts.push(s.to_ascii_lowercase());
} else {
tracing::error!("TRUSTED_PROXIES: ignoring invalid entry {s:?}");
p.errors.push(format!(
"{s:?}: not an IP address, a CIDR, a hostname or \"private\""
));
}
}
(trusted, hosts)
p
}
/// What a write of the `trusted_proxies` setting must pass: every entry is kept, none refused.
pub fn validate_trusted_proxies(v: &str) -> Result<(), String> {
let p = parse_trusted_proxies(v, true);
if p.errors.is_empty() {
Ok(())
} else {
Err(p.errors.join("; "))
}
}
fn parse_client_ip_header(v: &str) -> Result<HeaderName, String> {
let h = HeaderName::try_from(v.trim()).map_err(|_| format!("{v:?} is not a header name"))?;
// Read as one address, a multi-hop X-Forwarded-For would always fall back to the peer.
if h == "x-forwarded-for" {
return Err(
"X-Forwarded-For is read by default, from the right: leave the header empty".into(),
);
}
Ok(h)
}
/// Checks a write of one of [`SETTING_KEYS`]. `null` and an empty string clear the setting.
pub fn validate_setting(key: &str, value: &serde_json::Value) -> Result<(), String> {
use serde_json::Value;
match (key, value) {
(_, Value::Null) => Ok(()),
(_, Value::String(s)) if s.trim().is_empty() => Ok(()),
(TRUST_CLOUDFLARE_SETTING, Value::Bool(_)) => Ok(()),
(TRUST_CLOUDFLARE_SETTING, _) => Err("must be true or false".into()),
(TRUSTED_PROXIES_SETTING, Value::String(s)) => validate_trusted_proxies(s),
(CLIENT_IP_HEADER_SETTING, Value::String(s)) => parse_client_ip_header(s).map(|_| ()),
_ => Err("must be a string".into()),
}
}
async fn resolve_hosts(cfg: &ClientIpConfig) {
@@ -242,72 +498,155 @@ async fn resolve_hosts(cfg: &ClientIpConfig) {
cfg.resolved.store(Arc::new(resolved));
}
async fn resolve_all_hosts(s: &ClientIpSettings) {
for c in s.configs().filter(|c| !c.hosts.is_empty()) {
resolve_hosts(c).await;
}
}
static STARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
fn warn_if_private_trusted(s: &ClientIpSettings) {
if s.private_ranges_trusted {
tracing::warn!(
"Client IP: a whole private range is trusted as proxies, so any host on the private \
network, a Windmill job included, can name its own client address, which token IP \
allowlists then accept. List your reverse proxies' addresses on the Client IP \
instance settings page (or in TRUSTED_PROXIES) to trust only them."
);
}
}
/// Logs what the server trusts and, for hostnames in `TRUSTED_PROXIES`, resolves them before
/// the server accepts requests, then keeps them resolved until `killpill`.
/// the server accepts requests, then keeps those of the trust in force resolved until
/// `killpill`.
pub async fn init(mut killpill: tokio::sync::broadcast::Receiver<()>) {
if LOCAL_JOBS_ONLY.load(std::sync::atomic::Ordering::Relaxed) {
tracing::info!("Client IP: this process serves only its own jobs, no caller is a proxy");
return;
}
let s = &*CLIENT_IP_SETTINGS;
let describe = |c: &ClientIpConfig| {
let mut parts: Vec<String> = c
.trusted
.iter()
.filter(|n| !c.cloudflare || !nets(CLOUDFLARE).any(|cf| cf == **n))
.map(|n| n.to_string())
.collect();
parts.extend(c.hosts.iter().cloned());
if c.cloudflare {
parts.push("Cloudflare".to_string());
}
if parts.is_empty() {
"no proxy".to_string()
} else {
parts.join(", ")
}
};
match &s.attributed {
None => tracing::info!("Client IP: trusting {} as proxies", describe(&s.enforced)),
Some(a) => tracing::info!(
"Client IP: trusting {} as proxies for audit entries and login rate limits, {} for \
token IP allowlists",
describe(a),
describe(&s.enforced)
),
}
if !s.trusted_proxies_set {
tracing::warn!(
"Client IP: TRUSTED_PROXIES is unset, so any host on the private network, a Windmill \
job included, can name its own client address, which token IP allowlists then \
accept. Set TRUSTED_PROXIES to your reverse proxies' addresses to trust only them."
);
}
let configs: Vec<&'static ClientIpConfig> = [Some(&s.enforced), s.attributed.as_ref()]
.into_iter()
.flatten()
.filter(|c| !c.hosts.is_empty())
.collect();
if configs.is_empty() {
return;
}
for c in &configs {
resolve_hosts(c).await;
}
let s = CLIENT_IP_SETTINGS.load_full();
tracing::info!("Client IP: {}", s.describe());
warn_if_private_trusted(&s);
resolve_all_hosts(&s).await;
STARTED.store(true, std::sync::atomic::Ordering::Relaxed);
tokio::spawn(async move {
loop {
tokio::select! {
_ = killpill.recv() => return,
_ = tokio::time::sleep(HOST_REFRESH) => {
for c in &configs {
resolve_hosts(c).await;
}
resolve_all_hosts(&CLIENT_IP_SETTINGS.load_full()).await;
}
}
}
});
}
/// Names the stored settings an environment variable overrides, once per distinct set: the
/// settings are read again on every reload, every few seconds on an MCP server.
fn warn_if_shadowed(stored: &Stored) {
static LAST: Mutex<Vec<&'static str>> = Mutex::new(vec![]);
let env = &*ENV;
let mut shadowed = vec![];
if env.trusted_proxies.is_some() && stored.trusted_proxies.is_some() {
shadowed.push("TRUSTED_PROXIES");
}
if env.trust_cloudflare.is_some_and(|e| e != stored.trust_cloudflare) {
shadowed.push("TRUST_CLOUDFLARE");
}
if env.header.is_some() && stored.header.is_some() {
shadowed.push("CLIENT_IP_HEADER");
}
let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
if *last != shadowed {
if !shadowed.is_empty() && !LOCAL_JOBS_ONLY.load(std::sync::atomic::Ordering::Relaxed) {
tracing::warn!(
"Client IP: {} set in the environment, which overrides the value stored on the \
Client IP instance settings page",
shadowed.join(", ")
);
}
*last = shadowed;
}
}
/// Whether a whole private range is trusted as proxies, so that any host on the private network
/// can name its own client address.
pub fn private_ranges_trusted() -> bool {
current().private_ranges_trusted
}
/// Rebuilds the trust from the global settings' values, as read, and swaps it in.
pub async fn apply_stored(
trusted_proxies: Option<&serde_json::Value>,
trust_cloudflare: Option<&serde_json::Value>,
client_ip_header: Option<&serde_json::Value>,
) {
let stored = Stored::from_values(trusted_proxies, trust_cloudflare, client_ip_header);
warn_if_shadowed(&stored);
let next = Arc::new(ClientIpSettings::from_env_and_stored(&stored));
let prev = CLIENT_IP_SETTINGS.load_full();
if prev.configuration == next.configuration {
return;
}
// A name trusted before stays trusted at its known addresses until it is re-resolved, so
// a change elsewhere in the list leaves no window in which its proxy is not believed. Both
// views resolve the same names, so the enforced one seeds a newly added attributed one too.
let known = prev.enforced.resolved.load();
for n in next.configs() {
n.resolved.store(Arc::new(
known
.iter()
.filter(|(h, _)| n.hosts.contains(h))
.cloned()
.collect(),
));
}
CLIENT_IP_SETTINGS.store(next.clone());
if LOCAL_JOBS_ONLY.load(std::sync::atomic::Ordering::Relaxed) {
return;
}
if STARTED.load(std::sync::atomic::Ordering::Relaxed) {
tracing::info!("Client IP: settings changed, now {}", next.describe());
warn_if_private_trusted(&next);
}
if next.configs().any(|c| !c.hosts.is_empty()) {
tokio::spawn(async move { resolve_all_hosts(&next).await });
}
}
/// Reads the global settings and applies them: at startup, on a settings change, and on the
/// server that wrote it, right after the write. Reads and applies one reload at a time: a page
/// saves its changed keys concurrently, and a snapshot read before another key's write landed
/// must not be applied after the one read once it did. A failed read is retried, since the
/// settings change event that triggered it is not delivered again.
pub async fn reload(db: &crate::DB) {
static RELOAD: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
let _one_at_a_time = RELOAD.lock().await;
let mut wait = Duration::from_millis(500);
for attempt in 1..=4 {
match read_stored(db).await {
Ok(v) => return apply_stored(v[0].as_ref(), v[1].as_ref(), v[2].as_ref()).await,
Err(e) if attempt < 4 => {
tracing::warn!("Client IP: could not read the settings, retrying: {e:#}");
tokio::time::sleep(wait).await;
wait *= 4;
}
Err(e) => tracing::error!(
"Client IP: could not read the settings, the trust in force is unchanged: {e:#}"
),
}
}
}
async fn read_stored(db: &crate::DB) -> crate::error::Result<Vec<Option<serde_json::Value>>> {
let mut values = Vec::with_capacity(SETTING_KEYS.len());
for key in SETTING_KEYS {
values.push(crate::global_settings::load_value_from_global_settings(db, key).await?);
}
Ok(values)
}
/// The client address of a request as token IP allowlists see it: `None` when the server was not
/// given the connection's peer (a router served without connect info, as in tests or internal
/// dispatch).
@@ -352,12 +691,12 @@ pub fn client_ip_of(extensions: &Extensions, headers: &HeaderMap) -> Option<IpAd
Some(resolve_client_ip(
peer,
headers,
CLIENT_IP_SETTINGS.enforced(),
current().enforced(),
))
}
pub fn attributed_client_ip(peer: IpAddr, headers: &HeaderMap) -> IpAddr {
resolve_client_ip(peer, headers, CLIENT_IP_SETTINGS.attributed())
resolve_client_ip(peer, headers, current().attributed())
}
/// An IPv4 client of a dual-stack listener arrives as `::ffff:a.b.c.d`; compare it as IPv4 so
@@ -446,7 +785,11 @@ pub fn resolve_client_ip(peer: IpAddr, headers: &HeaderMap, cfg: &ClientIpConfig
/// The forwarding header a request carries, as written (`CLIENT_IP_HEADER` when set, else every
/// `X-Forwarded-For` field), whether or not its peer is trusted.
pub fn forwarding_header(headers: &HeaderMap) -> Option<String> {
let name = CLIENT_IP_SETTINGS
forwarding_header_in(headers, &current())
}
fn forwarding_header_in(headers: &HeaderMap, s: &ClientIpSettings) -> Option<String> {
let name = s
.enforced
.header
.clone()
@@ -482,7 +825,7 @@ static FORWARDERS: LazyLock<Mutex<Forwarders>> = LazyLock::new(Default::default)
/// are then recorded as that proxy's.
pub fn note_forwarder(peer: IpAddr, headers: &HeaderMap) {
let peer = canonical(peer);
let s = &*CLIENT_IP_SETTINGS;
let s = current();
let forwarded = match &s.enforced.header {
Some(h) => headers.contains_key(h),
None => headers.contains_key("x-forwarded-for"),
@@ -564,9 +907,12 @@ pub struct ClientIpDiagnostics {
pub client_ip: Option<String>,
pub enforced_client_ip: Option<String>,
pub trusted_proxies_set: bool,
pub private_ranges_trusted: bool,
pub client_ip_header: Option<String>,
pub enforced: TrustView,
pub attributed: Option<TrustView>,
/// What the trust is built from, and which values the environment fixes.
pub configuration: ClientIpConfiguration,
/// On this server process only, most recent first.
pub forwarders: Vec<ForwarderSeen>,
}
@@ -576,7 +922,7 @@ fn trust_view(c: &ClientIpConfig, cloudflare: bool) -> TrustView {
networks: c
.trusted
.iter()
.filter(|n| !cloudflare || !nets(CLOUDFLARE).any(|cf| cf == **n))
.filter(|n| !cloudflare || !CLOUDFLARE_NETS.contains(n))
.map(|n| n.to_string())
.collect(),
hosts: c
@@ -598,7 +944,7 @@ fn trust_view(c: &ClientIpConfig, cloudflare: bool) -> TrustView {
}
pub fn diagnose(extensions: &Extensions, headers: &HeaderMap) -> ClientIpDiagnostics {
let s = &*CLIENT_IP_SETTINGS;
let s = current();
let peer = peer_of(extensions).map(canonical);
let s_ip = |c: &ClientIpConfig| peer.map(|p| resolve_client_ip(p, headers, c).to_string());
let mut forwarders: Vec<ForwarderSeen> = {
@@ -617,16 +963,18 @@ pub fn diagnose(extensions: &Extensions, headers: &HeaderMap) -> ClientIpDiagnos
forwarders.sort_by(|a, b| b.last_seen.cmp(&a.last_seen));
ClientIpDiagnostics {
peer: peer.map(|p| p.to_string()),
forwarding_header: forwarding_header(headers),
forwarding_header: forwarding_header_in(headers, &s),
client_ip: s_ip(s.attributed()),
enforced_client_ip: s_ip(&s.enforced),
trusted_proxies_set: s.trusted_proxies_set,
private_ranges_trusted: s.private_ranges_trusted,
client_ip_header: s.enforced.header.as_ref().map(|h| h.to_string()),
enforced: trust_view(&s.enforced, s.enforced.cloudflare),
attributed: s
.attributed
.as_ref()
.map(|a| trust_view(a, a.cloudflare)),
configuration: s.configuration.clone(),
forwarders,
}
}
@@ -649,7 +997,8 @@ mod tests {
}
fn cfg(trusted: &str, header: Option<&'static str>) -> ClientIpConfig {
ClientIpConfig::new(trusted, false, header.map(HeaderName::from_static))
let p = parse_trusted_proxies(trusted, false);
ClientIpConfig::new(p.trusted, p.hosts, false, header.map(HeaderName::from_static))
}
/// `TRUSTED_PROXIES` unset on a self-hosted instance.
@@ -872,6 +1221,55 @@ mod tests {
assert_eq!(resolve_client_ip(ip("10.0.0.1"), &h, &c), ip("10.0.0.1"));
}
#[test]
fn stored_trusted_proxies_refuse_what_is_not_a_proxy() {
assert!(validate_trusted_proxies("private, 10.1.2.3, 172.20.0.0/16, caddy, fd00::/8").is_ok());
assert!(validate_trusted_proxies("none").is_ok());
for bad in [
"0.0.0.0/0",
"::/0",
"10.0.0.0/8, 104.16.0.0/12",
"162.158.1.1",
"2606:4700::/48",
"10.0.0.0/33",
"10.0.0.256",
"none, 10.0.0.1",
"not a host!",
] {
assert!(validate_trusted_proxies(bad).is_err(), "{bad} accepted");
}
// Refused entries never reach the trust, even from a value that skipped the check.
let p = parse_trusted_proxies("0.0.0.0/0, 104.16.0.0/12, 10.0.0.1", true);
assert_eq!(p.trusted, vec!["10.0.0.1/32".parse::<IpNet>().unwrap()]);
assert_eq!(p.errors.len(), 2);
}
#[tokio::test]
async fn a_swap_keeps_resolved_hosts_and_takes_effect() {
let v = |s: &str| serde_json::Value::String(s.to_string());
let h = headers(&[("x-forwarded-for", b"5.5.5.5")]);
apply_stored(Some(&v("caddy, 10.1.0.0/16")), None, None).await;
assert_eq!(resolve_client_ip(ip("10.1.0.1"), &h, current().enforced()), ip("5.5.5.5"));
assert_eq!(resolve_client_ip(ip("10.2.0.1"), &h, current().enforced()), ip("10.2.0.1"));
current()
.enforced()
.resolved
.store(Arc::new(vec![("caddy".to_string(), vec![ip("172.18.0.4")])]));
apply_stored(Some(&v("caddy, 10.2.0.0/16")), None, None).await;
let s = current();
assert_eq!(resolve_client_ip(ip("172.18.0.4"), &h, s.enforced()), ip("5.5.5.5"));
assert_eq!(resolve_client_ip(ip("10.1.0.1"), &h, s.enforced()), ip("10.1.0.1"));
assert_eq!(resolve_client_ip(ip("10.2.0.1"), &h, s.enforced()), ip("5.5.5.5"));
assert!(!s.configuration.trusted_proxies.from_env);
assert!(!s.private_ranges_trusted);
// Set, but still trusting every private host: the exposure, not the value, is what counts.
apply_stored(Some(&v("private, 1.2.3.4")), None, None).await;
assert!(current().private_ranges_trusted);
apply_stored(None, None, None).await;
assert!(!current().trusted_proxies_set);
assert!(current().private_ranges_trusted);
}
#[test]
fn mapped_v4_is_v4() {
assert_eq!(
@@ -276,6 +276,8 @@ pub struct GlobalSettings {
pub auto_build_binary_on_deploy: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ai_sessions_instance_storage_fallback: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub trust_cloudflare: Option<bool>,
// String settings
#[serde(skip_serializing_if = "Option::is_none")]
@@ -293,6 +295,10 @@ pub struct GlobalSettings {
#[serde(skip_serializing_if = "Option::is_none")]
pub api_base_url_applies_to: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub trusted_proxies: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_ip_header: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email_domain: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hub_base_url: Option<String>,
+12
View File
@@ -344,6 +344,18 @@ Symbols, not line numbers, are cited: they drift less.
addresses no worker can know it is seen from. An explicit `TRUSTED_PROXIES` replaces the default:
comma-separated IPs, CIDRs, `private`, and hostnames (re-resolved every 15s, a name that does not
resolve trusts nothing; the compose template sets `caddy`); empty or `none` trusts nothing.
Each of the three variables is also a global setting (`trusted_proxies`, `trust_cloudflare`,
`client_ip_header`) edited on the Client IP page; a variable that is set wins over its setting
for good, and the page shows it read-only. A stored list is checked on write and again on load:
a `/0`, a range overlapping Cloudflare's (that is what `trust_cloudflare` is for) and an
unreadable entry are refused, not dropped silently. The trust is one `ArcSwap` rebuilt whole by
`client_ip::reload` on `notify_global_setting_change` in every process, and right after the
write on the server that took it; a `MODE=mcp` process, which joins no monitor loop, polls the
three settings at the same interval instead. A hostname kept across a swap keeps its resolved
addresses.
A wrong value cannot lock a superadmin out of the page: sessions never carry `allowed_ips`, and
the per-IP login limit, off on self-hosted unless `LOGIN_RATE_LIMIT_PER_IP` is set, is per
minute; the variables still override a stored value.
Two views differ only by Cloudflare: *enforced* (`ClientIp`, `client_ip_of`, `/api/client_ip`,
read by token allowlists) and *attributed* (`AttributedClientIp`, `request_origin.rs`, read by
audit entries and the login rate limit). `TRUST_CLOUDFLARE=true` adds Cloudflare's published
+50
View File
@@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest'
import { appendTrustedProxy, clientIpHeaderError, trustedProxiesErrors } from './clientIpTrust'
// The same inputs as `stored_trusted_proxies_refuse_what_is_not_a_proxy` in `client_ip.rs`:
// the form must refuse exactly what the server refuses.
describe('trustedProxiesErrors', () => {
it('accepts proxies', () => {
for (const ok of ['private, 10.1.2.3, 172.20.0.0/16, caddy, fd00::/8', 'none', '', '::ffff:10.0.0.1']) {
expect(trustedProxiesErrors(ok), ok).toEqual([])
}
})
it('refuses what is not a proxy', () => {
for (const bad of [
'0.0.0.0/0',
'::/0',
'10.0.0.0/8, 104.16.0.0/12',
'162.158.1.1',
'2606:4700::/48',
'10.0.0.0/33',
'10.0.0.256',
'none, 10.0.0.1',
'not a host!'
]) {
expect(trustedProxiesErrors(bad).length, bad).toBeGreaterThan(0)
}
})
it('refuses X-Forwarded-For as the client IP header', () => {
expect(clientIpHeaderError('X-Forwarded-For')).toBeDefined()
expect(clientIpHeaderError('CF-Connecting-IP')).toBeUndefined()
// YAML mode can put any JSON type here.
expect(clientIpHeaderError(42)).toBeDefined()
expect(trustedProxiesErrors(['10.0.0.1']).length).toBeGreaterThan(0)
})
})
describe('appendTrustedProxy', () => {
it('adds to the default private trust or narrows it, as asked', () => {
expect(appendTrustedProxy(undefined, '1.2.3.4', true)).toBe('private, 1.2.3.4')
expect(appendTrustedProxy('', '10.0.0.5', false)).toBe('10.0.0.5')
expect(appendTrustedProxy('none', '1.2.3.4', true)).toBe('1.2.3.4')
expect(appendTrustedProxy('10.0.0.0/8, caddy', 'caddy', true)).toBe('10.0.0.0/8, caddy')
// Narrowing drops whatever still trusts a whole private range.
expect(appendTrustedProxy('private, 1.2.3.4', '10.0.0.5', false)).toBe('1.2.3.4, 10.0.0.5')
expect(appendTrustedProxy('10.0.0.0/8, caddy', '10.0.0.5', false)).toBe('caddy, 10.0.0.5')
// A subnet inside a private range is a list of proxies, kept.
expect(appendTrustedProxy('192.168.0.0/24, 0.0.0.0/1', '10.0.0.5', false)).toBe(
'192.168.0.0/24, 10.0.0.5'
)
})
})
+189
View File
@@ -0,0 +1,189 @@
// Mirrors the checks `windmill_common::client_ip::validate_setting` applies on save, so the
// Client IP settings refuse the same values before the server does.
/** https://www.cloudflare.com/ips-v4 and /ips-v6, as embedded in `client_ip.rs`. */
const CLOUDFLARE = [
'173.245.48.0/20',
'103.21.244.0/22',
'103.22.200.0/22',
'103.31.4.0/22',
'141.101.64.0/18',
'108.162.192.0/18',
'190.93.240.0/20',
'188.114.96.0/20',
'197.234.240.0/22',
'198.41.128.0/17',
'162.158.0.0/15',
'104.16.0.0/13',
'104.24.0.0/14',
'172.64.0.0/13',
'131.0.72.0/22',
'2400:cb00::/32',
'2606:4700::/32',
'2803:f800::/32',
'2405:b500::/32',
'2405:8100::/32',
'2a06:98c0::/29',
'2c0f:f248::/32'
]
type Net = { v6: boolean; addr: bigint; prefix: number }
function parseV4(s: string): bigint | undefined {
const parts = s.split('.')
if (parts.length !== 4) return undefined
let n = 0n
for (const p of parts) {
if (!/^\d{1,3}$/.test(p) || Number(p) > 255) return undefined
n = (n << 8n) | BigInt(p)
}
return n
}
function parseV6(s: string): bigint | undefined {
if (!/^[0-9a-fA-F:.]+$/.test(s) || s.split('::').length > 2) return undefined
const [head, tail] = s.includes('::') ? s.split('::') : [s, undefined]
const groups = (g: string) => (g === '' ? [] : g.split(':'))
const h = groups(head)
const t = tail === undefined ? [] : groups(tail)
const words: number[] = []
const push = (list: string[], isLast: boolean) => {
for (let i = 0; i < list.length; i++) {
const g = list[i]
if (isLast && i === list.length - 1 && g.includes('.')) {
const v4 = parseV4(g)
if (v4 === undefined) return false
words.push(Number(v4 >> 16n), Number(v4 & 0xffffn))
} else if (/^[0-9a-fA-F]{1,4}$/.test(g)) {
words.push(parseInt(g, 16))
} else {
return false
}
}
return true
}
if (!push(h, tail === undefined)) return undefined
const headLen = words.length
if (!push(t, true)) return undefined
if (tail === undefined ? words.length !== 8 : words.length > 7) return undefined
const full = [
...words.slice(0, headLen),
...Array(8 - words.length).fill(0),
...words.slice(headLen)
]
return full.reduce((n, w) => (n << 16n) | BigInt(w), 0n)
}
function parseNet(s: string): Net | undefined {
const [addr, prefix, ...rest] = s.split('/')
if (rest.length) return undefined
const v4 = parseV4(addr)
const v6 = v4 === undefined ? parseV6(addr) : undefined
if (v4 === undefined && v6 === undefined) return undefined
const isV6 = v4 === undefined
const max = isV6 ? 128 : 32
if (prefix !== undefined && !/^\d{1,3}$/.test(prefix)) return undefined
const p = prefix === undefined ? max : Number(prefix)
if (p > max) return undefined
return { v6: isV6, addr: (v4 ?? v6)!, prefix: p }
}
function network(n: Net): bigint {
const bits = BigInt(n.v6 ? 128 : 32)
const host = bits - BigInt(n.prefix)
return (n.addr >> host) << host
}
/** Whether `n` contains `other`'s network address: either containing the other is an overlap. */
function containsAddr(n: Net, other: Net): boolean {
if (n.v6 !== other.v6) return false
const host = BigInt((n.v6 ? 128 : 32) - n.prefix)
return network(n) >> host === network(other) >> host
}
const CLOUDFLARE_NETS = CLOUDFLARE.map((c) => [c, parseNet(c)!] as const)
function isHostname(s: string): boolean {
return (
s.length <= 253 &&
s
.split('.')
.every(
(l) => l.length > 0 && l.length <= 63 && !l.startsWith('-') && /^[A-Za-z0-9_-]+$/.test(l)
) &&
!/^\d+$/.test(s.split('.').pop() ?? '')
)
}
/** Why each entry of a `trusted_proxies` value is refused, empty when it can be saved. */
export function trustedProxiesErrors(value: unknown): string[] {
if (value === undefined || value === null) return []
if (typeof value !== 'string') return ['must be text: a comma-separated list']
if (!value || value.trim().toLowerCase() === 'none') return []
const errors: string[] = []
for (const s of value
.split(',')
.map((s) => s.trim())
.filter(Boolean)) {
if (s.toLowerCase() === 'private') continue
const net = parseNet(s)
if (net) {
if (net.prefix === 0) {
errors.push(`${s} trusts every address, so any client could name its own`)
continue
}
const cf = CLOUDFLARE_NETS.find(([, c]) => containsAddr(c, net) || containsAddr(net, c))
if (cf) {
errors.push(`${s} overlaps Cloudflare's range ${cf[0]}: turn on Trust Cloudflare instead`)
}
} else if (s.toLowerCase() === 'none') {
errors.push('none trusts no proxy only on its own, not among other entries')
} else if (!isHostname(s)) {
errors.push(`${s} is not an IP address, a CIDR, a hostname or private`)
}
}
return errors
}
/** Why a `client_ip_header` value is refused, if it is. */
export function clientIpHeaderError(value: unknown): string | undefined {
if (value === undefined || value === null) return undefined
if (typeof value !== 'string') return 'must be text: a header name'
const v = value.trim()
if (!v) return undefined
if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(v)) return `${v} is not a header name`
if (v.toLowerCase() === 'x-forwarded-for') {
return 'X-Forwarded-For is read by default, from the right: leave this empty'
}
return undefined
}
const PRIVATE_NETS = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'].map(
(n) => parseNet(n)!
)
/** Whether a trusted proxies entry trusts a whole private range, as the server's
* `private_ranges_trusted` counts it. */
function coversPrivateRange(entry: string): boolean {
if (entry.toLowerCase() === 'private') return true
const net = parseNet(entry)
return net !== undefined && PRIVATE_NETS.some((p) => net.prefix <= p.prefix && containsAddr(net, p))
}
/** `list` with `entry` appended, unless it already names it. An empty list stands for the
* default, `private`. `keepDefault` keeps that trust; otherwise the result is narrowed to the
* listed proxies, dropping every entry that trusts a whole private range. */
export function appendTrustedProxy(
list: string | undefined,
entry: string,
keepDefault: boolean
): string {
const base = list?.trim() ? list : keepDefault ? 'private' : ''
const entries = base
.split(',')
.map((s) => s.trim())
.filter((s) => s && s.toLowerCase() !== 'none')
.filter((s) => keepDefault || !coversPrivateRange(s))
if (!entries.includes(entry)) entries.push(entry)
return entries.join(', ')
}
@@ -1169,10 +1169,10 @@
{:else if category == 'Client IP'}
<SettingsPageHeader
title="Client IP"
description="The address Windmill records as a request's client: in audit logs, for login rate limits and for token IP allowlists. Read-only: trusted proxies are configured with the TRUSTED_PROXIES, TRUST_CLOUDFLARE and CLIENT_IP_HEADER environment variables."
description="The address Windmill records as a request's client: in audit logs, for login rate limits and for token IP allowlists. Forwarding headers are believed only from the proxies trusted here. The TRUSTED_PROXIES, TRUST_CLOUDFLARE and CLIENT_IP_HEADER environment variables, when set, take precedence."
link="https://www.windmill.dev/docs/advanced/self_host#client-ip-behind-a-reverse-proxy"
/>
<ClientIpStatus />
<ClientIpStatus {values} {loading} />
{:else if category == 'Agent workers'}
<SettingsPageHeader
title="Agent workers"
@@ -1210,7 +1210,7 @@
<div class="flex-col flex gap-6 pb-6">
{#each settings[category] as setting}
<!-- slack connect is handled with the alert channels settings, smtp_connect is handled in InstanceSetting -->
{#if setting.fieldType != 'slack_connect' && !(quickSetup && setting.hideInQuickSetup) && !(quickSetup && category === 'Core' && setting.key === 'license_key') && !(setting.key === 'mcp_external_idp' && authSubTab !== 'sso')}
{#if setting.fieldType != 'slack_connect' && setting.fieldType != 'client_ip' && !(quickSetup && setting.hideInQuickSetup) && !(quickSetup && category === 'Core' && setting.key === 'license_key') && !(setting.key === 'mcp_external_idp' && authSubTab !== 'sso')}
<InstanceSetting
{openSmtpSettings}
on:closeDrawer={() => closeDrawer?.()}
@@ -8,6 +8,7 @@ import { parseCount } from '$lib/parseCount'
import { writable } from 'svelte/store'
import { OidcService } from '$lib/gen'
import { workspaceRolesErrors } from '$lib/workspaceRoles'
import { clientIpHeaderError, trustedProxiesErrors } from '$lib/clientIpTrust'
import { deepEqual } from 'fast-equals'
/**
@@ -85,6 +86,8 @@ export interface Setting {
| 'agent_workload_identity_issuers'
| 'mcp_external_idp'
| 'workspace_roles'
/** Drawn by the Client IP page itself, beside what the server reports it trusts. */
| 'client_ip'
storage: SettingStorage
advancedToggle?: {
label: string
@@ -955,7 +958,28 @@ export const settings: Record<string, Setting[]> = {
],
'DB Health': [],
'OIDC signing': [],
'Client IP': [],
'Client IP': [
{
label: 'Trusted proxies',
key: 'trusted_proxies',
fieldType: 'client_ip',
storage: 'setting',
isValid: (v: unknown) => trustedProxiesErrors(v).length === 0
},
{
label: 'Trust Cloudflare',
key: 'trust_cloudflare',
fieldType: 'client_ip',
storage: 'setting'
},
{
label: 'Client IP header',
key: 'client_ip_header',
fieldType: 'client_ip',
storage: 'setting',
isValid: (v: unknown) => clientIpHeaderError(v) === undefined
}
],
Registries: [
{
label: 'Instance Python Version',
@@ -1,18 +1,32 @@
<script lang="ts">
import { SettingService, type ClientIpDiagnostics, type ClientIpTrustView } from '$lib/gen'
import { Alert, Badge } from '$lib/components/common'
import { Alert, Badge, Skeleton } from '$lib/components/common'
import DataTable from '$lib/components/table/DataTable.svelte'
import Head from '$lib/components/table/Head.svelte'
import Cell from '$lib/components/table/Cell.svelte'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import Toggle from '$lib/components/Toggle.svelte'
import { displayDate } from '$lib/utils'
import { resource } from 'runed'
import { enterpriseLicense } from '$lib/stores'
import { instanceSettingsSaved } from '$lib/components/instanceSettings'
import { appendTrustedProxy, clientIpHeaderError, trustedProxiesErrors } from '$lib/clientIpTrust'
import type { Writable } from 'svelte/store'
interface Props {
values: Writable<Record<string, any>>
loading: boolean
}
let { values, loading }: Props = $props()
// Refetched after a save: the server answering applies a change before it responds.
const diagnostics = resource(
() => null,
() => $instanceSettingsSaved,
(): Promise<ClientIpDiagnostics> => SettingService.getClientIpDiagnostics()
)
let status = $derived(diagnostics.current)
let configuration = $derived(status?.configuration)
let loadError = $derived.by(() => {
const e: any = diagnostics.error
return e ? (e.body ?? e.message ?? String(e)) : undefined
@@ -36,6 +50,31 @@
status?.forwarding_header != undefined && status.client_ip === status.peer
)
let trustedProxiesFromEnv = $derived(configuration?.trusted_proxies.from_env ?? false)
let proxiesErrors = $derived(trustedProxiesErrors($values?.trusted_proxies))
let headerError = $derived(clientIpHeaderError($values?.client_ip_header))
/** The address to offer under "Trust this proxy", unless saving it would be refused. */
function trustable(ip: string | undefined): string | undefined {
if (!ip || trustedProxiesFromEnv || trustedProxiesErrors(ip).length > 0) return undefined
return ip
}
/** `keepDefault`: add the proxy to the private ranges trusted by default, rather than narrow
* the trust to it alone, which is what the warning about that default asks for. */
function trustAction(ip: string | undefined, keepDefault: boolean) {
const t = trustable(ip)
if (!t) return []
return [
{
label: `Trust ${t}`,
variant: 'default' as const,
onClick: () => {
$values.trusted_proxies = appendTrustedProxy($values.trusted_proxies, t, keepDefault)
}
}
]
}
function describe(view: ClientIpTrustView): string {
const parts = [...view.networks]
for (const h of view.hosts) {
@@ -48,17 +87,63 @@
}
</script>
{#snippet fromEnv(variable: string, value: string, stored: unknown)}
<div class="text-xs text-primary">
{#if value}<code>{value}</code>{:else}<span class="text-secondary">empty</span>{/if}
<div class="text-2xs text-secondary mt-1">
Set by the <code>{variable}</code> environment variable of the server{#if variable === 'TRUSTED_PROXIES'}{' '}(Helm:
<code>windmill.trustedProxies</code>){/if}, which takes precedence. Unset it to edit it
here.
{#if stored !== undefined && stored !== null && stored !== ''}
A value is also saved here (<code>{typeof stored === 'boolean'
? stored
? 'on'
: 'off'
: String(stored)}</code>); it applies once the variable is unset.
{/if}
</div>
</div>
{/snippet}
{#if loadError}
<Alert type="error" title="Could not load the client IP status">{loadError}</Alert>
{:else if status}
<div class="flex flex-col gap-4">
{:else if status && configuration}
<div class="flex flex-col gap-6">
{#if !$enterpriseLicense}
<Alert type="info" title="Mostly used by Enterprise features">
Audit logs and token IP allowlists, which record and check the client IP, are Enterprise
features. On this edition it only keys the per-IP login rate limit, when
<code>LOGIN_RATE_LIMIT_PER_IP</code> is set.
</Alert>
{/if}
{#if ownRequestUntrusted}
<Alert type="warning" title="Your own request came through a proxy Windmill does not trust">
<Alert
type="warning"
title="Your own request came through a proxy Windmill does not trust"
actions={trustAction(status.peer ?? undefined, true)}
>
It arrived from <code>{status.peer}</code> with the forwarding header
<code>{status.forwarding_header}</code>, so Windmill records <code>{status.peer}</code> as
the client of every request through it. Add that address (or its network) to the
<code>TRUSTED_PROXIES</code> environment variable of the server, or set
<code>TRUST_CLOUDFLARE=true</code> if it is Cloudflare.
<code>{status.forwarding_header}</code>, so Windmill records <code>{status.peer}</code> as the
client of every request through it. Add that address (or its network) to the trusted proxies
below, or turn on Trust Cloudflare if it is Cloudflare.
</Alert>
{/if}
{#if status.private_ranges_trusted}
<Alert
type="warning"
title="Any host on your private network is trusted as a proxy"
actions={trustAction(ownProxy, false)}
>
{status.trusted_proxies_set
? 'The trusted proxies include a whole private range'
: 'No trusted proxies are configured'}, so Windmill believes the forwarding headers of every
address in it, which is where your ingress or load balancer reaches it from. A host on
that network, a Windmill job included, can therefore name its own client address in audit
logs, for the login rate limit{#if $enterpriseLicense}{' '}and for token IP allowlists: a
leaked token stays restricted for an outsider, not for someone who can run a job{/if}.
List your proxies' addresses below to trust only them{#if ownProxy}, for example
<code>{ownProxy}</code>, the proxy this page came through, or its subnet{/if}.
</Alert>
{/if}
@@ -98,18 +183,93 @@
{/if}
</div>
{#if !status.trusted_proxies_set}
<Alert type="warning" title="Any host on your private network is trusted as a proxy">
<code>TRUSTED_PROXIES</code> is unset, so Windmill believes the forwarding headers of every
private address, which is where your ingress or load balancer reaches it from. A host on that
network, a Windmill job included, can therefore name its own client address in audit logs, for
the login rate limit{#if $enterpriseLicense}
and for token IP allowlists: a leaked token stays restricted for an outsider, not for someone
who can run a job{/if}. Set <code>TRUSTED_PROXIES</code> (Helm:
<code>windmill.trustedProxies</code>) to your proxies' addresses to trust only them{#if ownProxy}, for example
<code>{ownProxy}</code>, the proxy this page came through, or its subnet{/if}. Never list
Cloudflare's ranges there: use <code>TRUST_CLOUDFLARE</code>.
</Alert>
{#if loading || !$values}
<Skeleton layout={[[2.5], 1, [2.5], 1, [2.5]]} />
{:else}
<div class="flex flex-col gap-1">
<label for="trusted_proxies" class="text-xs font-semibold text-emphasis">
Trusted proxies
</label>
<div class="text-xs text-secondary">
The proxies whose forwarding headers are believed, comma-separated: IP addresses, CIDRs,
hostnames (re-resolved every 15 seconds, such as a compose service) and
<code>private</code> for loopback and the private ranges. <code>none</code> trusts no proxy.
Empty trusts loopback and the private ranges. Never list Cloudflare's ranges here: turn on
Trust Cloudflare.
</div>
{#if trustedProxiesFromEnv}
{@render fromEnv(
'TRUSTED_PROXIES',
configuration.trusted_proxies.value ?? '',
$values.trusted_proxies
)}
{:else}
<TextInput
inputProps={{
type: 'text',
id: 'trusted_proxies',
placeholder: 'private (default)'
}}
bind:value={$values.trusted_proxies}
error={proxiesErrors.length > 0}
class="max-w-lg"
/>
{#each proxiesErrors as e, i (i)}
<span class="text-red-600 dark:text-red-400 text-2xs">{e}</span>
{/each}
{/if}
</div>
<div class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">Trust Cloudflare</span>
<div class="text-xs text-secondary">
Also believe Cloudflare's published ranges, and the <code>CF-Connecting-IP</code> they send,
for audit entries and login rate limits. Token IP allowlists never trust them: any Cloudflare
customer's Worker sends from those ranges with headers of its choosing.
</div>
{#if configuration.trust_cloudflare.from_env}
{@render fromEnv(
'TRUST_CLOUDFLARE',
String(configuration.trust_cloudflare.value),
$values.trust_cloudflare
)}
{:else}
<Toggle
bind:checked={$values.trust_cloudflare}
id="trust_cloudflare"
ariaLabel="Trust Cloudflare"
/>
{/if}
</div>
<div class="flex flex-col gap-1">
<label for="client_ip_header" class="text-xs font-semibold text-emphasis">
Client IP header
</label>
<div class="text-xs text-secondary">
A header the edge in front of Windmill overwrites on every request, read instead of
<code>X-Forwarded-For</code>: <code>CloudFront-Viewer-Address</code>,
<code>CF-Connecting-IP</code>, or an nginx <code>X-Real-IP</code>. Leave it empty unless
the edge sets it on every request, or clients can name their own address.
</div>
{#if configuration.client_ip_header.from_env}
{@render fromEnv(
'CLIENT_IP_HEADER',
configuration.client_ip_header.value ?? '',
$values.client_ip_header
)}
{:else}
<TextInput
inputProps={{ type: 'text', id: 'client_ip_header', placeholder: 'X-Forwarded-For' }}
bind:value={$values.client_ip_header}
error={headerError}
class="max-w-lg"
/>
{#if headerError}
<span class="text-red-600 dark:text-red-400 text-2xs">{headerError}</span>
{/if}
{/if}
</div>
{/if}
{#if status.forwarders.length > 0}
@@ -141,8 +301,8 @@
</DataTable>
<div class="text-2xs text-secondary">
Seen by the server answering this page since it started. A peer believed by nothing is
recorded as the client: either a proxy missing from <code>TRUSTED_PROXIES</code>
or a client sending forwarding headers of its own, which are ignored.
recorded as the client: either a proxy missing from the trusted proxies or a client sending
forwarding headers of its own, which are ignored.
</div>
{:else}
<div class="text-xs text-secondary">
@@ -8,7 +8,7 @@
usersWorkspaceStore,
type UserWorkspace
} from '$lib/stores'
import { Button, Skeleton } from '../common'
import { Alert, Button, Skeleton } from '../common'
import { triggerableByAI } from '$lib/actions/triggerableByAI.svelte'
import Toggle from '../Toggle.svelte'
import { SettingService, SettingsService, UserService, type NewToken } from '$lib/gen'
@@ -103,12 +103,18 @@
// The address this browser calls from, as the server's IP checks resolve it.
let clientIp = $state<string | undefined>(undefined)
let clientIpRequested = false
// While a whole private range is trusted, any host there is believed when it names a client:
// an allowlist then holds only against callers outside the instance's network.
let privateRangesTrusted = $state<boolean | undefined>(undefined)
$effect(() => {
if ($enterpriseLicense && !clientIpRequested) {
clientIpRequested = true
SettingsService.getClientIp()
.then((ip) => (clientIp = ip.trim() || undefined))
.catch(() => {})
SettingService.getClientIpTrust()
.then((t) => (privateRangesTrusted = t.private_ranges_trusted))
.catch(() => {})
}
})
function addClientIp() {
@@ -720,10 +726,16 @@
/>
<p class="text-2xs text-hint">
IP addresses or CIDR ranges, separated by commas. Requests from any other address are
refused. Leave empty to allow any. Unless an instance admin lists the reverse proxies in
<code>TRUSTED_PROXIES</code>, a host on the instance's private network, a job included,
can claim an allowed address.
refused. Leave empty to allow any.
</p>
{#if privateRangesTrusted && allowedIps.length > 0}
<Alert type="warning" size="xs" title="Insiders can claim an allowed address">
This instance trusts a whole private range as proxies, so a host on its private network,
a job included, can name its own client address. The allowlist holds against callers
outside that network only. An instance admin can list the reverse proxies on the Client
IP instance settings page.
</Alert>
{/if}
{#if clientIp}
<div class="flex items-center gap-2 text-2xs text-secondary">
<span>Windmill sees this browser's IP as <code>{clientIp}</code></span>