feat: restrict api tokens to allowed ip ranges (#12679)

* fix: derive the client ip from trusted proxies only

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

* fix: read forwarded-for as raw bytes and add an explicit client ip header

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

* fix: strip the source port from cloudfront-viewer-address before parsing

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

* style: rustfmt client_ip

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

* feat: restrict api tokens to allowed ip ranges

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

* fix: inherit token ip restrictions on every mint and refuse login links

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

* fix: keep a webhook token's ip restriction when rotating it

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

* test: pin that webhook token rotation keeps allowed_ips

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

* perf: resolve the client ip only for restricted tokens and throttle refusal logs

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

* chore: update ee-repo-ref to 49b7074a9ce31a2b7cd5a730c9b9d4b8295d0c7e

This commit updates the EE repository reference after PR #1011 was merged in windmill-ee-private.

Previous ee-repo-ref: 6c8458630cea7c3082771db9f772c964ef11dcdf

New ee-repo-ref: 49b7074a9ce31a2b7cd5a730c9b9d4b8295d0c7e

Automated by sync-ee-ref workflow.

* feat: show the caller's ip so a device can check what to allowlist

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

* feat: make token ip allowlists an ee feature

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

* refactor: move token ip allowlist logic into ee

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

* chore: update ee-repo-ref to cf0cee4ef89bd0b8b2399ced7b12ccc9a3d43dd8

This commit updates the EE repository reference after PR #1017 was merged in windmill-ee-private.

Previous ee-repo-ref: 98f8ade3347f3dcfc73962f4aa39618282f73fa3

New ee-repo-ref: cf0cee4ef89bd0b8b2399ced7b12ccc9a3d43dd8

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:
Ruben Fiszel
2026-11-26 21:27:52 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot]
parent 0b11d3e9a6
commit f555024e73
43 changed files with 922 additions and 53 deletions
@@ -0,0 +1,24 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO token\n (token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, workspace_id, read_only, allowed_ips)\n SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::text[]::cidr[]\n WHERE $9::varchar IS NULL OR NOT EXISTS(\n SELECT 1 FROM workspace WHERE id = $9 AND deleted = true\n )",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Timestamptz",
"Bool",
"TextArray",
"Varchar",
"Bool",
"TextArray"
]
},
"nullable": []
},
"hash": "2cd408ec9b9547ae3095bcb8f1e21edaefc5a7732c2bb8f6599fa8fd51c73745"
}
@@ -0,0 +1,24 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes, workspace_id, owner, expiration, allowed_ips)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::text[]::cidr[])",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Bool",
"TextArray",
"Varchar",
"Varchar",
"Timestamptz",
"TextArray"
]
},
"nullable": []
},
"hash": "35e54cdfd2df6d2ec4a9777490a87b938312a03f5ff1e3fe76f432bdf93af621"
}
@@ -0,0 +1,21 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO token\n (token_hash, token_prefix, token, email, label, expiration, super_admin, owner, allowed_ips)\n VALUES ($1, $2, $3, $4, $5, $6, false, $7, $8::text[]::cidr[])",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Timestamptz",
"Varchar",
"TextArray"
]
},
"nullable": []
},
"hash": "45e44eaaeaba49965c14bfea0af0978fdab66c004836cbee4b39fb7c4342e44e"
}
@@ -0,0 +1,21 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO token\n (token_hash, token_prefix, token, email, label, expiration, super_admin, allowed_ips)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8::text[]::cidr[])",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Timestamptz",
"Bool",
"TextArray"
]
},
"nullable": []
},
"hash": "6aab07d50008cb21b5ea1e23c5d1ddbeeb5da97c5c40a50c7945303c9930cb1b"
}
@@ -0,0 +1,46 @@
{
"db_name": "PostgreSQL",
"query": "SELECT email, workspace_id, super_admin, owner, allowed_ips::text[] AS allowed_ips\n FROM token WHERE token_hash = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "email",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "workspace_id",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "super_admin",
"type_info": "Bool"
},
{
"ordinal": 3,
"name": "owner",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "allowed_ips",
"type_info": "TextArray"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
true,
true,
false,
true,
null
]
},
"hash": "76355b8f5319afcecf2514c14a64ab70ce13b504b4c80364d4ceecede98e81ae"
}
@@ -0,0 +1,72 @@
{
"db_name": "PostgreSQL",
"query": "SELECT label, token_prefix, expiration, created_at, last_used_at, scopes, workspace_id, read_only, allowed_ips::text[] AS allowed_ips FROM token WHERE email = $1 AND (label != 'ephemeral-script' OR label IS NULL)\n ORDER BY created_at DESC LIMIT $2 OFFSET $3",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "label",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "token_prefix",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "expiration",
"type_info": "Timestamptz"
},
{
"ordinal": 3,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 4,
"name": "last_used_at",
"type_info": "Timestamptz"
},
{
"ordinal": 5,
"name": "scopes",
"type_info": "TextArray"
},
{
"ordinal": 6,
"name": "workspace_id",
"type_info": "Varchar"
},
{
"ordinal": 7,
"name": "read_only",
"type_info": "Bool"
},
{
"ordinal": 8,
"name": "allowed_ips",
"type_info": "TextArray"
}
],
"parameters": {
"Left": [
"Text",
"Int8",
"Int8"
]
},
"nullable": [
true,
false,
true,
false,
false,
true,
true,
false,
null
]
},
"hash": "b45ee8dffade9cd25f02e3906446a937e69bd92ba37064d7134791b8d901cec8"
}
@@ -0,0 +1,59 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE token SET last_used_at = now() WHERE\n token_hash = $1\n AND (expiration > NOW() OR expiration IS NULL)\n AND (workspace_id IS NULL OR workspace_id = $2)\n RETURNING owner, email, super_admin, scopes, label, read_only,\n allowed_ips::text[] AS allowed_ips",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "owner",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "email",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "super_admin",
"type_info": "Bool"
},
{
"ordinal": 3,
"name": "scopes",
"type_info": "TextArray"
},
{
"ordinal": 4,
"name": "label",
"type_info": "Varchar"
},
{
"ordinal": 5,
"name": "read_only",
"type_info": "Bool"
},
{
"ordinal": 6,
"name": "allowed_ips",
"type_info": "TextArray"
}
],
"parameters": {
"Left": [
"Text",
"Text"
]
},
"nullable": [
true,
true,
false,
true,
true,
false,
null
]
},
"hash": "bf8144fe246dcc0fbfb73b37036a7fae4d13e273ed22f430b74b62e0c0614e2a"
}
@@ -0,0 +1,72 @@
{
"db_name": "PostgreSQL",
"query": "SELECT label, token_prefix, expiration, created_at, last_used_at, scopes, workspace_id, read_only, allowed_ips::text[] AS allowed_ips FROM token WHERE email = $1\n ORDER BY created_at DESC LIMIT $2 OFFSET $3",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "label",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "token_prefix",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "expiration",
"type_info": "Timestamptz"
},
{
"ordinal": 3,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 4,
"name": "last_used_at",
"type_info": "Timestamptz"
},
{
"ordinal": 5,
"name": "scopes",
"type_info": "TextArray"
},
{
"ordinal": 6,
"name": "workspace_id",
"type_info": "Varchar"
},
{
"ordinal": 7,
"name": "read_only",
"type_info": "Bool"
},
{
"ordinal": 8,
"name": "allowed_ips",
"type_info": "TextArray"
}
],
"parameters": {
"Left": [
"Text",
"Int8",
"Int8"
]
},
"nullable": [
true,
false,
true,
false,
false,
true,
true,
false,
null
]
},
"hash": "df74a087ba68636152e1b9ae5d38db8a224bd4b1167dd584ae8f4e1ffa20e326"
}
+1 -1
View File
@@ -1 +1 @@
f0417fbaee7b4661bebc0123d34ccd3aba87c6a7
cf0cee4ef89bd0b8b2399ced7b12ccc9a3d43dd8
@@ -0,0 +1 @@
ALTER TABLE token DROP COLUMN IF EXISTS allowed_ips;
@@ -0,0 +1 @@
ALTER TABLE token ADD COLUMN IF NOT EXISTS allowed_ips cidr[];
+1
View File
@@ -28,6 +28,7 @@ fn scoped_authed(scopes: Vec<&str>) -> ApiAuthed {
credential_expiry: None,
mcp_client: None,
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
allowed_ips: None,
}
}
+1
View File
@@ -92,6 +92,7 @@ fn trigger_authed() -> windmill_api_auth::ApiAuthed {
credential_expiry: None,
mcp_client: None,
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
allowed_ips: None,
}
}
+83
View File
@@ -0,0 +1,83 @@
//! A token restricted to `allowed_ips` works only from those networks, and cannot mint a
//! credential that works from anywhere else. Setting a list is EE-only.
#![cfg(all(feature = "enterprise", feature = "private"))]
use sqlx::{Pool, Postgres};
use windmill_test_utils::*;
#[sqlx::test(fixtures("base"))]
async fn test_token_allowed_ips(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let base = format!("http://localhost:{}/api/users", server.addr.port());
let client = reqwest::Client::new();
for (token, nets) in [
("RESTRICTED_TOKEN", "{10.9.9.0/24}"),
("LOOPBACK_TOKEN", "{127.0.0.1/32,::1/128}"),
] {
sqlx::query(
"INSERT INTO token (token_hash, token_prefix, email, label, super_admin, allowed_ips)
VALUES (encode(sha256($1::bytea), 'hex'), substr($1, 1, 10), 'test@windmill.dev',
'ci', false, $2::cidr[])",
)
.bind(token)
.bind(nets)
.execute(&db)
.await?;
}
// The test client connects from loopback, a trusted proxy by default, so
// X-Forwarded-For stands in for a client on another network.
let whoami = |token: &'static str, from: Option<&'static str>| {
let req = client.get(format!("{base}/whoami")).bearer_auth(token);
let req = match from {
Some(ip) => req.header("X-Forwarded-For", ip),
None => req,
};
req.send()
};
assert_eq!(whoami("RESTRICTED_TOKEN", None).await?.status(), 401);
assert_eq!(
whoami("RESTRICTED_TOKEN", Some("10.9.9.5")).await?.status(),
200
);
// The identity is cached now; the address is still checked.
assert_eq!(
whoami("RESTRICTED_TOKEN", Some("8.8.8.8")).await?.status(),
401
);
assert_eq!(whoami("LOOPBACK_TOKEN", None).await?.status(), 200);
assert_eq!(
whoami("LOOPBACK_TOKEN", Some("10.9.9.5")).await?.status(),
401
);
let create = |body: serde_json::Value| {
client
.post(format!("{base}/tokens/create"))
.bearer_auth("RESTRICTED_TOKEN")
.header("X-Forwarded-For", "10.9.9.5")
.json(&body)
.send()
};
let resp = create(serde_json::json!({ "label": "child" })).await?;
assert_eq!(resp.status(), 201, "{}", resp.text().await?);
let inherited: Vec<String> =
sqlx::query_scalar("SELECT unnest(allowed_ips)::text FROM token WHERE label = 'child'")
.fetch_all(&db)
.await?;
assert_eq!(inherited, vec!["10.9.9.0/24"]);
let resp = create(serde_json::json!({ "label": "wide", "allowed_ips": ["0.0.0.0/0"] })).await?;
assert_eq!(resp.status(), 403);
let resp = client
.get(format!("{base}/refresh_token"))
.bearer_auth("RESTRICTED_TOKEN")
.header("X-Forwarded-For", "10.9.9.5")
.send()
.await?;
assert_eq!(resp.status(), 401);
Ok(())
}
@@ -181,6 +181,7 @@ fn make_authed() -> windmill_api_auth::ApiAuthed {
credential_expiry: None,
mcp_client: None,
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
allowed_ips: None,
}
}
+1
View File
@@ -1131,6 +1131,7 @@ async fn test_privilege_gates_reject_a_job_token_directly(
credential_expiry: None,
mcp_client: None,
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
allowed_ips: None,
}
}
@@ -38,6 +38,7 @@ fn outsider() -> ApiAuthed {
credential_expiry: None,
mcp_client: None,
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
allowed_ips: None,
}
}
+150 -13
View File
@@ -15,6 +15,7 @@ use tracing::Span;
use crate::{ApiAuthed, OptJobAuthed};
use std::{
net::IpAddr,
str::FromStr,
sync::{
atomic::{AtomicI64, AtomicU64, Ordering},
@@ -45,6 +46,57 @@ lazy_static::lazy_static! {
static ref PICKED_SESSION_CACHE: Cache<String, (Option<usize>, std::time::Instant)> = Cache::new(500);
}
/// Throttles the log line for refused IP-restricted tokens: a leaked token hammered from outside
/// its networks would otherwise log once per request.
static REFUSAL_LOG: std::sync::LazyLock<RefusalLog> = std::sync::LazyLock::new(RefusalLog::default);
const REFUSAL_LOG_INTERVAL: std::time::Duration = std::time::Duration::from_secs(60);
/// Bounds the memory an attacker cycling through many tokens can pin; a reset only lets each
/// token log once more early.
const REFUSAL_LOG_MAX_TOKENS: usize = 10_000;
#[derive(Default)]
struct RefusalLog(std::sync::Mutex<std::collections::HashMap<String, (std::time::Instant, u64)>>);
impl RefusalLog {
/// Records one refusal of `token_prefix`. Returns the number of its refusals to report when a
/// line is due (the first one, then at most one per interval), `None` while suppressed.
fn note(&self, token_prefix: &str, now: std::time::Instant) -> Option<u64> {
let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
if let Some((last, count)) = map.get_mut(token_prefix) {
*count += 1;
if now.duration_since(*last) < REFUSAL_LOG_INTERVAL {
return None;
}
let refused = *count;
*last = now;
*count = 0;
return Some(refused);
}
if map.len() >= REFUSAL_LOG_MAX_TOKENS {
map.clear();
}
map.insert(token_prefix.to_string(), (now, 0));
Some(1)
}
}
fn log_ip_refusal(token_prefix: &str, client_ip: Option<IpAddr>) {
if let Some(refused) = REFUSAL_LOG.note(token_prefix, std::time::Instant::now()) {
tracing::warn!(
token_prefix,
client_ip = client_ip.map(|ip| ip.to_string()).unwrap_or_default(),
refused_since_last_log = refused,
"token refused: request is outside the token's allowed IPs"
);
}
}
/// Marks a request whose IP refusal was already logged: a failed resolution is not memoized,
/// so a second auth extractor on the same request resolves the token again.
#[derive(Clone)]
struct IpRefusalLogged;
/// A token keeps its identity when a superadmin moves the account to another address, so entries
/// here must expire on their own; nothing invalidates them by token hash.
const TOKEN_EMAIL_CACHE_TTL_SECS: u64 = 60;
@@ -158,16 +210,54 @@ impl AuthCache {
AUTH_CACHE.remove(&(w_id.to_string(), token));
}
pub async fn get_authed(&self, w_id: Option<String>, token: &str) -> Option<ApiAuthed> {
Some(self.get_opt_job_authed(w_id, token).await?.authed)
/// `client_ip` is the address of the request presenting `token` (`ClientIp`), `None` outside
/// one: a token restricted to `allowed_ips` resolves only when it is inside them.
pub async fn get_authed(
&self,
w_id: Option<String>,
token: &str,
client_ip: Option<IpAddr>,
) -> Option<ApiAuthed> {
Some(
self.get_opt_job_authed(w_id, token, client_ip)
.await?
.authed,
)
}
pub async fn get_opt_job_authed(
&self,
w_id: Option<String>,
token: &str,
client_ip: Option<IpAddr>,
) -> Option<OptJobAuthed> {
self.get_opt_job_authed_lazy_ip(w_id, token, move || client_ip, log_ip_refusal)
.await
}
/// `client_ip` is resolved only for a token that has `allowed_ips`, so the hot path pays
/// nothing for unrestricted tokens. `on_refused` gets the token prefix and address of a
/// request refused for being outside them.
async fn get_opt_job_authed_lazy_ip(
&self,
w_id: Option<String>,
token: &str,
client_ip: impl FnOnce() -> Option<IpAddr>,
on_refused: impl FnOnce(&str, Option<IpAddr>),
) -> Option<OptJobAuthed> {
let mut opt_job_authed = self.get_opt_job_authed_inner(w_id.clone(), token).await?;
// Checked per request, outside the cache: the cached identity carries the list, and each
// request brings its own address.
if let Some(allowed) = opt_job_authed.authed.allowed_ips.as_deref() {
let client_ip = client_ip();
if !crate::client_ip_allowed(Some(allowed), client_ip) {
on_refused(
opt_job_authed.authed.token_prefix.as_deref().unwrap_or(""),
client_ip,
);
return None;
}
}
// Single source of truth: mirror the resolved job_id onto the authed so
// every consumer (require_super_admin, ...) sees that this identity came
// from a job's WM_TOKEN, even on an AUTH_CACHE hit whose cached authed
@@ -360,6 +450,7 @@ impl AuthCache {
credential_expiry: Some(credential_expiry),
mcp_client: None,
capabilities: None,
allowed_ips: None,
};
AUTH_CACHE.insert(
key,
@@ -407,6 +498,7 @@ impl AuthCache {
credential_expiry: None,
mcp_client: claims.mcp_client,
capabilities: None,
allowed_ips: None,
};
// Fail closed: a `job_id` claim that does not parse must reject
// the token rather than resolve to `None`, which would clear the
@@ -446,18 +538,22 @@ impl AuthCache {
token_hash = $1
AND (expiration > NOW() OR expiration IS NULL)
AND (workspace_id IS NULL OR workspace_id = $2)
RETURNING owner, email, super_admin, scopes, label, read_only",
RETURNING owner, email, super_admin, scopes, label, read_only,
allowed_ips::text[] AS allowed_ips",
t_hash,
w_id.as_ref(),
)
.map(|x| {
(
x.owner,
x.email,
x.super_admin,
x.scopes,
x.label,
x.read_only,
(
x.owner,
x.email,
x.super_admin,
x.scopes,
x.label,
x.read_only,
),
x.allowed_ips,
)
})
.fetch_optional(&self.db)
@@ -465,7 +561,8 @@ impl AuthCache {
.ok()
.flatten();
if let Some(user) = user_o {
if let Some((user, allowed_ips)) = user_o {
let allowed_ips = crate::token_ip_allowlist_oss::load_allowed_ips(allowed_ips);
let authed_o = {
match user {
(Some(owner), Some(email), super_admin, _, label, read_only)
@@ -540,6 +637,7 @@ impl AuthCache {
credential_expiry: None,
mcp_client: None,
capabilities: None,
allowed_ips: None,
})
} else {
tracing::warn!(
@@ -596,6 +694,7 @@ impl AuthCache {
credential_expiry: None,
mcp_client: None,
capabilities: None,
allowed_ips: None,
})
} else {
tracing::warn!(
@@ -697,6 +796,7 @@ impl AuthCache {
credential_expiry: None,
mcp_client: None,
capabilities: None,
allowed_ips: None,
})
}
None if super_admin => {
@@ -724,6 +824,7 @@ impl AuthCache {
credential_expiry: None,
mcp_client: None,
capabilities: None,
allowed_ips: None,
}),
Err(e) => {
tracing::error!(
@@ -764,6 +865,7 @@ impl AuthCache {
credential_expiry: None,
mcp_client: None,
capabilities: None,
allowed_ips: None,
})
}
None => None,
@@ -786,12 +888,14 @@ impl AuthCache {
credential_expiry: None,
mcp_client: None,
capabilities: None,
allowed_ips: None,
})
}
}
_ => None,
}
};
let authed_o = authed_o.map(|authed| ApiAuthed { allowed_ips, ..authed });
if let Some(authed) = authed_o.as_ref() {
AUTH_CACHE.insert(
key,
@@ -828,6 +932,7 @@ impl AuthCache {
credential_expiry: None,
mcp_client: None,
capabilities: None,
allowed_ips: None,
};
Some(OptJobAuthed { authed, job_id: None })
} else {
@@ -1274,6 +1379,7 @@ fn no_auth_admin_authed() -> ApiAuthed {
credential_expiry: None,
mcp_client: None,
capabilities: None,
allowed_ips: None,
}
}
@@ -1325,9 +1431,22 @@ pub async fn resolve_opt_job_authed(
.map(|g| g.0.clone())
});
if let Some(mut opt_job_authed) =
cache.get_opt_job_authed(workspace_id.clone(), &token).await
{
let mut ip_refused = None;
let resolved = cache
.get_opt_job_authed_lazy_ip(
workspace_id.clone(),
&token,
|| windmill_common::client_ip::client_ip_of_parts(&parts),
|prefix, ip| ip_refused = Some((prefix.to_string(), ip)),
)
.await;
if let Some((prefix, ip)) = ip_refused {
if parts.extensions.get::<IpRefusalLogged>().is_none() {
log_ip_refusal(&prefix, ip);
parts.extensions.insert(IpRefusalLogged);
}
}
if let Some(mut opt_job_authed) = resolved {
let path = original_uri.path();
let method = parts.method.as_str();
if workspace_id.is_none() && opt_job_authed.job_id.is_some() {
@@ -1547,6 +1666,24 @@ pub async fn list_tokens_internal(
mod tests {
use super::*;
#[test]
fn refusal_log_reports_once_per_interval_with_the_count() {
let log = RefusalLog::default();
let t0 = std::time::Instant::now();
assert_eq!(log.note("tok_a", t0), Some(1));
for _ in 0..4 {
assert_eq!(
log.note("tok_a", t0 + std::time::Duration::from_secs(1)),
None
);
}
// A token of its own is not held back by another's suppression.
assert_eq!(log.note("tok_b", t0), Some(1));
// The four suppressed refusals plus this one.
assert_eq!(log.note("tok_a", t0 + REFUSAL_LOG_INTERVAL), Some(5));
assert_eq!(log.note("tok_a", t0 + REFUSAL_LOG_INTERVAL), None);
}
#[test]
fn filter_tags_reach_their_dev_workspace_form() {
let mut scopes = vec![
+25 -2
View File
@@ -12,6 +12,10 @@ pub mod composed;
pub mod ee;
pub mod ee_oss;
pub mod scopes;
#[cfg(all(feature = "private", feature = "enterprise"))]
mod token_ip_allowlist_ee;
pub mod token_ip_allowlist_oss;
pub use token_ip_allowlist_oss::{client_ip_allowed, token_ip_allowlist};
use axum::extract::{FromRequestParts, OptionalFromRequestParts, Path, Request, State};
use axum::middleware::Next;
@@ -37,6 +41,7 @@ use windmill_common::{
};
use scopes::ScopeDefinition;
use windmill_common::client_ip::IpNet;
use windmill_common::scopes::scope_contains;
// Re-export key auth types and functions
@@ -97,6 +102,10 @@ pub struct ApiAuthed {
/// The role's capabilities in the request's workspace (`AuthCache::get_opt_job_authed`); `None`
/// outside a request.
pub capabilities: Option<RoleCapabilities>,
/// The networks the token row this identity came from may be used from (`token.allowed_ips`).
/// Enforced by `AuthCache::get_opt_job_authed` against each request's client IP; a token
/// minted from this identity through `tokens/create` is held within them.
pub allowed_ips: Option<Vec<IpNet>>,
}
impl ApiAuthed {
@@ -191,6 +200,7 @@ impl From<Authed> for ApiAuthed {
credential_expiry: None,
mcp_client: value.mcp_client,
capabilities: value.capabilities,
allowed_ips: None,
}
}
}
@@ -1197,6 +1207,7 @@ pub async fn fetch_api_authed_from_permissioned_as(
credential_expiry: None,
mcp_client: None,
capabilities: None,
allowed_ips: None,
};
API_AUTHED_CACHE.insert(
@@ -1231,6 +1242,10 @@ pub struct NewToken {
/// An MCP token carries its owner's superadmin rights (every workspace) only when asked.
#[serde(default)]
pub super_admin: Option<bool>,
/// IPs or CIDRs the token may be used from; `None` is anywhere. [`create_token_internal`]
/// validates it and holds it within the caller's own.
#[serde(default)]
pub allowed_ips: Option<Vec<String>>,
}
impl NewToken {
@@ -1250,6 +1265,7 @@ impl NewToken {
workspace_id,
read_only,
super_admin: None,
allowed_ips: None,
}
}
}
@@ -1299,6 +1315,12 @@ pub async fn create_token_internal(
.as_deref()
.is_some_and(|s| s.iter().any(|scope| scope.starts_with("mcp:")));
let is_super_admin = is_super_admin && (!is_mcp || token_config.super_admin == Some(true));
// Here rather than in each handler: every token minted from a caller's identity (app SDK
// and embed tokens, native trigger webhooks included) must inherit its IP restriction.
let allowed_ips = token_ip_allowlist(
authed.allowed_ips.as_deref(),
token_config.allowed_ips.as_deref(),
)?;
if *CLOUD_HOSTED {
let nb_tokens =
sqlx::query_scalar!("SELECT COUNT(*) FROM token WHERE email = $1", &authed.email)
@@ -1313,8 +1335,8 @@ pub async fn create_token_internal(
}
let rows = sqlx::query!(
"INSERT INTO token
(token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, workspace_id, read_only)
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10
(token_hash, token_prefix, token, email, label, expiration, super_admin, scopes, workspace_id, read_only, allowed_ips)
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::text[]::cidr[]
WHERE $9::varchar IS NULL OR NOT EXISTS(
SELECT 1 FROM workspace WHERE id = $9 AND deleted = true
)",
@@ -1328,6 +1350,7 @@ pub async fn create_token_internal(
token_config.scopes.as_ref().map(|x| x.as_slice()),
token_config.workspace_id,
token_config.read_only.unwrap_or(false),
allowed_ips.as_deref(),
)
.execute(&mut *tx)
.await?;
@@ -0,0 +1,49 @@
/*
* 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.
*/
//! Token IP allowlists are an Enterprise Edition feature. Without it a stored list is ignored
//! (never enforced, never inherited by a minted token) and asking for one is refused. `private`
//! alone is not that edition: community builds carry it.
use windmill_common::error::Error;
pub fn token_ip_allowlists_unavailable() -> Error {
Error::BadRequest("Token IP allowlists are a Windmill Enterprise Edition feature".to_string())
}
#[cfg(all(feature = "private", feature = "enterprise"))]
pub use crate::token_ip_allowlist_ee::{client_ip_allowed, load_allowed_ips, token_ip_allowlist};
#[cfg(not(all(feature = "private", feature = "enterprise")))]
pub use ce::*;
#[cfg(not(all(feature = "private", feature = "enterprise")))]
mod ce {
use windmill_common::{client_ip::IpNet, error};
pub fn load_allowed_ips(_stored: Option<Vec<String>>) -> Option<Vec<IpNet>> {
None
}
pub fn client_ip_allowed(
_allowed: Option<&[IpNet]>,
_client_ip: Option<std::net::IpAddr>,
) -> bool {
true
}
pub fn token_ip_allowlist(
_caller: Option<&[IpNet]>,
requested: Option<&[String]>,
) -> error::Result<Option<Vec<String>>> {
match requested {
Some(_) => Err(super::token_ip_allowlists_unavailable()),
None => Ok(None),
}
}
}
@@ -69,6 +69,7 @@ fn test_authed() -> ApiAuthed {
credential_expiry: None,
mcp_client: None,
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
allowed_ips: None,
}
}
@@ -342,6 +342,10 @@ async fn test_rotate_webhook_token(db: Pool<Postgres>) -> anyhow::Result<()> {
)
.execute(&db)
.await?;
sqlx::query("UPDATE token SET allowed_ips = '{10.0.0.0/8}' WHERE token_hash = $1")
.bind(&original_hash)
.execute(&db)
.await?;
// Rotate onto a different runnable than the original token was minted for: a rename moves the
// trigger, and rotation has to follow it rather than carry the old scopes forward.
@@ -361,6 +365,16 @@ async fn test_rotate_webhook_token(db: Pool<Postgres>) -> anyhow::Result<()> {
// New token's hash should exist in DB with the per-service label and expiration
let new_hash = hash_token(&rotated.new_token);
let allowed_ips: Option<Vec<String>> =
sqlx::query_scalar("SELECT allowed_ips::text[] FROM token WHERE token_hash = $1")
.bind(&new_hash)
.fetch_one(&db)
.await?;
assert_eq!(
allowed_ips,
Some(vec!["10.0.0.0/8".to_string()]),
"rotation must keep the token's IP restriction"
);
let new_row = sqlx::query!(
"SELECT label, expiration, scopes FROM token WHERE token_hash = $1",
new_hash
+2 -1
View File
@@ -3666,6 +3666,7 @@ async fn toggle_workspace_error_handler(
}
async fn get_tokened_raw_script_by_path(
windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp,
Extension(user_db): Extension<UserDB>,
Extension(db): Extension<DB>,
Extension(cache): Extension<Arc<AuthCache>>,
@@ -3673,7 +3674,7 @@ async fn get_tokened_raw_script_by_path(
Query(query): Query<RawScriptByPathQuery>,
) -> Result<StringWithLength> {
let authed = cache
.get_authed(Some(w_id.clone()), &token)
.get_authed(Some(w_id.clone()), &token, client_ip)
.await
.ok_or_else(|| Error::NotAuthorized("Invalid token".to_string()))?;
return raw_script_by_path(
+28 -6
View File
@@ -333,6 +333,8 @@ pub struct TruncatedToken {
pub scopes: Option<Vec<String>>,
pub workspace_id: Option<String>,
pub read_only: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub allowed_ips: Option<Vec<String>>,
}
// NewToken is re-exported from windmill-api-auth above
@@ -3000,6 +3002,12 @@ async fn refresh_token(
.to_string(),
));
}
// A session carries no IP restriction, so exchanging for one would lift it.
if authed.allowed_ips.is_some() {
return Err(Error::NotAuthorized(
"A token restricted to IP addresses cannot be exchanged for a session".to_string(),
));
}
let t_hash = windmill_common::auth::hash_token(&token);
// Only a live, non-impersonation row may be exchanged for a session: an impersonation must
// end at its 24h expiry, not become a renewable service-account session billed as active.
@@ -3416,6 +3424,10 @@ async fn impersonate(
));
}
let allowed_ips = windmill_api_auth::token_ip_allowlist(
authed.allowed_ips.as_deref(),
new_token.allowed_ips.as_deref(),
)?;
let impersonated = new_token.impersonate_email.unwrap();
let is_super_admin = sqlx::query_scalar!(
@@ -3430,15 +3442,16 @@ async fn impersonate(
sqlx::query!(
"INSERT INTO token
(token_hash, token_prefix, token, email, label, expiration, super_admin)
VALUES ($1, $2, $3, $4, $5, $6, $7)",
(token_hash, token_prefix, token, email, label, expiration, super_admin, allowed_ips)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8::text[]::cidr[])",
t_hash,
t_prefix,
plaintext as Option<&str>,
impersonated,
new_token.label,
expiration,
is_super_admin
is_super_admin,
allowed_ips.as_deref()
)
.execute(&mut *tx)
.await?;
@@ -3562,6 +3575,12 @@ async fn create_login_link(
) -> Result<(StatusCode, Json<LoginLink>)> {
require_super_admin(&db, &authed).await?;
forbid_superadmin_job_token(&db, &authed.email, job_id).await?;
// The link opens into a session that carries no IP restriction.
if authed.allowed_ips.is_some() {
return Err(Error::NotAuthorized(
"A token restricted to IP addresses cannot create login links".to_string(),
));
}
let email = nl.email.to_lowercase();
let rd = match nl.rd {
@@ -4020,7 +4039,8 @@ async fn list_tokens(
sqlx::query_as!(
TruncatedToken,
"SELECT label, token_prefix, expiration, created_at, \
last_used_at, scopes, workspace_id, read_only FROM token WHERE email = $1 AND (label != 'ephemeral-script' OR label IS NULL)
last_used_at, scopes, workspace_id, read_only, allowed_ips::text[] AS allowed_ips \
FROM token WHERE email = $1 AND (label != 'ephemeral-script' OR label IS NULL)
ORDER BY created_at DESC LIMIT $2 OFFSET $3",
email,
per_page as i64,
@@ -4032,7 +4052,8 @@ async fn list_tokens(
sqlx::query_as!(
TruncatedToken,
"SELECT label, token_prefix, expiration, created_at, \
last_used_at, scopes, workspace_id, read_only FROM token WHERE email = $1
last_used_at, scopes, workspace_id, read_only, allowed_ips::text[] AS allowed_ips \
FROM token WHERE email = $1
ORDER BY created_at DESC LIMIT $2 OFFSET $3",
email,
per_page as i64,
@@ -4337,6 +4358,7 @@ async fn get_all_runnables(
Extension(db): Extension<UserDB>,
authed: ApiAuthed,
Tokened { token }: Tokened,
ClientIp(client_ip): ClientIp,
Extension(cache): Extension<Arc<windmill_api_auth::AuthCache>>,
) -> JsonResult<Vec<Runnable>> {
let mut tx = db.clone().begin(&authed).await?;
@@ -4352,7 +4374,7 @@ async fn get_all_runnables(
for workspace in workspaces {
let nauthed = cache
.get_authed(Some(workspace.clone()), &token)
.get_authed(Some(workspace.clone()), &token, client_ip)
.await
.ok_or_else(|| {
Error::BadRequest(format!("not authorized to access workspace: {workspace}"))
@@ -14469,6 +14469,7 @@ async fn load_workspace_authed(
credential_expiry: base_authed.credential_expiry,
mcp_client: base_authed.mcp_client.clone(),
capabilities: None,
allowed_ips: None,
});
};
@@ -14511,6 +14512,7 @@ async fn load_workspace_authed(
credential_expiry: base_authed.credential_expiry,
mcp_client: base_authed.mcp_client.clone(),
capabilities: None,
allowed_ips: None,
})
}
+39
View File
@@ -41,6 +41,26 @@ paths:
schema:
type: string
/client_ip:
get:
summary: get the caller's IP address
description: |
The address of the client making the request, as Windmill resolves it for per-IP checks such
as token IP allowlists: forwarding headers are believed only from the proxies in
TRUSTED_PROXIES. Behind a proxy that is not listed, this is the proxy's address. Empty when
the server cannot tell.
operationId: getClientIp
tags:
- settings
security: []
responses:
"200":
description: the caller's IP address
content:
text/plain:
schema:
type: string
/health/status:
get:
summary: health status
@@ -34079,6 +34099,11 @@ components:
type: string
read_only:
type: boolean
allowed_ips:
type: array
description: IPs or CIDRs the token may be used from; absent when it may be used from anywhere.
items:
type: string
required:
- token_prefix
- created_at
@@ -34215,6 +34240,15 @@ components:
For an MCP token (an `mcp:` scope) owned by a superadmin: carry the owner's
superadmin rights, reaching every workspace rather than only their
memberships. Ignored for other tokens, which always carry them.
allowed_ips:
type: array
description: |
IPs or CIDRs (IPv4 or IPv6) the token may be used from; omit to allow any.
A request from elsewhere is refused as unauthenticated. A token that is itself
restricted can only create tokens within its own networks, and creates one
restricted to them when this is omitted.
items:
type: string
NewTokenImpersonate:
type: object
@@ -34228,6 +34262,11 @@ components:
type: string
workspace_id:
type: string
allowed_ips:
type: array
description: IPs or CIDRs the token may be used from; omit to allow any.
items:
type: string
required:
- impersonate_email
+2 -1
View File
@@ -1999,6 +1999,7 @@ async fn get_app_embed_token(
// Resolved from the token when there is one: this endpoint serves anonymous
// viewers too, so it cannot take an extractor that requires auth.
OptTokened { token }: OptTokened,
windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp,
Extension(cache): Extension<Arc<AuthCache>>,
Extension(user_db): Extension<UserDB>,
Extension(db): Extension<DB>,
@@ -2007,7 +2008,7 @@ async fn get_app_embed_token(
) -> JsonResult<EmbedTokenResponse> {
let job_id = match token.as_deref() {
Some(t) => cache
.get_opt_job_authed(Some(w_id.clone()), t)
.get_opt_job_authed(Some(w_id.clone()), t, client_ip)
.await
.and_then(|x| x.job_id),
None => None,
+24 -5
View File
@@ -36,6 +36,7 @@ pub fn global_service() -> Router {
/// discloses existence only inside a workspace they belong to.
async fn require_concurrency_key_read(
token: &str,
client_ip: Option<std::net::IpAddr>,
cache: &AuthCache,
db: &DB,
user_db: &UserDB,
@@ -55,7 +56,7 @@ async fn require_concurrency_key_read(
.ok_or_else(not_found)?;
let authed_in_workspace = cache
.get_authed(Some(job.workspace_id.clone()), token)
.get_authed(Some(job.workspace_id.clone()), token, client_ip)
.await
.ok_or_else(not_found)?;
windmill_api_auth::check_job_token_scope(&authed_in_workspace, || "jobs:read".to_string())?;
@@ -75,14 +76,23 @@ async fn require_concurrency_key_read(
async fn get_concurrency_key(
_authed: ApiAuthed,
Tokened { token }: Tokened,
windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp,
Extension(cache): Extension<Arc<AuthCache>>,
Extension(db): Extension<DB>,
Extension(user_db): Extension<UserDB>,
OptViewToken(view_token): OptViewToken,
Path(job_id): Path<Uuid>,
) -> JsonResult<Option<String>> {
require_concurrency_key_read(&token, &cache, &db, &user_db, view_token.as_deref(), job_id)
.await?;
require_concurrency_key_read(
&token,
client_ip,
&cache,
&db,
&user_db,
view_token.as_deref(),
job_id,
)
.await?;
let key = sqlx::query_scalar!("SELECT key FROM concurrency_key WHERE job_id = $1", job_id)
.fetch_optional(&db)
.await?;
@@ -103,14 +113,23 @@ struct ConcurrencyKeyStatus {
async fn get_concurrency_key_status(
_authed: ApiAuthed,
Tokened { token }: Tokened,
windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp,
Extension(cache): Extension<Arc<AuthCache>>,
Extension(db): Extension<DB>,
Extension(user_db): Extension<UserDB>,
OptViewToken(view_token): OptViewToken,
Path(job_id): Path<Uuid>,
) -> JsonResult<Option<ConcurrencyKeyStatus>> {
require_concurrency_key_read(&token, &cache, &db, &user_db, view_token.as_deref(), job_id)
.await?;
require_concurrency_key_read(
&token,
client_ip,
&cache,
&db,
&user_db,
view_token.as_deref(),
job_id,
)
.await?;
let status = sqlx::query_as!(
ConcurrencyKeyStatus,
"SELECT key, original_scheduled_for AS deferred_from, released_at FROM concurrency_key WHERE job_id = $1",
+2 -1
View File
@@ -1061,6 +1061,7 @@ pub struct TransferDraftsResponse {
async fn transfer_drafts(
authed: ApiAuthed,
tokened: crate::auth::Tokened,
windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp,
Extension(auth_cache): Extension<std::sync::Arc<crate::auth::AuthCache>>,
Extension(db): Extension<DB>,
Extension(user_db): Extension<UserDB>,
@@ -1111,7 +1112,7 @@ async fn transfer_drafts(
// own claims, not the database's. A job token stays refused even where its claims
// list both workspaces.
let authed_there = auth_cache
.get_authed(Some(target.to_string()), &tokened.token)
.get_authed(Some(target.to_string()), &tokened.token, client_ip)
.await
.filter(|a| a.job_id.is_none())
.ok_or_else(|| Error::PermissionDenied(format!("this token cannot act on {target}")))?;
+1
View File
@@ -13862,6 +13862,7 @@ mod approval_view_gate_tests {
credential_expiry: None,
mcp_client: None,
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
allowed_ips: None,
}
}
+11
View File
@@ -422,6 +422,7 @@ async fn inject_agent_authed(
credential_expiry: None,
mcp_client: None,
capabilities: None,
allowed_ips: None,
},
job_id: None,
});
@@ -1178,6 +1179,7 @@ pub async fn run_server(
}
})
.route("/version", get(git_v))
.route("/client_ip", get(client_ip))
.nest("/health/status", health::status_service())
.route("/min_keep_alive_version", get(min_keep_alive_version))
.route("/uptodate", get(is_up_to_date))
@@ -1424,6 +1426,15 @@ async fn git_v() -> String {
format!("CE {GIT_VERSION}")
}
/// The caller's address as every IP check sees it, so a device can learn what to put in a token's
/// allowed IPs, and an admin can tell a proxy missing from `TRUSTED_PROXIES` (its own address
/// comes back). Unauthenticated: it tells the caller only where it is calling from.
async fn client_ip(
windmill_common::client_ip::ClientIp(ip): windmill_common::client_ip::ClientIp,
) -> String {
ip.map(|ip| ip.to_string()).unwrap_or_default()
}
async fn min_keep_alive_version() -> Json<serde_json::Value> {
let worker = windmill_common::min_version::MIN_KEEP_ALIVE_VERSION;
let agent = windmill_common::min_version::AGENT_MIN_KEEP_ALIVE_VERSION;
+13 -3
View File
@@ -500,12 +500,16 @@ impl McpBackend for WindmillBackend {
async fn resolve_workspace_auth(
&self,
token: &str,
token: &McpToken,
workspace_id: &str,
) -> BackendResult<ApiAuthed> {
let authed = self
.auth_cache
.get_authed(Some(workspace_id.to_string()), token)
.get_authed(
Some(workspace_id.to_string()),
&token.token,
token.client_ip,
)
.await
.ok_or_else(|| {
ErrorData::invalid_params(
@@ -758,7 +762,13 @@ pub async fn extract_workspace_from_token(
.is_some_and(|s| s.iter().any(|scope| scope.starts_with("mcp:")));
if is_mcp {
request.extensions_mut().insert(MultiWorkspaceMcp);
request.extensions_mut().insert(McpToken(token));
let client_ip = windmill_common::client_ip::client_ip_of(
request.extensions(),
request.headers(),
);
request
.extensions_mut()
.insert(McpToken { token, client_ip });
}
}
}
@@ -885,6 +885,12 @@ async fn oauth_approve_inner(
// (GHSA-hfh4-cx4h-3fcr). Guarded at the shared inner fn: both the workspaced and
// the gateway approve route reach the exchange through here.
forbid_elevated_job_token(db, &authed.email, authed.job_id).await?;
// The exchanged token carries no IP restriction, so approving would lift the caller's.
if authed.allowed_ips.is_some() {
return Err(Error::NotAuthorized(
"A token restricted to IP addresses cannot approve an MCP client".to_string(),
));
}
let caller_restricted = authed
.scopes
+1
View File
@@ -1467,6 +1467,7 @@ mod tests {
credential_expiry: None,
mcp_client: None,
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
allowed_ips: None,
}
}
@@ -368,6 +368,7 @@ async fn get_http_route_trigger(
route_path: &str,
auth_cache: &Arc<AuthCache>,
token: Option<&String>,
client_ip: Option<std::net::IpAddr>,
db: &DB,
user_db: UserDB,
method: &http::Method,
@@ -408,7 +409,7 @@ async fn get_http_route_trigger(
let username_override = if let AuthenticationMethod::Windmill = trigger.authentication_method {
let opt_authed = if let Some(token) = token {
auth_cache
.get_authed(Some(trigger.workspace_id.clone()), token)
.get_authed(Some(trigger.workspace_id.clone()), token, client_ip)
.await
} else {
None
@@ -496,6 +497,7 @@ async fn route_job(
Extension(auth_cache): Extension<Arc<AuthCache>>,
Extension(cors_policy): Extension<ResolvedCorsPolicy>,
OptTokened { token }: OptTokened,
windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp,
Path(route_path): Path<StripPath>,
headers: HeaderMap,
args: RawHttpTriggerArgs,
@@ -506,6 +508,7 @@ async fn route_job(
route_path,
&auth_cache,
token.as_ref(),
client_ip,
&db,
user_db.clone(),
&args.0.metadata.method,
+9 -5
View File
@@ -12,8 +12,8 @@ use std::net::{IpAddr, SocketAddr};
use std::sync::LazyLock;
use axum::extract::{ConnectInfo, FromRequestParts};
use axum::http::{request::Parts, HeaderMap, HeaderName};
use ipnet::IpNet;
use axum::http::{request::Parts, Extensions, HeaderMap, HeaderName};
pub use ipnet::IpNet;
/// Loopback only on a self-hosted instance: it is often reached directly from a private network,
/// whose clients could otherwise name any address they like. A reverse proxy on a private
@@ -92,11 +92,15 @@ impl<S: Send + Sync> FromRequestParts<S> for ClientIp {
}
pub fn client_ip_of_parts(parts: &Parts) -> Option<IpAddr> {
let peer = parts
.extensions
client_ip_of(&parts.extensions, &parts.headers)
}
/// The same, for a handler holding the whole `Request` rather than its parts.
pub fn client_ip_of(extensions: &Extensions, headers: &HeaderMap) -> Option<IpAddr> {
let peer = extensions
.get::<ConnectInfo<SocketAddr>>()
.map(|c| c.0.ip())?;
Some(resolve_client_ip(peer, &parts.headers, &CLIENT_IP_CONFIG))
Some(resolve_client_ip(peer, headers, &CLIENT_IP_CONFIG))
}
/// An IPv4 client of a dual-stack listener arrives as `::ffff:a.b.c.d`; compare it as IPv4 so
+7 -2
View File
@@ -28,9 +28,14 @@ pub struct MultiWorkspaceMcp;
pub struct NoEndpointTools;
/// Raw bearer token wrapper for Axum extensions. In multi-workspace mode the
/// runner needs the raw token to re-resolve auth for each requested workspace.
/// runner needs the raw token to re-resolve auth for each requested workspace,
/// and the request's client address, which an IP-restricted token is checked
/// against on every resolution.
#[derive(Clone, Debug)]
pub struct McpToken(pub String);
pub struct McpToken {
pub token: String,
pub client_ip: Option<std::net::IpAddr>,
}
/// Summary of a workspace the caller can access, returned by the
/// `list_workspaces` tool in multi-workspace mode.
+3 -2
View File
@@ -10,7 +10,8 @@ use serde_json::Value;
use std::collections::HashMap;
use crate::common::types::{
FlowInfo, HubScriptInfo, ResourceInfo, ResourceType, SchemaType, ScriptInfo, WorkspaceInfo,
FlowInfo, HubScriptInfo, McpToken, ResourceInfo, ResourceType, SchemaType, ScriptInfo,
WorkspaceInfo,
};
use crate::server::endpoints::EndpointTool;
@@ -255,7 +256,7 @@ pub trait McpBackend: Send + Sync + Clone + 'static {
/// calls (the base auth carries no workspace-specific permissions).
async fn resolve_workspace_auth(
&self,
token: &str,
token: &McpToken,
workspace_id: &str,
) -> BackendResult<Self::Auth>;
+3 -3
View File
@@ -160,7 +160,7 @@ pub(super) enum McpMode {
/// The token has no bound workspace (`workspace_id IS NULL`). Tools take an
/// explicit `workspace_id` argument; the wrapped value is the raw bearer
/// token, used to re-resolve auth per requested workspace.
Multi(String),
Multi(McpToken),
}
/// Everything a request carries besides its MCP payload.
@@ -207,7 +207,7 @@ impl<B: McpBackend> Runner<B> {
tracing::error!("MultiWorkspaceMcp set but McpToken missing");
ErrorData::internal_error("MCP token not found for multi-workspace session", None)
})?;
McpMode::Multi(token.0.clone())
McpMode::Multi(token.clone())
} else {
let workspace_id = http_parts
.extensions
@@ -1204,7 +1204,7 @@ impl<B: McpBackend> Runner<B> {
async fn call_tool_multi(
&self,
base_auth: &B::Auth,
token: &str,
token: &McpToken,
scope_config: &crate::common::scope::McpScopeConfig,
read_only: bool,
name: std::borrow::Cow<'static, str>,
+5 -3
View File
@@ -1206,7 +1206,8 @@ pub async fn rotate_webhook_token(
use windmill_common::utils::rd_string;
let old = match sqlx::query!(
"SELECT email, workspace_id, super_admin, owner FROM token WHERE token_hash = $1",
"SELECT email, workspace_id, super_admin, owner, allowed_ips::text[] AS allowed_ips
FROM token WHERE token_hash = $1",
old_token_hash
)
.fetch_optional(db)
@@ -1237,8 +1238,8 @@ pub async fn rotate_webhook_token(
.map(|d| Utc::now() + d);
sqlx::query!(
"INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes, workspace_id, owner, expiration)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
"INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes, workspace_id, owner, expiration, allowed_ips)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::text[]::cidr[])",
new_hash,
new_prefix,
plaintext as Option<&str>,
@@ -1249,6 +1250,7 @@ pub async fn rotate_webhook_token(
old.workspace_id,
old.owner,
new_expiration,
old.allowed_ips.as_deref(),
)
.execute(db)
.await?;
+17
View File
@@ -246,3 +246,20 @@ Symbols, not line numbers, are cited: they drift less.
`TRUSTED_PROXIES`, or its edge address is the client. On cloud, the private-range default
also trusts job containers that can reach the server directly. Only the main API server carries the peer: a router called without connect
info (tests, internal dispatch) sees `None`, and per-IP decisions skip or refuse it.
- **`token.allowed_ips`** is EE. A CE build drops a stored list when it loads the token, so it
neither checks the list nor passes it on, and refuses a request that sets one. An EE build
keeps enforcing stored lists when its license lapses; only setting a new one needs a valid
license. The rest of this bullet describes an EE build. The column (`cidr[]`, `NULL` =
anywhere) restricts where a token row may be
used. `AuthCache::get_opt_job_authed` takes the request's client IP and refuses the token
outside its networks, or when the IP is unknown, so every path that resolves a request's
token passes that request's `ClientIp` (MCP's multi-workspace mode carries it in
`McpToken`). The list rides on the cached `ApiAuthed`, checked per request, never folded
into the cache entry. A restricted token cannot lift its restriction: every mint from the
caller's identity holds the new row within the caller's networks (the caller's list when
none is asked for). That is `create_token_internal` (`tokens/create`, app SDK and embed
tokens, native trigger webhook tokens, which then only work from those networks),
`tokens/impersonate` and service-account impersonation. `refresh_token`, the MCP OAuth
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.
@@ -1,10 +1,16 @@
<script lang="ts">
import { onMount, untrack } from 'svelte'
import { superadmin, userWorkspaces, usersWorkspaceStore, type UserWorkspace } from '$lib/stores'
import {
enterpriseLicense,
superadmin,
userWorkspaces,
usersWorkspaceStore,
type UserWorkspace
} from '$lib/stores'
import { Button, Skeleton } from '../common'
import { triggerableByAI } from '$lib/actions/triggerableByAI.svelte'
import Toggle from '../Toggle.svelte'
import { SettingService, UserService, type NewToken } from '$lib/gen'
import { SettingService, SettingsService, UserService, type NewToken } from '$lib/gen'
import { listEveryWorkspace, mcpTokenUrlDisabled } from '$lib/mcpAuth'
import { apiBaseUrl } from '$lib/apiBaseUrl.svelte'
import TokenDisplay from './TokenDisplay.svelte'
@@ -70,6 +76,29 @@
let pickedScopes = $state<string[] | null>(null)
let readOnly = $state(false)
let allowedIpsText = $state('')
let allowedIps = $derived(
allowedIpsText
.split(/[\s,]+/)
.map((s) => s.trim())
.filter((s) => s.length > 0)
)
// The address this browser calls from, as the server's IP checks resolve it.
let clientIp = $state<string | undefined>(undefined)
let clientIpRequested = false
$effect(() => {
if ($enterpriseLicense && !clientIpRequested) {
clientIpRequested = true
SettingsService.getClientIp()
.then((ip) => (clientIp = ip.trim() || undefined))
.catch(() => {})
}
})
function addClientIp() {
if (clientIp && !allowedIps.includes(clientIp)) {
allowedIpsText = [...allowedIps, clientIp].join(', ')
}
}
// How this instance lets an MCP client in. `oauth` means it refuses `?token=`, so a
// generated token would not get a client in and the URL is handed over bare instead.
// A failed read lands on `oauth`: the bare URL works whichever way the setting is,
@@ -218,7 +247,9 @@
scopes: tokenScopes,
workspace_id: tokenWorkspaceId,
read_only: mcpMode ? false : readOnly,
super_admin: mcpMode && mcpSuperAdmin
super_admin: mcpMode && mcpSuperAdmin,
allowed_ips:
$enterpriseLicense && !mcpMode && allowedIps.length > 0 ? allowedIps : undefined
} as NewToken
})
@@ -543,6 +574,35 @@
</div>
</div>
{#if $enterpriseLicense}
<div class="mt-4 flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">
Allowed IPs <span class="font-normal text-secondary">(optional)</span>
</span>
<TextInput
inputProps={{ type: 'text', placeholder: '203.0.113.4, 10.0.0.0/8' }}
bind:value={allowedIpsText}
class="w-full"
/>
<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.
</p>
{#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>
{#if !allowedIps.includes(clientIp)}
<Button variant="subtle" unifiedSize="2xs" onclick={addClientIp}>Add</Button>
{/if}
</div>
{/if}
</div>
{:else}
<p class="mt-4 text-2xs text-hint">
Restricting a token to IP ranges requires Enterprise Edition.
</p>
{/if}
{#if !scopes || scopes.length === 0}
<div class="mt-4">
<ScopesPicker
@@ -2,6 +2,7 @@
import { untrack } from 'svelte'
import TableCustom from '$lib/components/TableCustom.svelte'
import { displayDate } from '$lib/utils'
import { enterpriseLicense } from '$lib/stores'
import { UserService, type TruncatedToken } from '$lib/gen'
import { sendUserToast } from '$lib/toast'
import CreateToken from './CreateToken.svelte'
@@ -189,7 +190,7 @@
{#snippet body()}
<tbody>
{#if tokens && tokens.length > 0}
{#each tokens as { token_prefix, expiration, label, scopes, workspace_id, read_only } (token_prefix)}
{#each tokens as { token_prefix, expiration, label, scopes, workspace_id, read_only, allowed_ips } (token_prefix)}
{@const badge = expirationBadge(expiration, label)}
<tr>
<td class="w-32 text-xs text-primary">{token_prefix}****</td>
@@ -210,6 +211,15 @@
{#if read_only}
<Badge color="blue" small>Read-only</Badge>
{/if}
{#if $enterpriseLicense && allowed_ips && allowed_ips.length > 0}
<span title="Usable only from {allowed_ips.join(', ')}">
<Badge color="gray" small>
{allowed_ips.length === 1
? allowed_ips[0]
: `${allowed_ips.length} IP ranges`}
</Badge>
</span>
{/if}
<span class="truncate">{shownScopes(scopes)}</span>
</div>
</td>