diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 79c1f683ec..acbad8f6f0 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -c17af04e6cc7eb26b85b4c0e1d7b949961dd394a +c93fbda372440a8c5559fb20d203d0f275d97289 diff --git a/backend/src/main.rs b/backend/src/main.rs index 3669c54d26..3259094423 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -1630,6 +1630,7 @@ Windmill Community Edition {GIT_VERSION} _ = killpill_rx.recv() => return, _ = tokio::time::sleep(Duration::from_secs(*LISTEN_NEW_EVENTS_INTERVAL_SEC)) => { windmill_common::client_ip::reload(&db).await; + windmill_common::instance_ip_allowlist::reload(&db).await; } } } @@ -2106,6 +2107,9 @@ async fn process_notify_event( windmill_common::global_settings::MCP_EXTERNAL_IDP_SETTING => { crate::monitor::load_mcp_external_idp(db).await; } + windmill_common::global_settings::INSTANCE_IP_ALLOWLIST_SETTING => { + windmill_common::instance_ip_allowlist::reload(db).await; + } API_BASE_URL_SETTING => { load_api_base_url(db).await; } diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index 9a4ea26b92..afcec8681a 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -320,6 +320,11 @@ pub async fn initial_load( // 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( + windmill_common::global_settings::INSTANCE_IP_ALLOWLIST_SETTING, + false, + |v| async move { windmill_common::instance_ip_allowlist::apply_setting(v.as_ref()) }, + ); pass.setting(API_BASE_URL_SETTING, false, |v| async move { apply_api_base_url(v) }); diff --git a/backend/windmill-api-settings/src/lib.rs b/backend/windmill-api-settings/src/lib.rs index daf56ccd2b..9172c72650 100644 --- a/backend/windmill-api-settings/src/lib.rs +++ b/backend/windmill-api-settings/src/lib.rs @@ -37,6 +37,9 @@ use windmill_audit::{ use windmill_common::hub_resource_types::{self, SyncSource}; use windmill_common::utils::HTTP_CLIENT_PERMISSIVE as HTTP_CLIENT; use windmill_common::DB; +use windmill_common::{ + client_ip::RequestPeer, global_settings::INSTANCE_IP_ALLOWLIST_SETTING, instance_ip_allowlist, +}; use ee_oss::validate_license_key; use windmill_common::usernames::generate_instance_username_for_all_users; @@ -872,12 +875,26 @@ async fn workspace_fairness_settings_allowed() -> bool { pub async fn set_global_setting( Extension(db): Extension, authed: ApiAuthed, + request: RequestPeer, Path(key): Path, Json(value): Json, ) -> error::Result<()> { require_super_admin(&db, &authed).await?; let value = value.value.unwrap_or(serde_json::Value::Null); - set_global_setting_internal(&db, key.clone(), value.clone()).await?; + if instance_ip_allowlist::concerns(&key) { + // Validate the value itself first, so its own error is the one reported. + run_setting_pre_write_hook(&db, &key, &value).await?; + let cleared = value.is_null() || value.as_str().is_some_and(|s| s.trim().is_empty()); + let written = + std::collections::HashMap::from([(key.clone(), (!cleared).then(|| value.clone()))]); + instance_ip_allowlist::write_checked(&db, &written, Some(&request)).await?; + run_setting_post_write_hook(&db, &key).await?; + } else { + set_global_setting_internal(&db, key.clone(), value.clone()).await?; + } + if key == INSTANCE_IP_ALLOWLIST_SETTING { + instance_ip_allowlist::log_write(Some(&value)); + } audit_setting_write(&db, &authed, &key, Some(&value), None).await } @@ -1036,6 +1053,9 @@ async fn run_setting_post_write_hook(db: &DB, key: &str) -> error::Result<()> { if windmill_common::client_ip::SETTING_KEYS.contains(&key) { windmill_common::client_ip::reload(db).await; } + if key == INSTANCE_IP_ALLOWLIST_SETTING { + instance_ip_allowlist::reload(db).await; + } Ok(()) } @@ -1348,6 +1368,10 @@ async fn run_setting_pre_write_hook( windmill_common::global_settings::parse_mcp_external_idp(Some(value)) .map_err(|e| error::Error::BadRequest(format!("{key}: {e}")))?; } + INSTANCE_IP_ALLOWLIST_SETTING => { + instance_ip_allowlist::parse_setting(Some(value)) + .map_err(|e| error::Error::BadRequest(format!("{key}: {e}")))?; + } MAX_TOKEN_EXPIRATION_DAYS_SETTING => { windmill_common::global_settings::parse_max_token_expiration_days(Some(value)) .map_err(|e| { @@ -1434,11 +1458,20 @@ async fn get_instance_config_yaml( async fn set_instance_config( Extension(db): Extension, authed: ApiAuthed, + request: RequestPeer, Json(desired): Json, ) -> error::Result<()> { require_super_admin(&db, &authed).await?; + apply_instance_config(&db, &authed, &request, desired).await +} - let current = InstanceConfig::from_db(&db) +async fn apply_instance_config( + db: &DB, + authed: &ApiAuthed, + request: &RequestPeer, + desired: InstanceConfig, +) -> error::Result<()> { + let current = InstanceConfig::from_db(db) .await .map_err(|e| error::Error::internal_err(e.to_string()))?; @@ -1490,7 +1523,13 @@ async fn set_instance_config( run_setting_pre_write_hook(&db, WORKSPACE_ROLES_SETTING, &serde_json::Value::Null) .await?; } - let auditor = InstanceConfigAuditor { db: &db, author: &authed, source: None }; + let ip_allowlist_written = instance_ip_allowlist::take_concerned(&mut settings_diff); + instance_ip_allowlist::write_checked(db, &ip_allowlist_written, Some(request)).await?; + let auditor = InstanceConfigAuditor { db, author: authed, source: None }; + for (key, value) in &ip_allowlist_written { + instance_config::ConfigWriteObserver::setting_written(&auditor, key, value.as_ref()) + .await?; + } // The external-instance write removes its own key from the diff. windmill_common::external_instance_pg::write_external_instance_pg_from_diff( &db, @@ -1505,11 +1544,15 @@ async fn set_instance_config( if ai_config_changed { bump_instance_ai_config_revision(); } + if let Some(v) = ip_allowlist_written.get(INSTANCE_IP_ALLOWLIST_SETTING) { + instance_ip_allowlist::log_write(v.as_ref()); + } for key in settings_diff .upserts .iter() .map(|(k, _)| k) .chain(settings_diff.deletes.iter()) + .chain(ip_allowlist_written.keys()) { run_setting_post_write_hook(&db, key).await?; } @@ -1541,7 +1584,7 @@ async fn set_instance_config( instance_config::apply_configs_diff( &db, &configs_diff, - &InstanceConfigAuditor { db: &db, author: &authed, source: None }, + &InstanceConfigAuditor { db, author: authed, source: None }, ) .await .map_err(|e| error::Error::internal_err(e.to_string()))?; diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 3d08060e7f..e79cf8bd41 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -325,6 +325,30 @@ async fn set_request_client( windmill_common::trigger_history::scope_client(client, next.run(req)).await } +/// Refuses, before routing and authentication, a request from an address the instance IP +/// allowlist does not admit. +async fn enforce_instance_ip_allowlist( + req: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + if let Some(ip) = windmill_common::instance_ip_allowlist::refused( + req.uri().path(), + req.extensions(), + req.headers(), + ) + .await + { + return axum::response::IntoResponse::into_response(( + http::StatusCode::FORBIDDEN, + format!( + "This Windmill instance does not accept requests from {ip}: it is not in the \ + instance IP allowlist." + ), + )); + } + next.run(req).await +} + /// Scope the request in its origin (client address and user agent), recorded on the audit /// entries it writes. A request routed in-process has no connect info and keeps the origin /// of the request that routed it. @@ -1276,7 +1300,8 @@ pub async fn run_server( } }) .fallback(static_assets::static_handler) - .layer(middleware_stack); + .layer(middleware_stack) + .layer(axum::middleware::from_fn(enforce_instance_ip_allowlist)); let app = if disable_response_logs { app diff --git a/backend/windmill-audit/src/instance_config.rs b/backend/windmill-audit/src/instance_config.rs index 977e0fe6c6..85b00a5560 100644 --- a/backend/windmill-audit/src/instance_config.rs +++ b/backend/windmill-audit/src/instance_config.rs @@ -54,9 +54,14 @@ fn parameters<'a>( (!parameters.is_empty()).then_some(parameters) } -/// A setting is recorded by name, with its value only when that is a boolean or a number. -/// Any other shape can carry a credential (a registry URL, a webhook, a header map), and no -/// list of secret-bearing settings stays complete as settings are added. +/// Settings whose whole value is recorded: their shape is fixed and holds no credential. +const RECORDED_IN_FULL: &[&str] = + &[windmill_common::global_settings::INSTANCE_IP_ALLOWLIST_SETTING]; + +/// A setting is recorded by name, with its value only when that is a boolean or a number, or +/// the setting is in [`RECORDED_IN_FULL`]. Any other shape can carry a credential (a registry +/// URL, a webhook, a header map), and no list of secret-bearing settings stays complete as +/// settings are added. /// /// AUTHORIZATION: records a write, checks nothing. The caller must have established that /// `author` may change instance settings before performing the write this records. @@ -76,6 +81,7 @@ pub async fn audit_setting_write( Some(v @ (serde_json::Value::Bool(_) | serde_json::Value::Number(_))) => { Some(v.to_string()) } + Some(v) if !deleted && RECORDED_IN_FULL.contains(&key) => Some(v.to_string()), _ => None, }; audit_log( diff --git a/backend/windmill-common/src/client_ip.rs b/backend/windmill-common/src/client_ip.rs index eb48844421..98e0f2c7ff 100644 --- a/backend/windmill-common/src/client_ip.rs +++ b/backend/windmill-common/src/client_ip.rs @@ -740,6 +740,75 @@ pub fn serve_local_jobs_only() { LOCAL_JOBS_ONLY.store(true, std::sync::atomic::Ordering::Relaxed); } +pub fn serves_local_jobs_only() -> bool { + LOCAL_JOBS_ONLY.load(std::sync::atomic::Ordering::Relaxed) +} + +/// The trust the given stored values would put in force, environment overrides included and +/// its hostnames resolved, so a write can be checked against what it would change. +pub async fn settings_with( + trusted_proxies: Option<&serde_json::Value>, + trust_cloudflare: Option<&serde_json::Value>, + client_ip_header: Option<&serde_json::Value>, +) -> Arc { + let s = ClientIpSettings::from_env_and_stored(&Stored::from_values( + trusted_proxies, + trust_cloudflare, + client_ip_header, + )); + resolve_all_hosts(&s).await; + Arc::new(s) +} + +impl ClientIpSettings { + pub fn enforced_client_ip(&self, peer: &RequestPeer) -> Option { + peer.peer + .map(|p| resolve_client_ip(p, &peer.headers, &self.enforced)) + } + + /// What the instance IP allowlist needs: no trusted network is a whole private block or wider + /// (the default included), since every host of a trusted network can name its own client + /// address, and when that is a private block that is the network a job runs on. + pub fn trust_is_explicit(&self) -> bool { + !self.private_ranges_trusted + } + + /// Whether `peer` sends this request on its own behalf: it is loopback or a trusted proxy and + /// carries no forwarding header this trust would read. A relayed request is never that, even + /// when its forwarding header cannot be read and its client address falls back to the peer. + pub fn is_own_request(&self, peer: IpAddr, headers: &HeaderMap) -> bool { + let forwards = match &self.enforced.header { + Some(h) => headers.contains_key(h), + None => headers.contains_key("x-forwarded-for"), + }; + let peer = canonical(peer); + !forwards && (peer.is_loopback() || self.enforced.is_trusted(peer)) + } +} + +/// A request's TCP peer and headers, for checks that resolve its client address under a trust +/// other than the one in force. +pub struct RequestPeer { + pub peer: Option, + pub headers: HeaderMap, +} + +impl FromRequestParts for RequestPeer { + type Rejection = std::convert::Infallible; + + async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { + Ok(RequestPeer { + peer: peer_of(&parts.extensions).map(canonical), + headers: parts.headers.clone(), + }) + } +} + +/// The TCP peer of a request, `None` without connect info. +pub fn peer(extensions: &Extensions) -> Option { + peer_of(extensions).map(canonical) +} + pub fn resolve_client_ip(peer: IpAddr, headers: &HeaderMap, cfg: &ClientIpConfig) -> IpAddr { let peer = canonical(peer); if LOCAL_JOBS_ONLY.load(std::sync::atomic::Ordering::Relaxed) || !cfg.is_trusted(peer) { @@ -1244,6 +1313,26 @@ mod tests { assert_eq!(p.errors.len(), 2); } + #[tokio::test] + async fn explicit_trust_names_no_whole_private_block() { + let t = |v: Option<&'static str>| async move { + settings_with(v.map(serde_json::Value::from).as_ref(), None, None) + .await + .trust_is_explicit() + }; + assert!(t(Some("10.1.2.3")).await); + assert!(t(Some("10.244.0.0/16")).await); + for broad in [ + None, + Some("private"), + Some("10.0.0.0/8"), + Some("10.0.0.0/7"), + Some("10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"), + ] { + assert!(!t(broad).await, "{broad:?}"); + } + } + #[tokio::test] async fn a_swap_keeps_resolved_hosts_and_takes_effect() { let v = |s: &str| serde_json::Value::String(s.to_string()); diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index 70d50a073c..8d447f2e7a 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -117,6 +117,7 @@ pub const MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING: &str = "mcp_disable_token_query /// An external OIDC issuer whose access tokens the MCP endpoints accept, and the OAuth clients /// of that issuer they serve. Read and validated by [`parse_mcp_external_idp`]. pub const MCP_EXTERNAL_IDP_SETTING: &str = "mcp_external_idp"; +pub const INSTANCE_IP_ALLOWLIST_SETTING: &str = "instance_ip_allowlist"; /// Ceiling, in days, on how far ahead a token minted through `POST /users/tokens/create` or /// `POST /users/tokens/impersonate` may expire; a request asking for more, or for no /// expiration at all, is shortened to it rather than refused. On those routes only: server-side diff --git a/backend/windmill-common/src/instance_config.rs b/backend/windmill-common/src/instance_config.rs index a9f62ed5c2..cb4776cc93 100644 --- a/backend/windmill-common/src/instance_config.rs +++ b/backend/windmill-common/src/instance_config.rs @@ -1745,6 +1745,15 @@ pub async fn sync_global_settings_declarative( .await .map_err(|e| anyhow::anyhow!("{roles_key}: {e}"))?; } + // No request here to check a lockout against: a list written from config is the + // operator's to keep reachable. + let ip_allowlist_written = crate::instance_ip_allowlist::take_concerned(&mut diff); + crate::instance_ip_allowlist::write_checked(db, &ip_allowlist_written, None) + .await + .map_err(|e| anyhow::anyhow!("{e}"))?; + for (key, value) in &ip_allowlist_written { + observer.setting_written(key, value.as_ref()).await?; + } crate::external_instance_pg::write_external_instance_pg_from_diff(db, &mut diff, observer) .await?; apply_settings_diff(db, &diff, observer).await?; diff --git a/backend/windmill-common/src/instance_ip_allowlist_oss.rs b/backend/windmill-common/src/instance_ip_allowlist_oss.rs new file mode 100644 index 0000000000..0eb6d42370 --- /dev/null +++ b/backend/windmill-common/src/instance_ip_allowlist_oss.rs @@ -0,0 +1,193 @@ +/* + * Author: Windmill Labs, Inc + * Copyright: Windmill Labs, Inc 2026 + * This file and its contents are licensed under the AGPLv3 License. + * Please see the included NOTICE for copyright information and + * LICENSE-AGPL for a copy of the license. + */ + +//! The instance IP allowlist (the `instance_ip_allowlist` setting) is an Enterprise Edition +//! feature. A community build never enforces a stored list and refuses to enable one, but still +//! lets one be turned off or cleared. + +use std::collections::HashMap; +use std::sync::LazyLock; + +use crate::global_settings::INSTANCE_IP_ALLOWLIST_SETTING; + +pub const ENV_DISABLED: &str = "INSTANCE_IP_ALLOWLIST_DISABLED"; + +/// The escape hatch: with it set the stored list is ignored, so an admin locked out can restart +/// the server with it, sign in and fix the list. +pub static DISABLED_BY_ENV: LazyLock = LazyLock::new(|| { + std::env::var(ENV_DISABLED) + .is_ok_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "true" | "1" | "yes")) +}); + +/// Reads the stored setting and puts it in force. +pub async fn reload(db: &crate::DB) { + match crate::global_settings::load_value_from_global_settings(db, INSTANCE_IP_ALLOWLIST_SETTING) + .await + { + Ok(v) => apply_setting(v.as_ref()), + Err(e) => tracing::error!("Error loading {INSTANCE_IP_ALLOWLIST_SETTING}: {e:#}"), + } +} + +/// Whether a write to `key` can change whether the stored allowlist may stay in force. +pub fn concerns(key: &str) -> bool { + key == INSTANCE_IP_ALLOWLIST_SETTING || crate::client_ip::SETTING_KEYS.contains(&key) +} + +/// Moves the allowlist and trust keys out of `diff`, for [`write_checked`] to write. +pub fn take_concerned( + diff: &mut crate::instance_config::SettingsDiff, +) -> HashMap> { + let mut taken = HashMap::new(); + diff.upserts.retain(|k, v| { + let c = concerns(k); + if c { + taken.insert(k.clone(), Some(v.clone())); + } + !c + }); + diff.deletes.retain(|k| { + let c = concerns(k); + if c { + taken.insert(k.clone(), None); + } + !c + }); + taken +} + +/// The only writer of the allowlist and the client IP trust. In one transaction holding a lock +/// every server takes for it, reads what is stored, checks what the write would leave in force +/// (the list, under the trust it would put in force, with `request` resolved under that trust; +/// `None` for the declarative sync, which has no request), and writes. Two writes checked apart, +/// such as the Client IP page saving the trust and the list as separate requests, would each be +/// checked against the other's old value and together store what neither check saw. One +/// connection only: the write holds no second one while it waits for the pool. +/// `written` maps each written key to its new value, `None` when it is cleared. +/// +/// AUTHORIZATION: checks nothing about the caller. Callers must have established that it may +/// change instance settings (a superadmin, or the declarative sync) before calling. +pub async fn write_checked( + db: &crate::DB, + written: &HashMap>, + request: Option<&crate::client_ip::RequestPeer>, +) -> crate::error::Result<()> { + if written.is_empty() { + return Ok(()); + } + let mut tx = db.begin().await?; + sqlx::query("SELECT pg_advisory_xact_lock(hashtext('instance_ip_allowlist_write'))") + .execute(&mut *tx) + .await?; + let mut values: HashMap<&str, Option> = HashMap::new(); + for key in [INSTANCE_IP_ALLOWLIST_SETTING] + .into_iter() + .chain(crate::client_ip::SETTING_KEYS.iter().copied()) + { + let value = match written.get(key) { + Some(v) => v.clone(), + None => { + sqlx::query_scalar::<_, serde_json::Value>( + "SELECT value FROM global_settings WHERE name = $1", + ) + .bind(key) + .fetch_optional(&mut *tx) + .await? + } + }; + values.insert(key, value.filter(|v| !v.is_null())); + } + let get = |k: &str| values.get(k).and_then(|v| v.as_ref()); + let trust = crate::client_ip::settings_with( + get(crate::client_ip::TRUSTED_PROXIES_SETTING), + get(crate::client_ip::TRUST_CLOUDFLARE_SETTING), + get(crate::client_ip::CLIENT_IP_HEADER_SETTING), + ) + .await; + check_write( + get(INSTANCE_IP_ALLOWLIST_SETTING), + &trust, + request, + written.contains_key(INSTANCE_IP_ALLOWLIST_SETTING), + ) + .await + .map_err(|e| { + crate::error::Error::BadRequest(format!("{INSTANCE_IP_ALLOWLIST_SETTING}: {e}")) + })?; + for (key, value) in written { + match value { + Some(v) => { + sqlx::query( + "INSERT INTO global_settings (name, value) VALUES ($1, $2) \ + ON CONFLICT (name) DO UPDATE SET value = EXCLUDED.value, updated_at = now()", + ) + .bind(key) + .bind(v) + .execute(&mut *tx) + .await?; + } + None => { + sqlx::query("DELETE FROM global_settings WHERE name = $1") + .bind(key) + .execute(&mut *tx) + .await?; + } + } + tracing::info!("Wrote global setting {key}"); + } + tx.commit().await?; + Ok(()) +} + +#[cfg(all(feature = "private", feature = "enterprise"))] +pub use crate::instance_ip_allowlist_ee::{ + apply_setting, check_write, log_write, parse_setting, refused, +}; + +#[cfg(not(all(feature = "private", feature = "enterprise")))] +pub use ce::*; + +#[cfg(not(all(feature = "private", feature = "enterprise")))] +mod ce { + use std::net::IpAddr; + + use axum::http::{Extensions, HeaderMap}; + + use crate::client_ip::{ClientIpSettings, RequestPeer}; + + pub fn apply_setting(_value: Option<&serde_json::Value>) {} + + /// Validates nothing beyond what [`check_write`] refuses: the shape is the edition's. + pub fn parse_setting(_value: Option<&serde_json::Value>) -> Result<(), String> { + Ok(()) + } + + pub async fn check_write( + value: Option<&serde_json::Value>, + _trust: &ClientIpSettings, + _request: Option<&RequestPeer>, + _list_written: bool, + ) -> Result<(), String> { + match value.and_then(|v| v.get("enabled")) { + Some(serde_json::Value::Bool(true)) => Err( + "the instance IP allowlist is a Windmill Enterprise Edition feature".to_string(), + ), + _ => Ok(()), + } + } + + pub fn log_write(_value: Option<&serde_json::Value>) {} + + pub async fn refused( + _path: &str, + _extensions: &Extensions, + _headers: &HeaderMap, + ) -> Option { + None + } +} diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 186a93cbc0..21179411bc 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -82,6 +82,10 @@ pub mod guest_jwt; pub mod hub_resource_types; pub mod indexer; pub mod instance_config; +pub mod instance_ip_allowlist_oss; +pub use instance_ip_allowlist_oss as instance_ip_allowlist; +#[cfg(all(feature = "private", feature = "enterprise"))] +mod instance_ip_allowlist_ee; pub mod job_metrics; pub mod log_context; pub mod materialization; diff --git a/docs/auth-surface.md b/docs/auth-surface.md index 3da4f8ebc2..4355d61874 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -396,3 +396,31 @@ Symbols, not line numbers, are cited: they drift less. approve and `login_links` refuse a restricted caller, since what they lead to is a session with no restriction. Not inherited, by design: a job's `WM_TOKEN` (a JWT; starting the job already passed the check) and JWTs the server mints for its own loopback calls. +- **The instance IP allowlist** (`instance_ip_allowlist` setting, EE, `instance_ip_allowlist_ee.rs`) + refuses an `/api/` request before routing and authentication when its *enforced* client IP is + not listed; static assets and `/.well-known/` are not checked. Never the attributed view: behind + Cloudflare it sees the edge, and only Cloudflare Access or authenticated origin pulls restrict + an origin there. It may be in force only under named trusted proxies none of which covers a whole + private block (`ClientIpSettings::trust_is_explicit`: `private`, `10.0.0.0/8` or wider are refused, + and a client IP header alone does not count): every host of a trusted network names its own address. Every write + of the list or of the trust settings, per key, bulk or the declarative sync, goes through + `write_checked`: in one transaction holding an advisory lock, on one connection, it reads what is + stored, resolves the trust the write would put in force (`client_ip::settings_with`), refuses a + result that leaves the writing request's own address out under that trust (unless the list always + passes that request), and writes. The Client IP page saves each key as its own request, and two + writes checked apart would each be checked against the other's old value. + Turning the list off is always allowed; the license is checked only when the list is written, a + lapsed license keeps a stored list enforced, and a CE build ignores one. Always passing: requests + with no connect info (in-process dispatch), a worker process's own API, a loopback peer or trusted + proxy sending on its own behalf (`is_own_request`: no forwarding header it would read; a relayed + request is judged on the address it resolves to, since an unreadable header falls back to the + proxy's), and a request whose bearer is a valid job JWT (`job_id` set), which is how jobs reach + `BASE_INTERNAL_URL` from addresses no server can know; a job token proves no more than running + code on a worker, which already reaches the API. Everything else outside the list passes only + through a named exemption (webhooks, which native trigger deliveries call too; HTTP routes; + GitHub/GitLab webhooks, GCP/Azure pushes and Slack/Teams callbacks; public apps, with + `ee_license` but not `users/whoami`; health; the agent worker protocol, its routes named one by + one so the superadmin ones beside them stay behind the list) or a listed path prefix, matched on whole + segments, never on the query. Recovery: `INSTANCE_IP_ALLOWLIST_DISABLED=true` and a restart, or + setting `enabled` to false in `global_settings`, which every server, MCP ones included, reloads + within seconds. diff --git a/docs/feature-telemetry.md b/docs/feature-telemetry.md index ed2ca255e1..7b011ca59e 100644 --- a/docs/feature-telemetry.md +++ b/docs/feature-telemetry.md @@ -4,14 +4,14 @@ anonymous usage-stats payload. It answers "does anyone use this, and which variant do they pick" without any identifying data leaving the instance. -It currently carries 111 registered actions across forty-three features (`access_view`, `ai_session`, `ai_chat`, +It currently carries 113 registered actions across forty-four features (`access_view`, `ai_session`, `ai_chat`, `autoscaling_diagnostics`, `code_mode`, `ai_fix`, `ai_agent`, `ai_decision`, `ai_agent_eval`, `app_sandbox`, `datatable`, `db_manager`, `flow_editor`, `flow_run`, `flow_step`, `home`, `header_nav`, `run_form`, `sharing`, `debugger`, `trigger`, `command_script`, `mcp`, `mcp_workspace`, `mcp_external_client`, `hub_script`, `usage_meter`, `sso_groups_claim`, `cloud_trial_offer`, `job_token_scopes`, `worker_draining`, `worker_group`, `worker_resource_stats`, `dev_workspace_isolation`, `slack_agent`, `variable_expiration`, -`external_secret_ref`, `anthropic_federation`, `vertex_workload_identity`, `deployment_request`, `fork_roles`, `git_sync_review`, `workspace_webhook`). Nearly all of the +`external_secret_ref`, `anthropic_federation`, `vertex_workload_identity`, `deployment_request`, `fork_roles`, `git_sync_review`, `workspace_webhook`, `instance_ip_allowlist`). Nearly all of the product is uninstrumented, so new user-facing work is the opportunity to change that. ## When to instrument diff --git a/frontend/src/lib/components/InstanceSetting.svelte b/frontend/src/lib/components/InstanceSetting.svelte index 48323cab2a..dd526f0e8a 100644 --- a/frontend/src/lib/components/InstanceSetting.svelte +++ b/frontend/src/lib/components/InstanceSetting.svelte @@ -23,6 +23,7 @@ import RetentionPeriodOverrides from './instanceSettings/RetentionPeriodOverrides.svelte' import AgentWorkloadIdentityIssuers from './instanceSettings/AgentWorkloadIdentityIssuers.svelte' import McpExternalIdp from './instanceSettings/McpExternalIdp.svelte' + import InstanceIpAllowlist from './instanceSettings/InstanceIpAllowlist.svelte' import OtelAuditLogsSettings from './instanceSettings/OtelAuditLogsSettings.svelte' import WorkspaceRolesSetting from './instanceSettings/WorkspaceRolesSetting.svelte' import SmtpSettings from './instanceSettings/SmtpSettings.svelte' @@ -648,6 +649,8 @@ {:else if setting.fieldType == 'mcp_external_idp'} + {:else if setting.fieldType == 'instance_ip_allowlist'} + {:else if setting.fieldType == 'critical_error_channels'} {:else if setting.fieldType == 'otel'} diff --git a/frontend/src/lib/components/instanceSettings.ts b/frontend/src/lib/components/instanceSettings.ts index 710820c758..14fa956dd5 100644 --- a/frontend/src/lib/components/instanceSettings.ts +++ b/frontend/src/lib/components/instanceSettings.ts @@ -85,6 +85,7 @@ export interface Setting { | 'accent_color' | 'agent_workload_identity_issuers' | 'mcp_external_idp' + | 'instance_ip_allowlist' | 'workspace_roles' /** Drawn by the Client IP page itself, beside what the server reports it trusts. */ | 'client_ip' @@ -978,6 +979,16 @@ export const settings: Record = { fieldType: 'client_ip', storage: 'setting', isValid: (v: unknown) => clientIpHeaderError(v) === undefined + }, + { + label: 'IP allowlist', + description: + 'Refuse every API request whose client address is not listed, before it is authenticated.', + key: 'instance_ip_allowlist', + fieldType: 'instance_ip_allowlist', + storage: 'setting', + ee_only: '', + hideInQuickSetup: true } ], Registries: [ diff --git a/frontend/src/lib/components/instanceSettings/InstanceIpAllowlist.svelte b/frontend/src/lib/components/instanceSettings/InstanceIpAllowlist.svelte new file mode 100644 index 0000000000..ed7a0f5eed --- /dev/null +++ b/frontend/src/lib/components/instanceSettings/InstanceIpAllowlist.svelte @@ -0,0 +1,220 @@ + + +
+ {#if !trustExplicit} + + The allowlist needs your reverse proxies named in Trusted proxies above, and saved, none of them + a whole private range such as 10.0.0.0/8: every host of a trusted network, a Windmill job + included, could claim an allowlisted address. + + {/if} + {#if status?.attributed?.cloudflare} + + Cloudflare's ranges are trusted for audit entries only: anyone can put their own Cloudflare + zone in front of your origin and send it any CF-Connecting-IP. To restrict who + reaches an origin behind Cloudflare, use Cloudflare Access or authenticated origin pulls. + + {/if} + + + + + +
+ Reachable from anywhere + + What outside systems call. Each still needs its own token or secret. Browser sign-in callbacks + come from the user's address and need no exemption. + + {#each CATEGORIES as c (c.key)} + toggleCategory(c.key, e.detail)} + options={{ right: c.label, rightTooltip: c.description }} + /> + {/each} +
+ + + +
+ Locked out? Restart the server with INSTANCE_IP_ALLOWLIST_DISABLED=true, or turn it + off in the database, which every server picks up within seconds: + UPDATE global_settings SET value = jsonb_set(value, '{'{'}enabled{'}'}', 'false') WHERE name + = 'instance_ip_allowlist'; +
+