From f555024e7368bd2ce260f27af9627d00769be66d Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Thu, 26 Nov 2026 20:27:52 +0000 Subject: [PATCH] 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 * fix: read forwarded-for as raw bytes and add an explicit client ip header Co-Authored-By: Claude Opus 5.5 * fix: strip the source port from cloudfront-viewer-address before parsing Co-Authored-By: Claude Opus 5.5 * style: rustfmt client_ip Co-Authored-By: Claude Opus 5.5 * feat: restrict api tokens to allowed ip ranges Co-Authored-By: Claude Opus 5.5 * fix: inherit token ip restrictions on every mint and refuse login links Co-Authored-By: Claude Opus 5.5 * fix: keep a webhook token's ip restriction when rotating it Co-Authored-By: Claude Opus 5.5 * test: pin that webhook token rotation keeps allowed_ips Co-Authored-By: Claude Opus 5.5 * perf: resolve the client ip only for restricted tokens and throttle refusal logs Co-Authored-By: Claude Opus 5.5 * 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 * feat: make token ip allowlists an ee feature Co-Authored-By: Claude Opus 5.5 * refactor: move token ip allowlist logic into ee Co-Authored-By: Claude Opus 5.5 * 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 Co-authored-by: windmill-internal-app[bot] --- ...21edaefc5a7732c2bb8f6599fa8fd51c73745.json | 24 +++ ...87b938312a03f5ff1e3fe76f432bdf93af621.json | 24 +++ ...0978fdab66c004836cbee4b39fb7c4342e44e.json | 21 +++ ...1ddbeeb5da97c5c40a50c7945303c9930cb1b.json | 21 +++ ...4ab70ce13b504b4c80364d4ceecede98e81ae.json | 46 +++++ ...6a937e69bd92ba37064d7134791b8d901cec8.json | 72 ++++++++ ...a7fae4d13e273ed22f430b74b62e0c0614e2a.json | 59 +++++++ ...8db8a224bd4b1167dd584ae8f4e1ffa20e326.json | 72 ++++++++ backend/ee-repo-ref.txt | 2 +- .../20261126110005_token_allowed_ips.down.sql | 1 + .../20261126110005_token_allowed_ips.up.sql | 1 + backend/tests/postgres_trigger_scope.rs | 1 + backend/tests/reserved_control_args.rs | 1 + backend/tests/token_allowed_ips.rs | 83 +++++++++ backend/tests/trigger_listener_queries.rs | 1 + backend/tests/wm_token_confinement.rs | 1 + .../tests/dbt_pinned_graph.rs | 1 + backend/windmill-api-auth/src/auth.rs | 163 ++++++++++++++++-- backend/windmill-api-auth/src/lib.rs | 27 ++- .../src/token_ip_allowlist_oss.rs | 49 ++++++ .../tests/native_triggers.rs | 1 + .../tests/token_hash.rs | 14 ++ backend/windmill-api-scripts/src/scripts.rs | 3 +- backend/windmill-api-users/src/users.rs | 34 +++- .../windmill-api-workspaces/src/workspaces.rs | 2 + backend/windmill-api/openapi.yaml | 39 +++++ backend/windmill-api/src/apps.rs | 3 +- .../windmill-api/src/concurrency_groups.rs | 29 +++- backend/windmill-api/src/drafts.rs | 3 +- backend/windmill-api/src/jobs.rs | 1 + backend/windmill-api/src/lib.rs | 11 ++ backend/windmill-api/src/mcp/core.rs | 16 +- backend/windmill-api/src/mcp/oauth_server.rs | 6 + backend/windmill-api/src/mcp/utils.rs | 1 + .../windmill-api/src/triggers/http/handler.rs | 5 +- backend/windmill-common/src/client_ip.rs | 14 +- backend/windmill-mcp/src/common/types.rs | 9 +- backend/windmill-mcp/src/server/backend.rs | 5 +- backend/windmill-mcp/src/server/runner.rs | 6 +- backend/windmill-native-triggers/src/lib.rs | 8 +- docs/auth-surface.md | 17 ++ .../components/settings/CreateToken.svelte | 66 ++++++- .../components/settings/TokensTable.svelte | 12 +- 43 files changed, 922 insertions(+), 53 deletions(-) create mode 100644 backend/.sqlx/query-2cd408ec9b9547ae3095bcb8f1e21edaefc5a7732c2bb8f6599fa8fd51c73745.json create mode 100644 backend/.sqlx/query-35e54cdfd2df6d2ec4a9777490a87b938312a03f5ff1e3fe76f432bdf93af621.json create mode 100644 backend/.sqlx/query-45e44eaaeaba49965c14bfea0af0978fdab66c004836cbee4b39fb7c4342e44e.json create mode 100644 backend/.sqlx/query-6aab07d50008cb21b5ea1e23c5d1ddbeeb5da97c5c40a50c7945303c9930cb1b.json create mode 100644 backend/.sqlx/query-76355b8f5319afcecf2514c14a64ab70ce13b504b4c80364d4ceecede98e81ae.json create mode 100644 backend/.sqlx/query-b45ee8dffade9cd25f02e3906446a937e69bd92ba37064d7134791b8d901cec8.json create mode 100644 backend/.sqlx/query-bf8144fe246dcc0fbfb73b37036a7fae4d13e273ed22f430b74b62e0c0614e2a.json create mode 100644 backend/.sqlx/query-df74a087ba68636152e1b9ae5d38db8a224bd4b1167dd584ae8f4e1ffa20e326.json create mode 100644 backend/migrations/20261126110005_token_allowed_ips.down.sql create mode 100644 backend/migrations/20261126110005_token_allowed_ips.up.sql create mode 100644 backend/tests/token_allowed_ips.rs create mode 100644 backend/windmill-api-auth/src/token_ip_allowlist_oss.rs diff --git a/backend/.sqlx/query-2cd408ec9b9547ae3095bcb8f1e21edaefc5a7732c2bb8f6599fa8fd51c73745.json b/backend/.sqlx/query-2cd408ec9b9547ae3095bcb8f1e21edaefc5a7732c2bb8f6599fa8fd51c73745.json new file mode 100644 index 0000000000..997bd7d588 --- /dev/null +++ b/backend/.sqlx/query-2cd408ec9b9547ae3095bcb8f1e21edaefc5a7732c2bb8f6599fa8fd51c73745.json @@ -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" +} diff --git a/backend/.sqlx/query-35e54cdfd2df6d2ec4a9777490a87b938312a03f5ff1e3fe76f432bdf93af621.json b/backend/.sqlx/query-35e54cdfd2df6d2ec4a9777490a87b938312a03f5ff1e3fe76f432bdf93af621.json new file mode 100644 index 0000000000..7a40e26873 --- /dev/null +++ b/backend/.sqlx/query-35e54cdfd2df6d2ec4a9777490a87b938312a03f5ff1e3fe76f432bdf93af621.json @@ -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" +} diff --git a/backend/.sqlx/query-45e44eaaeaba49965c14bfea0af0978fdab66c004836cbee4b39fb7c4342e44e.json b/backend/.sqlx/query-45e44eaaeaba49965c14bfea0af0978fdab66c004836cbee4b39fb7c4342e44e.json new file mode 100644 index 0000000000..c8c9b71978 --- /dev/null +++ b/backend/.sqlx/query-45e44eaaeaba49965c14bfea0af0978fdab66c004836cbee4b39fb7c4342e44e.json @@ -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" +} diff --git a/backend/.sqlx/query-6aab07d50008cb21b5ea1e23c5d1ddbeeb5da97c5c40a50c7945303c9930cb1b.json b/backend/.sqlx/query-6aab07d50008cb21b5ea1e23c5d1ddbeeb5da97c5c40a50c7945303c9930cb1b.json new file mode 100644 index 0000000000..2d87cab61f --- /dev/null +++ b/backend/.sqlx/query-6aab07d50008cb21b5ea1e23c5d1ddbeeb5da97c5c40a50c7945303c9930cb1b.json @@ -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" +} diff --git a/backend/.sqlx/query-76355b8f5319afcecf2514c14a64ab70ce13b504b4c80364d4ceecede98e81ae.json b/backend/.sqlx/query-76355b8f5319afcecf2514c14a64ab70ce13b504b4c80364d4ceecede98e81ae.json new file mode 100644 index 0000000000..12703bb232 --- /dev/null +++ b/backend/.sqlx/query-76355b8f5319afcecf2514c14a64ab70ce13b504b4c80364d4ceecede98e81ae.json @@ -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" +} diff --git a/backend/.sqlx/query-b45ee8dffade9cd25f02e3906446a937e69bd92ba37064d7134791b8d901cec8.json b/backend/.sqlx/query-b45ee8dffade9cd25f02e3906446a937e69bd92ba37064d7134791b8d901cec8.json new file mode 100644 index 0000000000..82b60dbd1f --- /dev/null +++ b/backend/.sqlx/query-b45ee8dffade9cd25f02e3906446a937e69bd92ba37064d7134791b8d901cec8.json @@ -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" +} diff --git a/backend/.sqlx/query-bf8144fe246dcc0fbfb73b37036a7fae4d13e273ed22f430b74b62e0c0614e2a.json b/backend/.sqlx/query-bf8144fe246dcc0fbfb73b37036a7fae4d13e273ed22f430b74b62e0c0614e2a.json new file mode 100644 index 0000000000..2eb27c8a96 --- /dev/null +++ b/backend/.sqlx/query-bf8144fe246dcc0fbfb73b37036a7fae4d13e273ed22f430b74b62e0c0614e2a.json @@ -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" +} diff --git a/backend/.sqlx/query-df74a087ba68636152e1b9ae5d38db8a224bd4b1167dd584ae8f4e1ffa20e326.json b/backend/.sqlx/query-df74a087ba68636152e1b9ae5d38db8a224bd4b1167dd584ae8f4e1ffa20e326.json new file mode 100644 index 0000000000..1d9934e225 --- /dev/null +++ b/backend/.sqlx/query-df74a087ba68636152e1b9ae5d38db8a224bd4b1167dd584ae8f4e1ffa20e326.json @@ -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" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 70d595cc70..4d7a56d49a 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -f0417fbaee7b4661bebc0123d34ccd3aba87c6a7 +cf0cee4ef89bd0b8b2399ced7b12ccc9a3d43dd8 diff --git a/backend/migrations/20261126110005_token_allowed_ips.down.sql b/backend/migrations/20261126110005_token_allowed_ips.down.sql new file mode 100644 index 0000000000..12fba41917 --- /dev/null +++ b/backend/migrations/20261126110005_token_allowed_ips.down.sql @@ -0,0 +1 @@ +ALTER TABLE token DROP COLUMN IF EXISTS allowed_ips; diff --git a/backend/migrations/20261126110005_token_allowed_ips.up.sql b/backend/migrations/20261126110005_token_allowed_ips.up.sql new file mode 100644 index 0000000000..849c3d59ee --- /dev/null +++ b/backend/migrations/20261126110005_token_allowed_ips.up.sql @@ -0,0 +1 @@ +ALTER TABLE token ADD COLUMN IF NOT EXISTS allowed_ips cidr[]; diff --git a/backend/tests/postgres_trigger_scope.rs b/backend/tests/postgres_trigger_scope.rs index 9e7d8a665b..fa2d7dadee 100644 --- a/backend/tests/postgres_trigger_scope.rs +++ b/backend/tests/postgres_trigger_scope.rs @@ -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, } } diff --git a/backend/tests/reserved_control_args.rs b/backend/tests/reserved_control_args.rs index ed0fa6d002..571802c804 100644 --- a/backend/tests/reserved_control_args.rs +++ b/backend/tests/reserved_control_args.rs @@ -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, } } diff --git a/backend/tests/token_allowed_ips.rs b/backend/tests/token_allowed_ips.rs new file mode 100644 index 0000000000..0a95348d99 --- /dev/null +++ b/backend/tests/token_allowed_ips.rs @@ -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) -> 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 = + 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(()) +} diff --git a/backend/tests/trigger_listener_queries.rs b/backend/tests/trigger_listener_queries.rs index c2392202a8..3f0c4eb9fd 100644 --- a/backend/tests/trigger_listener_queries.rs +++ b/backend/tests/trigger_listener_queries.rs @@ -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, } } diff --git a/backend/tests/wm_token_confinement.rs b/backend/tests/wm_token_confinement.rs index 6b995115c2..256071cbab 100644 --- a/backend/tests/wm_token_confinement.rs +++ b/backend/tests/wm_token_confinement.rs @@ -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, } } diff --git a/backend/windmill-api-assets/tests/dbt_pinned_graph.rs b/backend/windmill-api-assets/tests/dbt_pinned_graph.rs index eaa531dc4b..6e55ea2794 100644 --- a/backend/windmill-api-assets/tests/dbt_pinned_graph.rs +++ b/backend/windmill-api-assets/tests/dbt_pinned_graph.rs @@ -38,6 +38,7 @@ fn outsider() -> ApiAuthed { credential_expiry: None, mcp_client: None, capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), + allowed_ips: None, } } diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index 32b31f771a..79bf0e1948 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -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, 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 = 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>); + +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 { + 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) { + 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, token: &str) -> Option { - 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, + token: &str, + client_ip: Option, + ) -> Option { + Some( + self.get_opt_job_authed(w_id, token, client_ip) + .await? + .authed, + ) } pub async fn get_opt_job_authed( &self, w_id: Option, token: &str, + client_ip: Option, + ) -> Option { + 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, + token: &str, + client_ip: impl FnOnce() -> Option, + on_refused: impl FnOnce(&str, Option), ) -> Option { 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::().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![ diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index 070ff51dda..3957daeec4 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -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, + /// 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>, } impl ApiAuthed { @@ -191,6 +200,7 @@ impl From 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, + /// 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>, } 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?; diff --git a/backend/windmill-api-auth/src/token_ip_allowlist_oss.rs b/backend/windmill-api-auth/src/token_ip_allowlist_oss.rs new file mode 100644 index 0000000000..3fa370a4d9 --- /dev/null +++ b/backend/windmill-api-auth/src/token_ip_allowlist_oss.rs @@ -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>) -> Option> { + None + } + + pub fn client_ip_allowed( + _allowed: Option<&[IpNet]>, + _client_ip: Option, + ) -> bool { + true + } + + pub fn token_ip_allowlist( + _caller: Option<&[IpNet]>, + requested: Option<&[String]>, + ) -> error::Result>> { + match requested { + Some(_) => Err(super::token_ip_allowlists_unavailable()), + None => Ok(None), + } + } +} diff --git a/backend/windmill-api-integration-tests/tests/native_triggers.rs b/backend/windmill-api-integration-tests/tests/native_triggers.rs index 327c9ab9b9..4dc0672eaa 100644 --- a/backend/windmill-api-integration-tests/tests/native_triggers.rs +++ b/backend/windmill-api-integration-tests/tests/native_triggers.rs @@ -69,6 +69,7 @@ fn test_authed() -> ApiAuthed { credential_expiry: None, mcp_client: None, capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), + allowed_ips: None, } } diff --git a/backend/windmill-api-integration-tests/tests/token_hash.rs b/backend/windmill-api-integration-tests/tests/token_hash.rs index 285f15a9c6..270651001f 100644 --- a/backend/windmill-api-integration-tests/tests/token_hash.rs +++ b/backend/windmill-api-integration-tests/tests/token_hash.rs @@ -342,6 +342,10 @@ async fn test_rotate_webhook_token(db: Pool) -> 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) -> 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> = + 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 diff --git a/backend/windmill-api-scripts/src/scripts.rs b/backend/windmill-api-scripts/src/scripts.rs index e063874533..72a1e2837d 100644 --- a/backend/windmill-api-scripts/src/scripts.rs +++ b/backend/windmill-api-scripts/src/scripts.rs @@ -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, Extension(db): Extension, Extension(cache): Extension>, @@ -3673,7 +3674,7 @@ async fn get_tokened_raw_script_by_path( Query(query): Query, ) -> Result { 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( diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index 1c80a8ec28..49f5594256 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -333,6 +333,8 @@ pub struct TruncatedToken { pub scopes: Option>, pub workspace_id: Option, pub read_only: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub allowed_ips: Option>, } // 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)> { 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, authed: ApiAuthed, Tokened { token }: Tokened, + ClientIp(client_ip): ClientIp, Extension(cache): Extension>, ) -> JsonResult> { 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}")) diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index cbb586c2fc..5c45f5ed96 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -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, }) } diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 4c7e907136..95e0348d18 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -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 diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 3e5067c202..a835203697 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -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>, Extension(user_db): Extension, Extension(db): Extension, @@ -2007,7 +2008,7 @@ async fn get_app_embed_token( ) -> JsonResult { 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, diff --git a/backend/windmill-api/src/concurrency_groups.rs b/backend/windmill-api/src/concurrency_groups.rs index 3e0a136b30..b8017f48bf 100644 --- a/backend/windmill-api/src/concurrency_groups.rs +++ b/backend/windmill-api/src/concurrency_groups.rs @@ -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, 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>, Extension(db): Extension, Extension(user_db): Extension, OptViewToken(view_token): OptViewToken, Path(job_id): Path, ) -> JsonResult> { - 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>, Extension(db): Extension, Extension(user_db): Extension, OptViewToken(view_token): OptViewToken, Path(job_id): Path, ) -> JsonResult> { - 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", diff --git a/backend/windmill-api/src/drafts.rs b/backend/windmill-api/src/drafts.rs index 4b0785080d..2a9bc2a28b 100644 --- a/backend/windmill-api/src/drafts.rs +++ b/backend/windmill-api/src/drafts.rs @@ -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>, Extension(db): Extension, Extension(user_db): Extension, @@ -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}")))?; diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index 50f7463bda..e5f5485988 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -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, } } diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 26535b211f..fc22ade6e0 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -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 { let worker = windmill_common::min_version::MIN_KEEP_ALIVE_VERSION; let agent = windmill_common::min_version::AGENT_MIN_KEEP_ALIVE_VERSION; diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index 25507b4119..9716627e3b 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -500,12 +500,16 @@ impl McpBackend for WindmillBackend { async fn resolve_workspace_auth( &self, - token: &str, + token: &McpToken, workspace_id: &str, ) -> BackendResult { 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 }); } } } diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index f07f563b32..89ed6942e2 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -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 diff --git a/backend/windmill-api/src/mcp/utils.rs b/backend/windmill-api/src/mcp/utils.rs index 1330d7cbca..09c91436ee 100644 --- a/backend/windmill-api/src/mcp/utils.rs +++ b/backend/windmill-api/src/mcp/utils.rs @@ -1467,6 +1467,7 @@ mod tests { credential_expiry: None, mcp_client: None, capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), + allowed_ips: None, } } diff --git a/backend/windmill-api/src/triggers/http/handler.rs b/backend/windmill-api/src/triggers/http/handler.rs index 402cc28696..26c2ed5525 100644 --- a/backend/windmill-api/src/triggers/http/handler.rs +++ b/backend/windmill-api/src/triggers/http/handler.rs @@ -368,6 +368,7 @@ async fn get_http_route_trigger( route_path: &str, auth_cache: &Arc, token: Option<&String>, + client_ip: Option, 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>, Extension(cors_policy): Extension, OptTokened { token }: OptTokened, + windmill_common::client_ip::ClientIp(client_ip): windmill_common::client_ip::ClientIp, Path(route_path): Path, 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, diff --git a/backend/windmill-common/src/client_ip.rs b/backend/windmill-common/src/client_ip.rs index 95ee5ed59d..5c7d5ad70d 100644 --- a/backend/windmill-common/src/client_ip.rs +++ b/backend/windmill-common/src/client_ip.rs @@ -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 FromRequestParts for ClientIp { } pub fn client_ip_of_parts(parts: &Parts) -> Option { - 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 { + let peer = extensions .get::>() .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 diff --git a/backend/windmill-mcp/src/common/types.rs b/backend/windmill-mcp/src/common/types.rs index 7d91e94255..2b902a4d18 100644 --- a/backend/windmill-mcp/src/common/types.rs +++ b/backend/windmill-mcp/src/common/types.rs @@ -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, +} /// Summary of a workspace the caller can access, returned by the /// `list_workspaces` tool in multi-workspace mode. diff --git a/backend/windmill-mcp/src/server/backend.rs b/backend/windmill-mcp/src/server/backend.rs index 1dd746a2b7..5938b4c9c5 100644 --- a/backend/windmill-mcp/src/server/backend.rs +++ b/backend/windmill-mcp/src/server/backend.rs @@ -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; diff --git a/backend/windmill-mcp/src/server/runner.rs b/backend/windmill-mcp/src/server/runner.rs index 6af8eebc1b..d320916964 100644 --- a/backend/windmill-mcp/src/server/runner.rs +++ b/backend/windmill-mcp/src/server/runner.rs @@ -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 Runner { 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 Runner { 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>, diff --git a/backend/windmill-native-triggers/src/lib.rs b/backend/windmill-native-triggers/src/lib.rs index eb13bf9a28..02b4ae8e88 100644 --- a/backend/windmill-native-triggers/src/lib.rs +++ b/backend/windmill-native-triggers/src/lib.rs @@ -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?; diff --git a/docs/auth-surface.md b/docs/auth-surface.md index 8903cac79c..359ec92fb9 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -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. diff --git a/frontend/src/lib/components/settings/CreateToken.svelte b/frontend/src/lib/components/settings/CreateToken.svelte index e96cfad47d..aa6460900d 100644 --- a/frontend/src/lib/components/settings/CreateToken.svelte +++ b/frontend/src/lib/components/settings/CreateToken.svelte @@ -1,10 +1,16 @@