mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-30 16:11:55 +00:00
feat: instance-wide IP allowlist on the Client IP settings page (#12756)
* 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> * feat: instance-wide IP allowlist enforced before authentication * fix: check every allowlist and trust write against the trust it puts in force * refactor: store each ip allowlist exemption as an object, rename push callbacks * fix: serialize allowlist and trust writes, refuse whole-block proxy trust * fix: check and write allowlist and trust keys in one locked transaction * fix: keep the allowlist reload marker in step with the list in force * chore: update ee-repo-ref to c93fbda372440a8c5559fb20d203d0f275d97289 This commit updates the EE repository reference after PR #1028 was merged in windmill-ee-private. Previous ee-repo-ref: ff722f7f7e14ba883a356af063d31b2d71d24550 New ee-repo-ref: c93fbda372440a8c5559fb20d203d0f275d97289 Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
windmill-internal-app[bot]
parent
de14e74ec0
commit
d62b195f48
@@ -1 +1 @@
|
||||
c17af04e6cc7eb26b85b4c0e1d7b949961dd394a
|
||||
c93fbda372440a8c5559fb20d203d0f275d97289
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
});
|
||||
|
||||
@@ -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<DB>,
|
||||
authed: ApiAuthed,
|
||||
request: RequestPeer,
|
||||
Path(key): Path<String>,
|
||||
Json(value): Json<Value>,
|
||||
) -> 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<DB>,
|
||||
authed: ApiAuthed,
|
||||
request: RequestPeer,
|
||||
Json(desired): Json<InstanceConfig>,
|
||||
) -> 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()))?;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<ClientIpSettings> {
|
||||
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<IpAddr> {
|
||||
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<IpAddr>,
|
||||
pub headers: HeaderMap,
|
||||
}
|
||||
|
||||
impl<S: Send + Sync> FromRequestParts<S> for RequestPeer {
|
||||
type Rejection = std::convert::Infallible;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
|
||||
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<IpAddr> {
|
||||
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());
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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?;
|
||||
|
||||
@@ -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<bool> = 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<String, Option<serde_json::Value>> {
|
||||
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<String, Option<serde_json::Value>>,
|
||||
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<serde_json::Value>> = 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<IpAddr> {
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 @@
|
||||
<AgentWorkloadIdentityIssuers {values} disabled={!$enterpriseLicense} />
|
||||
{:else if setting.fieldType == 'mcp_external_idp'}
|
||||
<McpExternalIdp {values} disabled={!$enterpriseLicense} />
|
||||
{:else if setting.fieldType == 'instance_ip_allowlist'}
|
||||
<InstanceIpAllowlist {values} licensed={!!$enterpriseLicense} />
|
||||
{:else if setting.fieldType == 'critical_error_channels'}
|
||||
<CriticalAlertChannels {values} {openSmtpSettings} {oauths} />
|
||||
{:else if setting.fieldType == 'otel'}
|
||||
|
||||
@@ -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<string, Setting[]> = {
|
||||
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: [
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
<script lang="ts">
|
||||
import type { Writable } from 'svelte/store'
|
||||
import { resource } from 'runed'
|
||||
import { SettingService, type ClientIpDiagnostics } from '$lib/gen'
|
||||
import { Alert, Button } from '../common'
|
||||
import Toggle from '../Toggle.svelte'
|
||||
import Label from '../Label.svelte'
|
||||
import { Plus } from 'lucide-svelte'
|
||||
import { instanceSettingsSaved } from '../instanceSettings'
|
||||
|
||||
interface Props {
|
||||
values: Writable<Record<string, any>>
|
||||
/** Without a valid license a stored list stays enforced, and may only be turned off. */
|
||||
licensed: boolean
|
||||
}
|
||||
|
||||
let { values, licensed }: Props = $props()
|
||||
|
||||
const KEY = 'instance_ip_allowlist'
|
||||
|
||||
const CATEGORIES = [
|
||||
{
|
||||
key: 'webhooks',
|
||||
label: 'Webhooks',
|
||||
description:
|
||||
'Runs of a script or flow by path or hash called with a token (jobs/run, run_wait_result, run_and_stream), native trigger deliveries included, their results, resume and cancel links of approval steps, and webhook captures.'
|
||||
},
|
||||
{ key: 'http_routes', label: 'HTTP routes', description: 'Every route under /api/r/.' },
|
||||
{
|
||||
key: 'push_callbacks',
|
||||
label: 'Push and chat callbacks',
|
||||
description:
|
||||
'GitHub and GitLab webhooks, GCP Pub/Sub and Azure Event Grid pushes, Slack and Teams callbacks. Native trigger deliveries are webhooks.'
|
||||
},
|
||||
{
|
||||
key: 'public_apps',
|
||||
label: 'Public apps',
|
||||
description: 'Public app pages and the runs they start (apps_u, jobs_u, resources_u).'
|
||||
},
|
||||
{
|
||||
key: 'health',
|
||||
label: 'Health checks',
|
||||
description:
|
||||
'/api/version, /api/health/status and /api/min_keep_alive_version, for load balancers.'
|
||||
},
|
||||
{
|
||||
key: 'agent_workers',
|
||||
label: 'Agent workers',
|
||||
description:
|
||||
'The agent worker protocol, not the route that creates agent tokens. Their jobs reach the API with their job token, which always passes.'
|
||||
}
|
||||
] as const
|
||||
|
||||
type Form = { enabled: boolean; allowed: string; exempt: string[]; prefixes: string }
|
||||
|
||||
const diagnostics = resource(
|
||||
() => $instanceSettingsSaved,
|
||||
(): Promise<ClientIpDiagnostics> => SettingService.getClientIpDiagnostics()
|
||||
)
|
||||
let status = $derived(diagnostics.current)
|
||||
let ownIp = $derived(status?.enforced_client_ip ?? undefined)
|
||||
let trustExplicit = $derived(status ? !status.private_ranges_trusted : true)
|
||||
let disabled = $derived(!licensed)
|
||||
|
||||
function lines(s: string): string[] {
|
||||
return s
|
||||
.split(/[\n,]/)
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l)
|
||||
}
|
||||
|
||||
type ExemptRule = { category?: string; path_prefix?: string; [field: string]: unknown }
|
||||
|
||||
function toForm(v: any): Form {
|
||||
const rules: ExemptRule[] = v?.exempt ?? []
|
||||
return {
|
||||
enabled: v?.enabled ?? false,
|
||||
allowed: (v?.allowed ?? []).join('\n'),
|
||||
exempt: rules.flatMap((r) => (r.category ? [r.category] : [])),
|
||||
prefixes: rules.flatMap((r) => (r.path_prefix ? [r.path_prefix] : [])).join('\n')
|
||||
}
|
||||
}
|
||||
|
||||
// Each rule is rebuilt from the stored one when it is still selected, so fields this form
|
||||
// does not edit survive a save.
|
||||
function serialize(f: Form): any | undefined {
|
||||
const allowed = lines(f.allowed)
|
||||
const prefixes = lines(f.prefixes)
|
||||
if (!f.enabled && allowed.length === 0 && f.exempt.length === 0 && prefixes.length === 0) {
|
||||
return undefined
|
||||
}
|
||||
const stored: ExemptRule[] = $values[KEY]?.exempt ?? []
|
||||
const exempt: ExemptRule[] = [
|
||||
...f.exempt.map((c) => stored.find((r) => r.category === c) ?? { category: c }),
|
||||
...prefixes.map((p) => stored.find((r) => r.path_prefix === p) ?? { path_prefix: p })
|
||||
]
|
||||
// Key order as jsonb stores it (shorter keys first), so an untouched list shows no diff.
|
||||
return { exempt, allowed, enabled: f.enabled }
|
||||
}
|
||||
|
||||
let form = $state<Form>(toForm(undefined))
|
||||
let lastSynced: string | undefined = undefined
|
||||
|
||||
$effect(() => {
|
||||
const cur = JSON.stringify($values[KEY] ?? null)
|
||||
if (cur === lastSynced) return
|
||||
lastSynced = cur
|
||||
form = toForm($values[KEY])
|
||||
})
|
||||
|
||||
$effect(() => {
|
||||
const next = serialize(form)
|
||||
if (lastSynced === undefined) return
|
||||
const nextStr = JSON.stringify(next ?? null)
|
||||
if (nextStr === JSON.stringify(serialize(toForm($values[KEY])) ?? null)) return
|
||||
lastSynced = nextStr
|
||||
$values[KEY] = next
|
||||
})
|
||||
|
||||
let ownIpListed = $derived(
|
||||
ownIp != undefined && lines(form.allowed).some((l) => l === ownIp || l === `${ownIp}/32`)
|
||||
)
|
||||
|
||||
function toggleCategory(key: string, on: boolean) {
|
||||
form.exempt = on ? [...new Set([...form.exempt, key])] : form.exempt.filter((k) => k !== key)
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-4 p-4 rounded-md border">
|
||||
{#if !trustExplicit}
|
||||
<Alert type="warning" title="Name your trusted proxies first">
|
||||
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.
|
||||
</Alert>
|
||||
{/if}
|
||||
{#if status?.attributed?.cloudflare}
|
||||
<Alert type="info" title="Behind Cloudflare, this list sees the Cloudflare edge">
|
||||
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 <code>CF-Connecting-IP</code>. To restrict who
|
||||
reaches an origin behind Cloudflare, use Cloudflare Access or authenticated origin pulls.
|
||||
</Alert>
|
||||
{/if}
|
||||
|
||||
<Toggle
|
||||
bind:checked={form.enabled}
|
||||
disabled={!form.enabled && (disabled || !trustExplicit)}
|
||||
options={{
|
||||
right: 'Only accept API requests from the addresses below',
|
||||
rightTooltip:
|
||||
"Checked before authentication, against the client IP that token IP allowlists use. Windmill's own traffic always passes: loopback, the trusted proxies, worker processes and requests carrying a job token."
|
||||
}}
|
||||
/>
|
||||
|
||||
<Label label="Allowed IPs and CIDRs">
|
||||
<textarea
|
||||
rows="4"
|
||||
{disabled}
|
||||
placeholder={'203.0.113.0/24\n2001:db8::/48'}
|
||||
bind:value={form.allowed}
|
||||
></textarea>
|
||||
<div class="flex items-center gap-2 text-2xs text-secondary">
|
||||
{#if ownIp}
|
||||
<span>This request comes from <code>{ownIp}</code>.</span>
|
||||
{#if !ownIpListed}
|
||||
<Button
|
||||
unifiedSize="xs"
|
||||
variant="subtle"
|
||||
startIcon={{ icon: Plus }}
|
||||
{disabled}
|
||||
onclick={() => (form.allowed = [...lines(form.allowed), ownIp].join('\n'))}
|
||||
>
|
||||
Add it
|
||||
</Button>
|
||||
{/if}
|
||||
{/if}
|
||||
<span
|
||||
>A list that leaves out your own address is refused, so saving it cannot lock you out.</span
|
||||
>
|
||||
</div>
|
||||
</Label>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<span class="text-xs font-semibold text-emphasis">Reachable from anywhere</span>
|
||||
<span class="text-xs text-secondary">
|
||||
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.
|
||||
</span>
|
||||
{#each CATEGORIES as c (c.key)}
|
||||
<Toggle
|
||||
size="xs"
|
||||
{disabled}
|
||||
checked={form.exempt.includes(c.key)}
|
||||
on:change={(e) => toggleCategory(c.key, e.detail)}
|
||||
options={{ right: c.label, rightTooltip: c.description }}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<Label label="Other path prefixes reachable from anywhere">
|
||||
<textarea
|
||||
rows="2"
|
||||
{disabled}
|
||||
placeholder="/api/w/main/jobs/run/p/u/admin/webhook"
|
||||
bind:value={form.prefixes}
|
||||
></textarea>
|
||||
<span class="text-2xs text-hint"
|
||||
>One per line, under /api/, matched on whole path segments.</span
|
||||
>
|
||||
</Label>
|
||||
|
||||
<div class="text-2xs text-secondary">
|
||||
Locked out? Restart the server with <code>INSTANCE_IP_ALLOWLIST_DISABLED=true</code>, or turn it
|
||||
off in the database, which every server picks up within seconds:
|
||||
<code
|
||||
>UPDATE global_settings SET value = jsonb_set(value, '{'{'}enabled{'}'}', 'false') WHERE name
|
||||
= 'instance_ip_allowlist';</code
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
Reference in New Issue
Block a user