Merge remote-tracking branch 'origin/main' into ruben/datatable-clone-extensions

# Conflicts:
#	backend/ee-repo-ref.txt
This commit is contained in:
Ruben Fiszel
2026-11-29 12:12:41 +01:00
128 changed files with 3585 additions and 688 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "1.888.0"
".": "1.889.1"
}
+30
View File
@@ -1,5 +1,35 @@
# Changelog
## [1.889.1](https://github.com/windmill-labs/windmill/compare/v1.889.0...v1.889.1) (2026-11-28)
### Bug Fixes
* **frontend:** keep url helpers in their own chunk ([dde36c1](https://github.com/windmill-labs/windmill/commit/dde36c16826ce534ff3d4e0c403e373394693149))
* read scope for listing mcp tools ([8ccb60c](https://github.com/windmill-labs/windmill/commit/8ccb60c711ada9abdb46e9afa24760bb899bdd89))
## [1.889.0](https://github.com/windmill-labs/windmill/compare/v1.888.0...v1.889.0) (2026-11-28)
### Features
* **mcp:** show client details on the oauth consent page ([1a43ff8](https://github.com/windmill-labs/windmill/commit/1a43ff85005fb972404323decab3bbbf61f8cb2b))
### Bug Fixes
* app rendering mode for visitors ([24b15a7](https://github.com/windmill-labs/windmill/commit/24b15a72e846a648ce52f50f9d7141a1aff8ad52))
* **cli:** dev server and sync path handling improvements ([46a64b1](https://github.com/windmill-labs/windmill/commit/46a64b1b467b9596e698456abf38369744dd8843))
* **frontend:** dev page and raw app editor message handling ([c883b82](https://github.com/windmill-labs/windmill/commit/c883b82fa73a4a6556cebe4b0ef72d2923d8046b))
* **frontend:** input handling cleanups ([90c1361](https://github.com/windmill-labs/windmill/commit/90c1361b73f8897a4dce78f1b59163df4027a3ea))
* **frontend:** use the shared markdown renderer in more views ([767d2d6](https://github.com/windmill-labs/windmill/commit/767d2d6f915db277a3e712e3a0075924a17aadbb))
* recordings and mcp tools loading tweaks ([b9e0e06](https://github.com/windmill-labs/windmill/commit/b9e0e068788681a24748f28b4af2df9a3c7e7998))
* serve s3 previews with an explicit content type ([#12715](https://github.com/windmill-labs/windmill/issues/12715)) ([4f309ec](https://github.com/windmill-labs/windmill/commit/4f309ec5fb01d13636a4bcef7fd1fe427a307823))
* tidy redirect handling after login and logout ([561c5a1](https://github.com/windmill-labs/windmill/commit/561c5a1ad30b3c34c8c7d42008f57645078e9854))
* token scope matching cleanups ([7365bfd](https://github.com/windmill-labs/windmill/commit/7365bfdf68a3cdb42c25f6a0b7053eec22f64752))
* **typescript-client:** read task parameter names past a default value ([#12718](https://github.com/windmill-labs/windmill/issues/12718)) ([a7ee99c](https://github.com/windmill-labs/windmill/commit/a7ee99ce63671efde8860e89b3ead8cf794c1c9f))
* **typescript-client:** skip regex literals when reading task parameter names ([00acb80](https://github.com/windmill-labs/windmill/commit/00acb80e0dfe803c7741f63b380bf95f33605f8f))
## [1.888.0](https://github.com/windmill-labs/windmill/compare/v1.887.0...v1.888.0) (2026-11-28)
@@ -0,0 +1,40 @@
{
"db_name": "PostgreSQL",
"query": "SELECT client_id, client_name, redirect_uris, created_at FROM mcp_oauth_server_client\n WHERE client_id = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "client_id",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "client_name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "redirect_uris",
"type_info": "TextArray"
},
{
"ordinal": 3,
"name": "created_at",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
false,
false
]
},
"hash": "99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465"
}
+80 -79
View File
@@ -15657,7 +15657,7 @@ dependencies = [
[[package]]
name = "windmill"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-nats",
@@ -15747,7 +15747,7 @@ dependencies = [
[[package]]
name = "windmill-ai"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"async-stream",
"async-trait",
@@ -15782,7 +15782,7 @@ dependencies = [
[[package]]
name = "windmill-alerting"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -15795,7 +15795,7 @@ dependencies = [
[[package]]
name = "windmill-api"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"argon2",
@@ -15937,7 +15937,7 @@ dependencies = [
[[package]]
name = "windmill-api-agent-workers"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -15961,7 +15961,7 @@ dependencies = [
[[package]]
name = "windmill-api-assets"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -15978,7 +15978,7 @@ dependencies = [
[[package]]
name = "windmill-api-auth"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"axum",
@@ -15997,6 +15997,7 @@ dependencies = [
"tokio",
"tower-cookies",
"tracing",
"url",
"uuid",
"windmill-audit",
"windmill-common",
@@ -16005,7 +16006,7 @@ dependencies = [
[[package]]
name = "windmill-api-client"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"reqwest 0.12.28",
"serde",
@@ -16015,7 +16016,7 @@ dependencies = [
[[package]]
name = "windmill-api-configs"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -16032,7 +16033,7 @@ dependencies = [
[[package]]
name = "windmill-api-debug"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"base64 0.22.1",
@@ -16054,7 +16055,7 @@ dependencies = [
[[package]]
name = "windmill-api-embeddings"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"axum",
@@ -16077,7 +16078,7 @@ dependencies = [
[[package]]
name = "windmill-api-flow-conversations"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -16093,7 +16094,7 @@ dependencies = [
[[package]]
name = "windmill-api-flows"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -16115,7 +16116,7 @@ dependencies = [
[[package]]
name = "windmill-api-groups"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -16137,7 +16138,7 @@ dependencies = [
[[package]]
name = "windmill-api-inputs"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -16151,7 +16152,7 @@ dependencies = [
[[package]]
name = "windmill-api-integration-tests"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-nats",
@@ -16187,7 +16188,7 @@ dependencies = [
[[package]]
name = "windmill-api-jobs"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"axum",
@@ -16213,7 +16214,7 @@ dependencies = [
[[package]]
name = "windmill-api-npm-proxy"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -16241,7 +16242,7 @@ dependencies = [
[[package]]
name = "windmill-api-openapi"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"axum",
@@ -16263,7 +16264,7 @@ dependencies = [
[[package]]
name = "windmill-api-schedule"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -16282,7 +16283,7 @@ dependencies = [
[[package]]
name = "windmill-api-scripts"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"axum",
@@ -16324,7 +16325,7 @@ dependencies = [
[[package]]
name = "windmill-api-settings"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"axum",
@@ -16355,7 +16356,7 @@ dependencies = [
[[package]]
name = "windmill-api-sse"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"lazy_static",
"serde",
@@ -16367,7 +16368,7 @@ dependencies = [
[[package]]
name = "windmill-api-users"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"argon2",
"axum",
@@ -16395,7 +16396,7 @@ dependencies = [
[[package]]
name = "windmill-api-workers"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -16410,7 +16411,7 @@ dependencies = [
[[package]]
name = "windmill-api-workspaces"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"axum",
"chrono",
@@ -16449,7 +16450,7 @@ dependencies = [
[[package]]
name = "windmill-audit"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"chrono",
"lazy_static",
@@ -16464,7 +16465,7 @@ dependencies = [
[[package]]
name = "windmill-autoscaling"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"axum",
@@ -16483,7 +16484,7 @@ dependencies = [
[[package]]
name = "windmill-common"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"aes-gcm",
"aho-corasick",
@@ -16604,7 +16605,7 @@ dependencies = [
[[package]]
name = "windmill-dep-map"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"chrono",
"futures",
@@ -16624,7 +16625,7 @@ dependencies = [
[[package]]
name = "windmill-git-sync"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"regex",
"serde",
@@ -16641,7 +16642,7 @@ dependencies = [
[[package]]
name = "windmill-indexer"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"astral-tokio-tar",
@@ -16668,7 +16669,7 @@ dependencies = [
[[package]]
name = "windmill-jseval"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"futures",
@@ -16685,7 +16686,7 @@ dependencies = [
[[package]]
name = "windmill-macros"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"itertools 0.14.0",
"lazy_static",
@@ -16701,7 +16702,7 @@ dependencies = [
[[package]]
name = "windmill-mcp"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -16723,7 +16724,7 @@ dependencies = [
[[package]]
name = "windmill-native-triggers"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -16755,7 +16756,7 @@ dependencies = [
[[package]]
name = "windmill-oauth"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"arc-swap",
@@ -16780,7 +16781,7 @@ dependencies = [
[[package]]
name = "windmill-object-store"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-stream",
@@ -16816,7 +16817,7 @@ dependencies = [
[[package]]
name = "windmill-operator"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"futures",
@@ -16835,7 +16836,7 @@ dependencies = [
[[package]]
name = "windmill-parser"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"convert_case 0.6.0",
"serde",
@@ -16844,7 +16845,7 @@ dependencies = [
[[package]]
name = "windmill-parser-bash"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -16856,7 +16857,7 @@ dependencies = [
[[package]]
name = "windmill-parser-csharp"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"serde_json",
@@ -16868,7 +16869,7 @@ dependencies = [
[[package]]
name = "windmill-parser-go"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"gosyn",
@@ -16880,7 +16881,7 @@ dependencies = [
[[package]]
name = "windmill-parser-graphql"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -16892,7 +16893,7 @@ dependencies = [
[[package]]
name = "windmill-parser-java"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"serde_json",
@@ -16904,7 +16905,7 @@ dependencies = [
[[package]]
name = "windmill-parser-nu"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"nu-parser",
@@ -16915,7 +16916,7 @@ dependencies = [
[[package]]
name = "windmill-parser-php"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"itertools 0.14.0",
@@ -16926,7 +16927,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"itertools 0.14.0",
@@ -16938,7 +16939,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py-asset"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"ruff_python_ast",
@@ -16949,7 +16950,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py-imports"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-recursion",
@@ -16972,7 +16973,7 @@ dependencies = [
[[package]]
name = "windmill-parser-r"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"serde_json",
@@ -16984,7 +16985,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ruby"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -16998,7 +16999,7 @@ dependencies = [
[[package]]
name = "windmill-parser-rust"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"convert_case 0.6.0",
@@ -17015,7 +17016,7 @@ dependencies = [
[[package]]
name = "windmill-parser-sql"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -17028,7 +17029,7 @@ dependencies = [
[[package]]
name = "windmill-parser-sql-asset"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"serde",
@@ -17040,7 +17041,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ts"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -17058,7 +17059,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ts-asset"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"serde-wasm-bindgen",
@@ -17074,7 +17075,7 @@ dependencies = [
[[package]]
name = "windmill-parser-wac"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"ruff_python_ast",
@@ -17091,7 +17092,7 @@ dependencies = [
[[package]]
name = "windmill-parser-yaml"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -17105,7 +17106,7 @@ dependencies = [
[[package]]
name = "windmill-queue"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-recursion",
@@ -17143,7 +17144,7 @@ dependencies = [
[[package]]
name = "windmill-runtime-nativets"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"const_format",
@@ -17181,7 +17182,7 @@ dependencies = [
[[package]]
name = "windmill-sql-datatype-parser-wasm"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"getrandom 0.3.4",
"wasm-bindgen",
@@ -17192,7 +17193,7 @@ dependencies = [
[[package]]
name = "windmill-store"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-recursion",
@@ -17227,7 +17228,7 @@ dependencies = [
[[package]]
name = "windmill-test-utils"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17251,7 +17252,7 @@ dependencies = [
[[package]]
name = "windmill-trigger"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17284,7 +17285,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-amqp"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17311,7 +17312,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-azure"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17344,7 +17345,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-email"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17364,7 +17365,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-gcp"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17398,7 +17399,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-http"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17435,7 +17436,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-kafka"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17458,7 +17459,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-mqtt"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17482,7 +17483,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-nats"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-nats",
@@ -17506,7 +17507,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-postgres"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17541,7 +17542,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-sqs"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17569,7 +17570,7 @@ dependencies = [
[[package]]
name = "windmill-trigger-websocket"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-trait",
@@ -17595,7 +17596,7 @@ dependencies = [
[[package]]
name = "windmill-types"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"bitflags 2.13.2",
@@ -17615,7 +17616,7 @@ dependencies = [
[[package]]
name = "windmill-worker"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-once-cell",
@@ -17733,7 +17734,7 @@ dependencies = [
[[package]]
name = "windmill-worker-volumes"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"bytes",
"fs4",
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "windmill"
version = "1.888.0"
version = "1.889.1"
authors.workspace = true
edition.workspace = true
@@ -88,7 +88,7 @@ members = [
exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"]
[workspace.package]
version = "1.888.0"
version = "1.889.1"
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
edition = "2021"
+1 -1
View File
@@ -1 +1 @@
88fac323b86968314ffe60900dcff26fff7cb33a
5a35e6f2a01650b4cc846eba8997837bb307bf71
+24 -24
View File
@@ -6340,7 +6340,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windmill-common"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"aes-gcm",
"aho-corasick",
@@ -6430,7 +6430,7 @@ dependencies = [
[[package]]
name = "windmill-macros"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"proc-macro2",
"quote",
@@ -6442,7 +6442,7 @@ dependencies = [
[[package]]
name = "windmill-parser"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"convert_case",
"serde",
@@ -6451,7 +6451,7 @@ dependencies = [
[[package]]
name = "windmill-parser-bash"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -6463,7 +6463,7 @@ dependencies = [
[[package]]
name = "windmill-parser-csharp"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"serde_json",
@@ -6475,7 +6475,7 @@ dependencies = [
[[package]]
name = "windmill-parser-go"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"gosyn",
@@ -6487,7 +6487,7 @@ dependencies = [
[[package]]
name = "windmill-parser-graphql"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -6499,7 +6499,7 @@ dependencies = [
[[package]]
name = "windmill-parser-java"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"serde_json",
@@ -6511,7 +6511,7 @@ dependencies = [
[[package]]
name = "windmill-parser-nu"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"nu-parser",
@@ -6522,7 +6522,7 @@ dependencies = [
[[package]]
name = "windmill-parser-php"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"itertools 0.14.0",
@@ -6533,7 +6533,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"itertools 0.14.0",
@@ -6545,7 +6545,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py-asset"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"ruff_python_ast",
@@ -6556,7 +6556,7 @@ dependencies = [
[[package]]
name = "windmill-parser-py-imports"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"async-recursion",
@@ -6579,7 +6579,7 @@ dependencies = [
[[package]]
name = "windmill-parser-r"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"serde_json",
@@ -6591,7 +6591,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ruby"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -6605,7 +6605,7 @@ dependencies = [
[[package]]
name = "windmill-parser-rust"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"convert_case",
@@ -6622,7 +6622,7 @@ dependencies = [
[[package]]
name = "windmill-parser-sql"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -6635,7 +6635,7 @@ dependencies = [
[[package]]
name = "windmill-parser-sql-asset"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"serde",
@@ -6647,7 +6647,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ts"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -6665,7 +6665,7 @@ dependencies = [
[[package]]
name = "windmill-parser-ts-asset"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"serde-wasm-bindgen",
@@ -6681,7 +6681,7 @@ dependencies = [
[[package]]
name = "windmill-parser-wac"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"ruff_python_ast",
@@ -6698,7 +6698,7 @@ dependencies = [
[[package]]
name = "windmill-parser-wasm"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"getrandom 0.2.17",
@@ -6730,7 +6730,7 @@ dependencies = [
[[package]]
name = "windmill-parser-yaml"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"lazy_static",
@@ -6744,7 +6744,7 @@ dependencies = [
[[package]]
name = "windmill-types"
version = "1.888.0"
version = "1.889.1"
dependencies = [
"anyhow",
"bitflags",
@@ -12,7 +12,7 @@ resolver = "2"
members = ["."]
[workspace.package]
version = "1.888.0"
version = "1.889.1"
edition = "2021"
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
@@ -0,0 +1,91 @@
//! An app its publisher left unsandboxed renders same-origin only for members of its
//! workspace; the embed-token response tells every other viewer to isolate it.
//!
//! Users from the `base` fixture:
//! test-user (admin, superadmin, token SECRET_TOKEN)
//! test-user-2 (member, token SECRET_TOKEN_2)
use serde_json::json;
use sqlx::{Pool, Postgres};
use windmill_test_utils::*;
const APP_PATH: &str = "u/test-user/unsandboxed_app";
const OUTSIDER_SUPERADMIN_TOKEN: &str = "OUTSIDER_SUPERADMIN";
async fn embed_sandbox(url: &str, token: Option<&str>) -> anyhow::Result<bool> {
let mut req = reqwest::Client::new().get(url);
if let Some(t) = token {
req = req.header("Authorization", format!("Bearer {t}"));
}
let resp = req.send().await?;
assert_eq!(resp.status(), 200, "{url}: {}", resp.text().await?);
let body: serde_json::Value = resp.json().await?;
Ok(body["sandbox"]
.as_bool()
.expect("embed-token response must say how to render"))
}
#[sqlx::test(fixtures("base"))]
async fn unsandboxed_app_is_isolated_for_non_members(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
let ws = format!("http://localhost:{port}/api/w/test-workspace");
// A superadmin of the instance who is not a member of the app's workspace.
sqlx::query(
"INSERT INTO password(email, password_hash, login_type, super_admin, verified, name)
VALUES ('outsider@windmill.dev', 'not-a-real-hash', 'password', true, true, 'Outsider')",
)
.execute(&db)
.await?;
sqlx::query(
"INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin)
VALUES (encode(sha256($1::bytea), 'hex'), 'OUTSIDER_S', $1, 'outsider@windmill.dev', 'session', true)",
)
.bind(OUTSIDER_SUPERADMIN_TOKEN)
.execute(&db)
.await?;
let resp = reqwest::Client::new()
.post(format!("{ws}/apps/create"))
.header("Authorization", "Bearer SECRET_TOKEN")
.json(&json!({
"path": APP_PATH,
"summary": "Unsandboxed app",
"value": {},
"policy": { "execution_mode": "anonymous", "triggerables": {}, "sandbox": false }
}))
.send()
.await?;
assert_eq!(resp.status(), 201, "{}", resp.text().await?);
let secret = reqwest::Client::new()
.get(format!("{ws}/apps/secret_of/{APP_PATH}"))
.header("Authorization", "Bearer SECRET_TOKEN")
.send()
.await?
.text()
.await?;
let by_secret = format!("{ws}/apps_u/embed_token/{secret}");
assert!(embed_sandbox(&by_secret, None).await?, "anonymous visitor");
assert!(
embed_sandbox(&by_secret, Some(OUTSIDER_SUPERADMIN_TOKEN)).await?,
"superadmin outside the workspace"
);
assert!(
!embed_sandbox(&by_secret, Some("SECRET_TOKEN_2")).await?,
"a member keeps the publisher's choice"
);
let by_path = format!("{ws}/apps/embed_token/p/{APP_PATH}");
assert!(
embed_sandbox(&by_path, Some(OUTSIDER_SUPERADMIN_TOKEN)).await?,
"superadmin outside the workspace, in-workspace viewer"
);
assert!(
!embed_sandbox(&by_path, Some("SECRET_TOKEN")).await?,
"a member keeps the publisher's choice, in-workspace viewer"
);
Ok(())
}
+136
View File
@@ -0,0 +1,136 @@
//! The worker count autoscaling decides from, driven through `apply_all_autoscaling` with a
//! dry-run integration against planted `worker_ping` rows.
#![cfg(all(feature = "enterprise", feature = "private"))]
use sqlx::{Pool, Postgres};
use windmill_autoscaling::apply_all_autoscaling;
async fn setup(db: &Pool<Postgres>) -> anyhow::Result<()> {
let updated = sqlx::query(
r#"UPDATE config SET config = config || '{"autoscaling": {"enabled": true, "min_workers": 2,
"max_workers": 12, "integration": {"type": "dryrun"}}}'::jsonb
WHERE name = 'worker__default'"#,
)
.execute(db)
.await?
.rows_affected();
assert_eq!(updated, 1, "the default worker group config is seeded");
Ok(())
}
async fn plant_workers(db: &Pool<Postgres>, n: i32, draining: bool) -> anyhow::Result<()> {
sqlx::query(
"INSERT INTO worker_ping (worker, worker_instance, worker_group, started_at, draining)
SELECT 'wk-' || $2::text || '-' || i, 'pod-' || $2::text || '-' || i, 'default',
now() - interval '1 hour', $2
FROM generate_series(1, $1) AS i",
)
.bind(n)
.bind(draining)
.execute(db)
.await?;
Ok(())
}
/// `apply_all_autoscaling` runs only for the holder of a 15s lock, so each tick backdates it.
async fn tick(db: &Pool<Postgres>) -> anyhow::Result<()> {
sqlx::query(
"INSERT INTO concurrency_locks (id, last_locked_at) VALUES ('autoscaling', now() - interval '1 hour')
ON CONFLICT (id) DO UPDATE SET last_locked_at = EXCLUDED.last_locked_at",
)
.execute(db)
.await?;
apply_all_autoscaling(db).await
}
async fn events(db: &Pool<Postgres>) -> anyhow::Result<Vec<(i32, String)>> {
Ok(sqlx::query_as(
"SELECT desired_workers, reason FROM autoscaling_event WHERE worker_group = 'default' ORDER BY id",
)
.fetch_all(db)
.await?)
}
#[sqlx::test(migrations = "./migrations")]
async fn draining_workers_are_not_counted(db: Pool<Postgres>) -> anyhow::Result<()> {
setup(&db).await?;
plant_workers(&db, 12, false).await?;
plant_workers(&db, 2, true).await?;
tick(&db).await?;
assert_eq!(events(&db).await?, vec![]);
Ok(())
}
#[sqlx::test(migrations = "./migrations")]
async fn above_max_applies_max_once_per_cooldown(db: Pool<Postgres>) -> anyhow::Result<()> {
setup(&db).await?;
plant_workers(&db, 14, false).await?;
tick(&db).await?;
tick(&db).await?;
let events = events(&db).await?;
assert_eq!(events.len(), 1, "{events:?}");
assert_eq!(events[0].0, 12);
sqlx::query("UPDATE autoscaling_event SET applied_at = applied_at - interval '10 minutes'")
.execute(&db)
.await?;
tick(&db).await?;
assert_eq!(self::events(&db).await?.len(), 2);
Ok(())
}
/// A group restarting in place marks every worker draining while its pods remain replicas.
#[sqlx::test(migrations = "./migrations")]
async fn restarting_group_is_not_scaled_below_last_applied(db: Pool<Postgres>) -> anyhow::Result<()> {
setup(&db).await?;
sqlx::query(
"INSERT INTO autoscaling_event (worker_group, event_type, desired_workers, reason)
VALUES ('default', 'scaleout', 10, 'planted')",
)
.execute(&db)
.await?;
plant_workers(&db, 1, false).await?;
plant_workers(&db, 9, true).await?;
tick(&db).await?;
assert_eq!(events(&db).await?.len(), 1);
sqlx::query("UPDATE autoscaling_event SET applied_at = applied_at - interval '10 minutes'")
.execute(&db)
.await?;
tick(&db).await?;
let events = events(&db).await?;
assert_eq!(events.last().map(|e| e.0), Some(10), "{events:?}");
Ok(())
}
/// Idle restarted workers beside ones still draining must not make one scale-in remove the
/// draining pods too.
#[sqlx::test(migrations = "./migrations")]
async fn partially_restarted_group_scales_in_one_step(db: Pool<Postgres>) -> anyhow::Result<()> {
setup(&db).await?;
sqlx::query(
"INSERT INTO autoscaling_event (worker_group, event_type, desired_workers, reason, applied_at)
VALUES ('default', 'scaleout', 10, 'planted', now() - interval '10 minutes')",
)
.execute(&db)
.await?;
plant_workers(&db, 4, false).await?;
plant_workers(&db, 6, true).await?;
sqlx::query(
"UPDATE worker_ping SET occupancy_rate_15s = 0, occupancy_rate_5m = 0, occupancy_rate_30m = 0",
)
.execute(&db)
.await?;
tick(&db).await?;
let events = events(&db).await?;
assert_eq!(events.last().map(|e| e.0), Some(8), "{events:?}");
Ok(())
}
+46 -6
View File
@@ -14,12 +14,15 @@
//! exempting the parameter would let `?token=junk` reinstate the vector.
//!
//! This test pins down:
//! - both endpoints refuse a cross-site cookie GET to a Hub script (the core fix), whether
//! `Sec-Fetch-Site` says so or, with no such header (plain http), a cross-host `Referer`,
//! - both endpoints refuse a cookie GET to a Hub script from another site, same-site
//! included, whether `Sec-Fetch-Site` says so or, with no such header (plain http), a
//! cross-host `Referer`,
//! - a junk `token` query parameter does not buy a pass,
//! - the scope: the same request to a workspace script is not refused,
//! - a POST from another site does not authenticate on the cookie, but does on its own
//! `?token=`,
//! - a Hub-script request with its own credential (bearer, or `?token=` and no cookie), or
//! sent as a POST, gets through.
//! sent as a same-origin POST, gets through.
//!
//! No runnable exists and no Hub is contacted. A request that gets past the guard fails as
//! not-found on a workspace path, and for a Hub path on fetching it from a Hub pointed at a
@@ -69,6 +72,11 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool<Postgres>) -> anyho
"Sec-Fetch-Site: cross-site",
cookie_get(path).header("Sec-Fetch-Site", "cross-site"),
),
// A sibling subdomain gets the `SameSite=Lax` cookie on every request.
(
"Sec-Fetch-Site: same-site",
cookie_get(path).header("Sec-Fetch-Site", "same-site"),
),
// Plain http gets no `Sec-Fetch-*` at all, so `Referer` is the only signal left.
(
"cross-host Referer with no Sec-Fetch-Site",
@@ -113,8 +121,32 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool<Postgres>) -> anyho
);
}
// ---- A Hub-script request that carries its own credential, or is a POST, gets through.
// ---- A POST from another site does not authenticate on the cookie.
let hub = HUB_GETS[1];
for (name, headers) in [
("same-site", &[("Sec-Fetch-Site", "same-site")][..]),
(
"Origin on another host",
&[("Origin", "http://sibling.localhost")][..],
),
] {
let mut req = client
.post(format!("{base}/{hub}"))
.header("Cookie", "token=SECRET_TOKEN")
.json(&serde_json::json!({}));
for (k, v) in headers {
req = req.header(*k, *v);
}
let (status, body) = send(req).await?;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"POST [{name}] must not use the cookie: {body}"
);
}
// ---- A Hub-script request that carries its own credential, or is a same-origin POST,
// gets through.
let allowed = [
(
"cross-origin bearer token",
@@ -130,11 +162,19 @@ async fn test_cross_site_get_cannot_run_hub_scripts(db: Pool<Postgres>) -> anyho
.header("Sec-Fetch-Site", "cross-site"),
),
(
"POST with the cookie",
"same-origin POST with the cookie",
client
.post(format!("{base}/{hub}"))
.header("Cookie", "token=SECRET_TOKEN")
.header("Sec-Fetch-Site", "cross-site")
.header("Sec-Fetch-Site", "same-origin")
.json(&serde_json::json!({})),
),
(
"same-site POST with ?token= next to the cookie",
client
.post(format!("{base}/{hub}?token=SECRET_TOKEN"))
.header("Cookie", "token=junk")
.header("Sec-Fetch-Site", "same-site")
.json(&serde_json::json!({})),
),
];
+2 -2
View File
@@ -91,7 +91,7 @@ async fn test_mcp_header_var_ref_requires_variable_scope(db: Pool<Postgres>) ->
let server = ApiServer::start(db.clone()).await?;
let resp = reqwest::Client::new()
.get(format!(
.post(format!(
"http://localhost:{}/api/w/test-workspace/resources/mcp_tools/u/test-user/mcp",
server.addr.port()
))
@@ -127,7 +127,7 @@ async fn test_mcp_header_var_ref_requires_variable_scope(db: Pool<Postgres>) ->
.execute(&db)
.await?;
let resp = reqwest::Client::new()
.get(format!(
.post(format!(
"http://localhost:{}/api/w/test-workspace/resources/mcp_tools/u/test-user/mcp",
server.addr.port()
))
+5 -5
View File
@@ -1,6 +1,6 @@
//! Regression test for the MCP token-exfiltration vulnerability.
//!
//! `GET /api/w/{w}/resources/mcp_tools/{path}` builds an MCP client from a
//! `POST /api/w/{w}/resources/mcp_tools/{path}` builds an MCP client from a
//! resource whose `token` field is a `$var:` reference. Before the fix the token
//! was resolved with `get_secret_value_as_admin` on the bare DB pool — no RLS,
//! no audit — so any workspace member who could read an MCP *resource* could
@@ -38,9 +38,9 @@ fn client() -> reqwest::Client {
reqwest::Client::new()
}
async fn get(base: &str, path: &str, token: &str) -> (reqwest::StatusCode, String) {
async fn list_tools(base: &str, path: &str, token: &str) -> (reqwest::StatusCode, String) {
let resp = client()
.get(format!("{base}/{path}"))
.post(format!("{base}/{path}"))
.header("Authorization", format!("Bearer {token}"))
.send()
.await
@@ -100,7 +100,7 @@ async fn test_mcp_token_not_exfiltrated(db: Pool<Postgres>) -> anyhow::Result<()
// able to resolve the locked secret. They are denied (401) at the
// variable-RLS gate, before any MCP connection is attempted, and the
// secret never appears in the response.
let (status, body) = get(&base, path, "SECRET_TOKEN_3").await;
let (status, body) = list_tools(&base, path, "SECRET_TOKEN_3").await;
assert_eq!(
status,
reqwest::StatusCode::UNAUTHORIZED,
@@ -125,7 +125,7 @@ async fn test_mcp_token_not_exfiltrated(db: Pool<Postgres>) -> anyhow::Result<()
// resolves and the request only fails later at the connect/SSRF step.
// A different failure mode (not 401, reaches the connection) proves the
// legitimate read still works.
let (status, body) = get(&base, path, "SECRET_TOKEN").await;
let (status, body) = list_tools(&base, path, "SECRET_TOKEN").await;
assert_ne!(
status,
reqwest::StatusCode::UNAUTHORIZED,
+1
View File
@@ -29,6 +29,7 @@ serde_json.workspace = true
uuid.workspace = true
itertools.workspace = true
tower-cookies.workspace = true
url.workspace = true
tracing.workspace = true
chrono.workspace = true
quick_cache.workspace = true
+41 -2
View File
@@ -1159,6 +1159,36 @@ async fn pick_live_session_token<S: Send + Sync>(
picked.map(|i| candidates[i].clone()).or(fallback)
}
/// Set on a request whose session cookie [`refuse_foreign_cookie`] set aside, so that the
/// rejection names the reason rather than reading as a plain logged-out 401.
#[derive(Clone, Copy)]
struct ForeignCookieRefused;
const FOREIGN_COOKIE_REFUSED: &str = "the session cookie is not accepted on a state-changing \
request sent by a page of another site: pass a token in the `Authorization` header, or, \
for a site the instance trusts, list it in SESSION_COOKIE_TRUSTED_ORIGINS";
/// Whether to set aside the session cookie of a state-changing request sent by a page of
/// another origin (see [`crate::request_site`]). The request then authenticates as if it had no
/// cookie: on its `token` query parameter if it has one, else not at all, so routes that take
/// an optional caller (public apps, approval links, HTTP routes, login callbacks) still serve
/// it anonymously. Safe methods are left to the routes that act on a GET, which check for
/// themselves (`CrossSiteGetGuard`).
fn refuse_foreign_cookie(parts: &mut Parts) -> bool {
if parts.method.is_safe() {
return false;
}
if parts.extensions.get::<ForeignCookieRefused>().is_some() {
return true;
}
let Some(foreign) = crate::request_site::foreign_request(&parts.headers, &parts.uri) else {
return false;
};
foreign.log("ignoring the session cookie");
parts.extensions.insert(ForeignCookieRefused);
true
}
pub(crate) async fn extract_token<S: Send + Sync>(parts: &mut Parts, state: &S) -> Option<String> {
let auth_header = parts
.headers
@@ -1170,7 +1200,7 @@ pub(crate) async fn extract_token<S: Send + Sync>(parts: &mut Parts, state: &S)
Some(x) => Some(x.to_owned()),
None => {
let candidates = session_cookie_values(parts);
if candidates.len() > 1 {
let cookie = if candidates.len() > 1 {
pick_live_session_token(parts, state, candidates).await
} else {
Extension::<Cookies>::from_request_parts(parts, state)
@@ -1181,7 +1211,8 @@ pub(crate) async fn extract_token<S: Send + Sync>(parts: &mut Parts, state: &S)
.get(COOKIE_NAME)
.map(|c| c.value_trimmed().to_owned())
})
}
};
cookie.filter(|_| !refuse_foreign_cookie(parts))
}
};
@@ -1263,6 +1294,8 @@ where
let tokened = Self { token: "no_auth".to_string() };
parts.extensions.insert(tokened.clone());
Ok(tokened)
} else if parts.extensions.get::<ForeignCookieRefused>().is_some() {
Err((StatusCode::FORBIDDEN, FOREIGN_COOKIE_REFUSED.to_owned()))
} else {
BRUTE_FORCE_COUNTER.increment().await;
Err((StatusCode::UNAUTHORIZED, "Unauthorized".to_owned()))
@@ -1526,6 +1559,12 @@ pub async fn resolve_opt_job_authed(
}
}
}
if parts.extensions.get::<ForeignCookieRefused>().is_some() {
return Err((
Error::PermissionDenied(FOREIGN_COOKIE_REFUSED.to_string()),
parts,
));
}
BRUTE_FORCE_COUNTER.increment().await;
Err((Error::NotAuthorized("Unauthorized".to_string()), parts))
}
+32 -4
View File
@@ -11,6 +11,7 @@ pub mod composed;
#[cfg(feature = "private")]
pub mod ee;
pub mod ee_oss;
pub mod request_site;
pub mod scopes;
#[cfg(all(feature = "private", feature = "enterprise"))]
mod token_ip_allowlist_ee;
@@ -465,7 +466,7 @@ where
{
if let Some(scopes) = authed.scopes.as_ref() {
let mut is_scoped_token = false;
let required_scope = ScopeDefinition::from_scope_string(&required())?;
let required_scope = ScopeDefinition::from_required_scope_string(&required())?;
for scope in scopes {
if !scope.starts_with("if_jobs:filter_tags:") {
if !is_scoped_token {
@@ -473,7 +474,7 @@ where
}
match ScopeDefinition::from_scope_string(scope) {
Ok(scope) if scope.includes(&required_scope) => return Ok(()),
Ok(scope) if scope.grants(&required_scope) => return Ok(()),
_ => {}
}
}
@@ -807,11 +808,11 @@ pub fn build_scope_path_predicate(
return true;
}
let required =
match ScopeDefinition::from_scope_string(&format!("{}:{}:{}", domain, action, path)) {
match ScopeDefinition::from_required_scope_string(&format!("{domain}:{action}:{path}")) {
Ok(r) => r,
Err(_) => return false,
};
parsed.iter().any(|s| s.includes(&required))
parsed.iter().any(|s| s.grants(&required))
}
}
@@ -1944,6 +1945,33 @@ mod tests {
assert!(require_owner_of_path(&alice, "u/alice/script").is_ok());
}
#[test]
fn check_scopes_reads_the_required_path_literally() {
let authed = authed_with_scopes(Some(vec![
"jobs:run:scripts:u/alice/ping",
"resources:read:f/team/*",
]));
assert!(check_scopes(&authed, || "jobs:run:scripts:u/alice/ping".into()).is_ok());
assert!(check_scopes(&authed, || "resources:read:f/team/db".into()).is_ok());
for required in [
"jobs:run:scripts:hub/1/x,u/alice/ping",
"jobs:run:scripts:hub/1/x,*",
"jobs:run:scripts:*",
"jobs:run:scripts:u/*",
"resources:read:CUSTOM_INSTANCE_DB/x,f/team/db",
"resources:read:*",
"resources:read:f/*",
] {
assert!(
check_scopes(&authed, || required.to_string()).is_err(),
"{required}"
);
}
let allowed = build_scope_path_predicate(&authed, "resources", "read");
assert!(!allowed("x,f/team/db"));
assert!(!allowed("*"));
}
#[test]
fn predicate_no_scopes_allows_all() {
let authed = authed_with_scopes(None);
@@ -0,0 +1,331 @@
/*
* Author: Ruben Fiszel
* 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.
*/
//! Whether a request was sent by a page of this instance's own origin.
//!
//! The session cookie is `SameSite=Lax`, which a browser attaches to every request from a
//! *same-site* page: any sibling host under the same registrable domain (every
//! `*.windmill.dev` host for a `<name>.windmill.dev` instance, every `*.corp.com` host for
//! `windmill.corp.com`), forms and top-level GETs alike. The cookie is therefore only treated
//! as the caller's intent on requests from the instance's own origin, a bookmark or a typed
//! URL, or a non-browser client.
use http::{header, HeaderMap, Uri};
use url::Url;
/// Hosts, besides the instance's own, whose pages may send requests that authenticate with
/// the session cookie. `*` accepts every site.
pub const TRUSTED_ORIGINS_ENV: &str = "SESSION_COOKIE_TRUSTED_ORIGINS";
lazy_static::lazy_static! {
static ref TRUSTED_ORIGINS: TrustedOrigins = TrustedOrigins::parse(
&std::env::var(TRUSTED_ORIGINS_ENV).unwrap_or_default()
);
}
#[derive(Debug, Default)]
pub struct TrustedOrigins {
any: bool,
hosts: Vec<String>,
}
impl TrustedOrigins {
/// A comma-separated list of hosts or origins (`dash.corp.com`, `https://dash.corp.com`).
pub fn parse(value: &str) -> Self {
let mut trusted = TrustedOrigins::default();
for entry in value.split(',').map(str::trim).filter(|e| !e.is_empty()) {
if entry == "*" {
trusted.any = true;
} else if let Some(host) = Url::parse(entry)
.ok()
.and_then(|u| u.host_str().map(str::to_owned))
.or_else(|| host_of(entry))
{
trusted.hosts.push(host);
} else {
tracing::warn!("{TRUSTED_ORIGINS_ENV}: ignoring {entry:?}, not a host or origin");
}
}
trusted
}
fn allows(&self, host: &str) -> bool {
self.hosts.iter().any(|h| h.eq_ignore_ascii_case(host))
}
}
/// Why a request is taken to come from a page of another origin.
#[derive(Debug)]
pub enum Foreign {
/// `Sec-Fetch-Site` says so (`same-site`, `cross-site`, or a value this code does not know).
Declared(String),
/// No `Sec-Fetch-Site`; `Origin` names another host, or an opaque origin (`null`).
Origin { origin: String, instance_hosts: Vec<String> },
/// No `Sec-Fetch-Site` and no `Origin`; `Referer` names another host.
Referer { referer: String, instance_hosts: Vec<String> },
}
impl Foreign {
/// Logged when a request is refused. The `Origin`/`Referer` legs compare against the hosts
/// the backend can see, so a proxy that rewrites `Host` without setting
/// `X-Forwarded-Host`, with `BASE_URL` naming another host, refuses requests that were
/// same-origin: say so, so it reads as a misconfiguration.
pub fn log(&self, what: &str) {
match self {
Foreign::Declared(site) => {
tracing::info!(sec_fetch_site = %site, "{what}: the request comes from another site")
}
Foreign::Origin { origin: page, instance_hosts }
| Foreign::Referer { referer: page, instance_hosts } => tracing::warn!(
page = %page,
?instance_hosts,
"{what}: the page that sent the request is on another host; if it was this \
instance, set `X-Forwarded-Host` on the proxy or configure `BASE_URL`"
),
}
}
}
/// [`foreign_signal`] against the configured `BASE_URL` and trusted origins.
pub fn foreign_request(headers: &HeaderMap, uri: &Uri) -> Option<Foreign> {
foreign_signal(
headers,
uri,
windmill_common::BASE_URL.load().as_str(),
&TRUSTED_ORIGINS,
)
}
/// `Sec-Fetch-Site` decides when present: only `same-origin` and `none` (a bookmark, a typed
/// URL) are this instance's own. Fetch Metadata rides only on potentially trustworthy URLs, so
/// a plain-http instance (and Safari before 16.4) never gets it; then `Origin`, which a
/// browser sends on every non-GET request, must name an instance host, and failing that
/// `Referer`, the only thing a top-level GET navigation carries. A request with none of them
/// is not from a browser page and is not refused.
///
/// The `Referer` leg is weak: `strict-origin-when-cross-origin` drops it on an https-to-http
/// downgrade, so an https page pointing at a plain-http instance sends neither header there.
pub fn foreign_signal(
headers: &HeaderMap,
uri: &Uri,
base_url: &str,
trusted: &TrustedOrigins,
) -> Option<Foreign> {
if trusted.any {
return None;
}
let page_host = || {
header_url_host(headers, header::ORIGIN)
.or_else(|| header_url_host(headers, header::REFERER))
};
if let Some(site) = headers.get("sec-fetch-site") {
let site = String::from_utf8_lossy(site.as_bytes()).to_ascii_lowercase();
if site == "same-origin" || site == "none" {
return None;
}
if !trusted.hosts.is_empty() && page_host().is_some_and(|h| trusted.allows(&h)) {
return None;
}
return Some(Foreign::Declared(site));
}
let is_ours = |host: &str| {
trusted.allows(host)
|| instance_hosts(headers, uri, base_url).any(|h| h.eq_ignore_ascii_case(host))
};
if let Some(origin) = headers.get(header::ORIGIN) {
if header_url_host(headers, header::ORIGIN).is_some_and(|h| is_ours(&h)) {
return None;
}
return Some(Foreign::Origin {
origin: String::from_utf8_lossy(origin.as_bytes()).into_owned(),
instance_hosts: instance_hosts(headers, uri, base_url).collect(),
});
}
let referer = header_url_host(headers, header::REFERER)?;
(!is_ours(&referer)).then(|| Foreign::Referer {
referer,
instance_hosts: instance_hosts(headers, uri, base_url).collect(),
})
}
/// Every host a same-origin request can name. `Host` alone is not enough: a reverse proxy that
/// forwards without preserving it (nginx `proxy_pass` with no `proxy_set_header Host $host`)
/// hands the backend the upstream's name. A browser page cannot set any of these on a request
/// that carries the cookie (a custom header needs a CORS preflight no route grants with
/// credentials), and `BASE_URL` is instance config. Ports are not compared: the dev frontend
/// and the API differ only by port.
fn instance_hosts<'a>(
headers: &'a HeaderMap,
uri: &'a Uri,
base_url: &'a str,
) -> impl Iterator<Item = String> + 'a {
[
uri.host()
.map(str::to_owned)
.or_else(|| header_host(headers, header::HOST)),
header_host(headers, "x-forwarded-host"),
Url::parse(base_url)
.ok()
.and_then(|url| url.host_str().map(str::to_owned)),
]
.into_iter()
.flatten()
}
fn header_url_host(headers: &HeaderMap, name: header::HeaderName) -> Option<String> {
let value = headers.get(name)?.to_str().ok()?;
Url::parse(value).ok()?.host_str().map(str::to_owned)
}
fn header_host(headers: &HeaderMap, name: impl header::AsHeaderName) -> Option<String> {
host_of(headers.get(name)?.to_str().ok()?)
}
/// The host in a `Host`-shaped header value: `host[:port]`, where `host` may be a bracketed
/// IPv6 literal, and where a chain of proxies appends to `X-Forwarded-Host` so only the first
/// entry is the one the browser addressed.
pub fn host_of(value: &str) -> Option<String> {
let host = value.split(',').next()?.trim();
Url::parse(&format!("http://{host}"))
.ok()?
.host_str()
.map(str::to_owned)
}
#[cfg(test)]
mod tests {
use super::*;
const BASE: &str = "https://windmill.example";
fn signal_with(headers: &[(&str, &str)], trusted: &TrustedOrigins) -> Option<Foreign> {
let mut map = HeaderMap::new();
for (name, value) in headers {
map.append(
header::HeaderName::from_bytes(name.as_bytes()).unwrap(),
value.parse().unwrap(),
);
}
foreign_signal(
&map,
&Uri::from_static("/api/w/ws/jobs/run/p/f"),
BASE,
trusted,
)
}
fn signal(headers: &[(&str, &str)]) -> Option<Foreign> {
signal_with(headers, &TrustedOrigins::default())
}
#[test]
fn sec_fetch_site_decides_when_present() {
for site in ["same-origin", "none", "Same-Origin"] {
assert!(signal(&[("sec-fetch-site", site)]).is_none(), "{site}");
}
for site in ["same-site", "cross-site", "unknown"] {
assert!(
matches!(
signal(&[("sec-fetch-site", site)]),
Some(Foreign::Declared(_))
),
"{site}"
);
}
// An `Origin` naming the instance does not outvote the browser's own verdict.
assert!(signal(&[
("sec-fetch-site", "same-site"),
("host", "windmill.example"),
("origin", "https://windmill.example"),
])
.is_some());
// Nor does a foreign `Referer` outvote `same-origin`.
assert!(signal(&[
("sec-fetch-site", "same-origin"),
("host", "windmill.example"),
("referer", "https://other.example/page"),
])
.is_none());
}
#[test]
fn origin_then_referer_stand_in_when_sec_fetch_site_is_absent() {
let host = ("host", "windmill-server.internal:8000");
assert!(signal(&[host, ("origin", "http://windmill.example")]).is_none());
assert!(signal(&[
("host", "windmill.example:8000"),
("origin", "http://windmill.example:3000")
])
.is_none());
assert!(signal(&[
host,
("x-forwarded-host", "alias.example, proxy.internal"),
("origin", "http://alias.example")
])
.is_none());
assert!(matches!(
signal(&[host, ("origin", "http://hub.example")]),
Some(Foreign::Origin { .. })
));
assert!(matches!(
signal(&[host, ("origin", "null")]),
Some(Foreign::Origin { .. })
));
// `Origin` outranks `Referer`.
assert!(signal(&[
host,
("origin", "http://hub.example"),
("referer", "http://windmill.example/")
])
.is_some());
assert!(signal(&[host, ("referer", "http://windmill.example/apps")]).is_none());
assert!(matches!(
signal(&[host, ("referer", "http://hub.example/x")]),
Some(Foreign::Referer { .. })
));
// No browser page named: a script, the CLI, a server-side webhook caller.
assert!(signal(&[host]).is_none());
}
#[test]
fn trusted_origins_admit_named_sites() {
let trusted = TrustedOrigins::parse(" https://dash.example , tools.example:8443 ,");
let from =
|site, origin| signal_with(&[("sec-fetch-site", site), ("origin", origin)], &trusted);
assert!(from("same-site", "https://dash.example").is_none());
assert!(from("same-site", "https://tools.example").is_none());
assert!(from("same-site", "https://hub.example").is_some());
// A top-level navigation has no `Origin`; the `Referer` names the page.
assert!(signal_with(
&[
("sec-fetch-site", "same-site"),
("referer", "https://dash.example/p")
],
&trusted
)
.is_none());
assert!(signal_with(&[("origin", "https://dash.example")], &trusted).is_none());
let any = TrustedOrigins::parse("*");
assert!(signal_with(&[("sec-fetch-site", "cross-site")], &any).is_none());
}
#[test]
fn host_of_strips_port_brackets_and_proxy_chain() {
assert_eq!(
host_of("windmill.example:8000"),
Some("windmill.example".into())
);
assert_eq!(host_of("[::1]:8000"), Some("[::1]".into()));
assert_eq!(
host_of("windmill.example, proxy.internal"),
Some("windmill.example".into())
);
assert_eq!(host_of(""), None);
assert_eq!(host_of("not a host"), None);
}
}
+5
View File
@@ -251,6 +251,11 @@ fn map_http_method_to_action(method: &str, route_path: &str) -> ScopeAction {
return ScopeAction::Run;
}
// Lists a resource's tools; a POST only so that a navigation cannot reach it.
if method.eq_ignore_ascii_case("POST") && route_path.contains("/resources/mcp_tools/") {
return ScopeAction::Read;
}
match method.to_uppercase().as_str() {
"GET" | "HEAD" | "OPTIONS" => ScopeAction::Read,
"POST" | "PUT" | "PATCH" | "DELETE" => ScopeAction::Write,
@@ -946,25 +946,35 @@ async fn test_mcp_tools(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let port = server.addr.port();
let list_tools = |path: &'static str| async move {
authed(client().post(resource_url(port, "mcp_tools", path)))
.send()
.await
.unwrap()
};
// unauthenticated -> 401
let resp = client()
.get(resource_url(port, "mcp_tools", "u/test-user/mcp_valid"))
.post(resource_url(port, "mcp_tools", "u/test-user/mcp_valid"))
.send()
.await
.unwrap();
assert_eq!(resp.status(), 401);
// A link or redirect to the route must not connect to the resource's server.
let resp = authed_get(port, "mcp_tools", "u/test-user/mcp_valid").await;
assert_eq!(resp.status(), 405);
// not found -> 404
let resp = authed_get(port, "mcp_tools", "u/test-user/nonexistent").await;
let resp = list_tools("u/test-user/nonexistent").await;
assert_eq!(resp.status(), 404);
// null value -> 400
let resp = authed_get(port, "mcp_tools", "u/test-user/mcp_null").await;
let resp = list_tools("u/test-user/mcp_null").await;
assert_eq!(resp.status(), 400);
// invalid format -> 400 with parse error message
let resp = authed_get(port, "mcp_tools", "u/test-user/mcp_invalid_format").await;
let resp = list_tools("u/test-user/mcp_invalid_format").await;
assert_eq!(resp.status(), 400);
let body = resp.text().await?;
assert!(
@@ -973,7 +983,7 @@ async fn test_mcp_tools(db: Pool<Postgres>) -> anyhow::Result<()> {
);
// valid MCP resource but unreachable server -> 500
let resp = authed_get(port, "mcp_tools", "u/test-user/mcp_valid").await;
let resp = list_tools("u/test-user/mcp_valid").await;
assert_eq!(resp.status(), 500);
let body = resp.text().await?;
assert!(
+44 -10
View File
@@ -770,14 +770,20 @@ async fn logout(
}
async fn is_valid_logout_redirect(rd: &str) -> bool {
// Allow relative paths (same-origin redirects)
if rd.starts_with('/') && !rd.starts_with("//") {
return true;
if rd.starts_with('/') {
return same_origin_rd(Some(rd.to_string())).is_some();
}
if rd.chars().any(|c| c.is_ascii_control()) {
return false;
}
let parsed = match url::Url::parse(rd) {
Ok(u) => u,
Err(_) => return false,
};
// Before the host check: `javascript://windmill.dev/...` has host `windmill.dev`.
if !matches!(parsed.scheme(), "http" | "https") {
return false;
}
let host: &str = match parsed.host_str() {
Some(h) => h,
None => return false,
@@ -2968,7 +2974,9 @@ async fn verify_password_login<'c>(
match row {
Some((email, hash, super_admin, totp_enabled))
if argon2.verify_password(password.as_bytes(), hash.as_str()).is_ok() =>
if argon2
.verify_password(password.as_bytes(), hash.as_str())
.is_ok() =>
{
Ok((tx, PasswordAccount { email, super_admin, totp_enabled }))
}
@@ -3019,9 +3027,15 @@ async fn start_password_session(
account: &PasswordAccount,
cookies: Cookies,
) -> Result<String> {
let token =
create_session_token(&account.email, account.super_admin, None, false, &mut tx, cookies)
.await?;
let token = create_session_token(
&account.email,
account.super_admin,
None,
false,
&mut tx,
cookies,
)
.await?;
let audit_author = AuditAuthor {
token_prefix: Some(safe_token_prefix(&token)),
..login_audit_author(&account.email)
@@ -3056,7 +3070,8 @@ async fn login(
}
let email = email.to_lowercase();
let (mut tx, account) = verify_password_login(&db, client_ip, &argon2, &email, &password).await?;
let (mut tx, account) =
verify_password_login(&db, client_ip, &argon2, &email, &password).await?;
// Asked only once the password matched, so whether an account has a second factor is not
// disclosed to someone who does not know its password.
@@ -3068,7 +3083,9 @@ async fn login(
return Err(reject_totp_code(tx, &account.email).await);
}
} else if crate::totp::required() {
return Err(Error::BadRequest(crate::totp::TOTP_SETUP_REQUIRED.to_string()));
return Err(Error::BadRequest(
crate::totp::TOTP_SETUP_REQUIRED.to_string(),
));
}
start_password_session(tx, &account, cookies).await
}
@@ -3236,7 +3253,9 @@ async fn refresh_token(
// A session from before the instance required a second factor is not renewed, so it ends
// within one session lifetime and the next login goes through the setup.
if crate::totp::required() && account.as_ref().is_some_and(|a| a.lacks_totp) {
return Err(Error::BadRequest(crate::totp::TOTP_SETUP_REQUIRED.to_string()));
return Err(Error::BadRequest(
crate::totp::TOTP_SETUP_REQUIRED.to_string(),
));
}
let super_admin = account.is_some_and(|a| a.super_admin);
@@ -3761,6 +3780,21 @@ mod same_origin_rd_tests {
assert!(!accepts("/x\r\nSet-Cookie: a=b"));
assert!(!accepts("user/workspaces"));
}
#[tokio::test]
async fn logout_redirect_takes_same_origin_paths_and_web_urls_only() {
use super::is_valid_logout_redirect as ok;
assert!(ok("/user/login").await);
assert!(ok("https://app.windmill.dev/user/login").await);
assert!(!ok("/\\evil.example/").await);
assert!(!ok("/\t/evil.example/").await);
assert!(!ok("//evil.example/").await);
assert!(!ok("https://evil.example/").await);
assert!(!ok("javascript://windmill.dev/%0aalert(1)").await);
assert!(!ok("JAVASCRIPT://app.windmill.dev/%0aalert(1)").await);
assert!(!ok("data://windmill.dev/x").await);
assert!(!ok("https://app.windmill.dev/\r\nSet-Cookie: a=b").await);
}
}
/// Both provisioning writes reference `password(email)`; a typo'd address from the
+47 -5
View File
@@ -1,7 +1,7 @@
openapi: "3.0.3"
info:
version: 1.888.0
version: 1.889.1
title: Windmill API
contact:
@@ -10267,7 +10267,7 @@ paths:
- truncated
/w/{workspace}/resources/mcp_tools/{path}:
get:
post:
summary: get MCP tools from resource
operationId: getMcpTools
tags:
@@ -29740,6 +29740,47 @@ paths:
items:
$ref: "#/components/schemas/EndpointTool"
/mcp/gateway/oauth/server/client/{client_id}:
get:
summary: get an MCP client registered with Windmill's OAuth server
description: |
The name and redirect URIs a client registered itself with, for the consent page to
show from the server rather than from the authorization URL.
operationId: getMcpOAuthServerClient
tags:
- mcp_oauth
parameters:
- name: client_id
in: path
required: true
schema:
type: string
responses:
"200":
description: the registered client
content:
application/json:
schema:
type: object
required:
- client_id
- client_name
- redirect_uris
- created_at
properties:
client_id:
type: string
client_name:
type: string
description: The name the client chose when it registered, unverified.
redirect_uris:
type: array
items:
type: string
created_at:
type: string
format: date-time
/mcp/oauth/discover:
post:
summary: discover MCP server OAuth metadata
@@ -40118,8 +40159,9 @@ components:
description: >
Publisher opt-in to app sandbox isolation (alpha). When true the app
is isolated from each viewer's Windmill session. When false/absent
the app runs same-origin with the viewer's full session (the
default, pre-isolation behavior).
the app runs same-origin with the session of viewers who are members
of the app's workspace; anonymous viewers and everyone else always
get the isolated render.
frontend_sdk_scopes:
type: array
items:
@@ -40520,7 +40562,7 @@ components:
a different credential from the low-code embed token.
sandbox:
type: boolean
description: Publisher opted this app into sandbox isolation. When false the viewer runs the app same-origin with its full session.
description: Whether the viewer must render the app isolated, because the publisher opted in or because the viewer is not a member of the app's workspace. When false the viewer runs the app same-origin with its full session.
app_path:
type: string
nullable: true
+31 -5
View File
@@ -1703,6 +1703,7 @@ pub async fn build_embed_token_response(
sdk_consent: bool,
job_id: Option<uuid::Uuid>,
) -> Result<EmbedTokenResponse> {
let sandbox = policy.sandbox || !viewer_is_workspace_member(db, w_id, opt_authed).await?;
// Only advertise scopes where a token could actually be minted, so the viewer
// is never shown a permission prompt that can grant nothing: an anonymous
// visitor has no identity to mint against.
@@ -1742,7 +1743,7 @@ pub async fn build_embed_token_response(
}
_ => (None, None),
}
} else if policy.sandbox {
} else if sandbox {
let resp = mint_app_embed_token(db, w_id, app_path, opt_authed, job_id).await?;
(resp.token, resp.expiration)
} else {
@@ -1756,7 +1757,7 @@ pub async fn build_embed_token_response(
token,
expiration,
raw_app,
sandbox: policy.sandbox,
sandbox,
app_path: Some(app_path.to_string()),
workspace_id: Some(w_id.to_string()),
sdk_scopes,
@@ -1764,6 +1765,31 @@ pub async fn build_embed_token_response(
})
}
/// Whether the viewer belongs to the app's workspace, the only audience for whom an
/// author's `sandbox: false` holds. Anyone else (anonymous, a guest, a superadmin of
/// another workspace) holds a session the author has no business running code with,
/// so the app renders isolated for them whatever its policy says.
async fn viewer_is_workspace_member(
db: &DB,
w_id: &str,
opt_authed: Option<&ApiAuthed>,
) -> Result<bool> {
let Some(authed) = opt_authed else {
return Ok(false);
};
if windmill_api_auth::scopes::has_guest_sentinel(authed.scopes.as_deref()) {
return Ok(false);
}
let member: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM usr WHERE workspace_id = $1 AND email = $2 AND NOT disabled)",
)
.bind(w_id)
.bind(&authed.email)
.fetch_one(db)
.await?;
Ok(member)
}
#[derive(Deserialize)]
pub struct PreviewSdkTokenRequest {
/// The app being edited. May not exist yet (a draft), so this is only used for
@@ -1825,9 +1851,9 @@ pub struct EmbedTokenResponse {
/// and the embed token entirely — it loads the app with the page credential.
#[serde(default)]
pub raw_app: bool,
/// WIN-2006: publisher opted this app into sandbox isolation. When false the
/// viewer runs the app same-origin with its full session (the default,
/// pre-isolation behavior).
/// Whether the viewer must render the app isolated: the publisher opted in, or
/// the viewer is not a member of the app's workspace. When false the viewer runs
/// the app same-origin with its full session.
#[serde(default)]
pub sandbox: bool,
/// WIN-2006: the resolved app path. The embedder uses it (together with
+20 -181
View File
@@ -9,21 +9,22 @@
use axum::extract::FromRequestParts;
use axum::http::{header, request::Parts, Method};
use axum::Extension;
use url::Url;
use windmill_api_auth::request_site::{self, Foreign};
use windmill_common::error::Error;
use windmill_common::users::COOKIE_NAME;
use crate::triggers::trigger_helpers::RunnableId;
/// Whether a request is a cross-site GET authenticating on the session cookie alone. A GET
/// handler that runs a script by path resolves it through [`Self::script_runnable`], which
/// refuses a Hub script on such a request.
/// Whether a request is a GET from a page of another origin authenticating on the session
/// cookie alone. A GET handler that runs a script by path resolves it through
/// [`Self::script_runnable`], which refuses a Hub script on such a request.
///
/// The cookie is `SameSite=Lax`, so browsers attach it to cross-site top-level GET
/// navigations. A `hub/` path runs any public Hub script, and an argument written
/// `$var:<path>` or `$res:<path>` is resolved as the caller before the script sees it: such a
/// GET lets any page pick a generic Hub script and hand it the victim's secrets, which the job
/// can then send anywhere.
/// The cookie is `SameSite=Lax`, so browsers attach it to top-level GET navigations from any
/// site, and to every request from a same-site page (a sibling subdomain). A `hub/` path runs
/// any public Hub script, and an argument written `$var:<path>` or `$res:<path>` is resolved as
/// the caller before the script sees it: such a GET lets any page pick a generic Hub script and
/// hand it the victim's secrets, which the job can then send anywhere. What counts as another
/// origin is decided by [`request_site::foreign_request`].
///
/// Workspace scripts and flows are not refused, by choice, so that GET links to them keep
/// working. That is a scope decision, not a safety property: they still take attacker-chosen
@@ -35,9 +36,10 @@ use crate::triggers::trigger_helpers::RunnableId;
/// way to authenticate, since it cannot set headers. The checks run in `extract_token`'s
/// order, header before cookie, because that is the order it resolves them in: a request
/// carrying both a cookie and `token=` authenticates on the cookie and is therefore still
/// ambient, which is also why a valid `token=` link opened cross-site while signed in is
/// refused.
pub struct CrossSiteGetGuard(Option<CrossSite>);
/// ambient, which is also why a valid `token=` link opened from another site while signed in
/// is refused. Other methods never get here with the cookie: `extract_token` sets it aside on
/// a state-changing request from another origin.
pub struct CrossSiteGetGuard(Option<Foreign>);
impl CrossSiteGetGuard {
pub fn script_runnable(
@@ -48,24 +50,12 @@ impl CrossSiteGetGuard {
let (Some(signal), RunnableId::HubScript(_)) = (&self.0, &runnable_id) else {
return Ok(runnable_id);
};
// The `Referer` leg is the one that can misfire, on a request that really was
// same-host: it compares against the hosts the backend can see, and a proxy that
// rewrites `Host` without setting `X-Forwarded-Host` leaves none of them matching
// what the browser addressed. Name the comparison so that shows up as a
// misconfiguration rather than as an unexplained 403.
if let CrossSite::RefererMismatch { referer, instance_hosts } = signal {
tracing::warn!(
referer_host = %referer,
?instance_hosts,
"refusing a cross-site GET Hub script run inferred from Referer; if the request \
was same-host, set `X-Forwarded-Host` on the proxy or configure `BASE_URL`"
);
}
signal.log("refusing a GET Hub script run on the session cookie");
Err(Error::PermissionDenied(
"a cross-site GET request cannot run a Hub script with the session cookie, which takes \
precedence over a `token` query parameter: pass the token in the `Authorization` \
header, or open the link from the instance itself or from a browser with no Windmill \
session"
"a GET request from another site cannot run a Hub script with the session cookie, \
which takes precedence over a `token` query parameter: pass the token in the \
`Authorization` header, or open the link from the instance itself or from a browser \
with no Windmill session"
.to_string(),
))
}
@@ -81,7 +71,7 @@ impl<S: Send + Sync> FromRequestParts<S> for CrossSiteGetGuard {
if parts.method != Method::GET {
return Ok(CrossSiteGetGuard(None));
}
let Some(signal) = cross_site_signal(parts) else {
let Some(signal) = request_site::foreign_request(&parts.headers, &parts.uri) else {
return Ok(CrossSiteGetGuard(None));
};
@@ -101,154 +91,3 @@ impl<S: Send + Sync> FromRequestParts<S> for CrossSiteGetGuard {
Ok(CrossSiteGetGuard(has_session_cookie.then_some(signal)))
}
}
enum CrossSite {
Declared,
RefererMismatch { referer: String, instance_hosts: Vec<String> },
}
fn cross_site_signal(parts: &Parts) -> Option<CrossSite> {
if let Some(site) = parts.headers.get("sec-fetch-site") {
return site
.as_bytes()
.eq_ignore_ascii_case(b"cross-site")
.then_some(CrossSite::Declared);
}
// Fetch Metadata rides only on potentially trustworthy URLs, so an instance served
// over plain http never receives `Sec-Fetch-Site` (nor does Safari before 16.4) while
// the cookie, not being `Secure` there either, still arrives. `Referer` is the only
// other thing a top-level GET navigation carries — `Origin` is not sent on one — so it
// is all that is left there, and it is weak: the default `strict-origin-when-cross-
// origin` policy already drops `Referer` on an https-to-http downgrade, so an https
// attacker page pointing a victim at a plain-http instance sends neither header. This
// leg catches an http-served attacker page and pre-16.4 Safari on https; the guard is
// load-bearing on https and best-effort at best on plain http. An absent `Referer`
// reads as not cross-site, matching how `Sec-Fetch-Site: none` (a bookmark, a typed
// URL) is treated.
let referer = referer_host(parts)?;
let instance_hosts: Vec<String> = instance_hosts(parts).collect();
(!instance_hosts
.iter()
.any(|host| host.eq_ignore_ascii_case(&referer)))
.then_some(CrossSite::RefererMismatch { referer, instance_hosts })
}
/// Every host a legitimate same-host request can name. `Host` alone is not enough: a
/// reverse proxy that forwards without preserving it (nginx `proxy_pass` with no
/// `proxy_set_header Host $host`) hands the backend the upstream's name, which no browser
/// `Referer` will ever match. None of these is browser-settable on a navigation — a
/// navigation carries no custom headers, and `BASE_URL` is instance config — so widening
/// the accepted set costs nothing.
fn instance_hosts(parts: &Parts) -> impl Iterator<Item = String> {
let base_url = windmill_common::BASE_URL.load();
[
request_host(parts),
header_host(parts, "x-forwarded-host"),
Url::parse(base_url.as_str())
.ok()
.and_then(|url| url.host_str().map(str::to_owned)),
]
.into_iter()
.flatten()
}
fn referer_host(parts: &Parts) -> Option<String> {
let referer = parts.headers.get(header::REFERER)?.to_str().ok()?;
Url::parse(referer).ok()?.host_str().map(str::to_owned)
}
fn request_host(parts: &Parts) -> Option<String> {
if let Some(host) = parts.uri.host() {
return Some(host.to_owned());
}
header_host(parts, header::HOST)
}
fn header_host(parts: &Parts, name: impl header::AsHeaderName) -> Option<String> {
host_of(parts.headers.get(name)?.to_str().ok()?)
}
/// The host in a `Host`-shaped header value: `host[:port]`, where `host` may be a bracketed
/// IPv6 literal, and where a chain of proxies appends to `X-Forwarded-Host` so only the
/// first entry is the one the browser addressed. The port is split off by the URL parser
/// rather than by hand-rolling the bracket rules.
fn host_of(value: &str) -> Option<String> {
let host = value.split(',').next()?.trim();
Url::parse(&format!("http://{host}"))
.ok()?
.host_str()
.map(str::to_owned)
}
#[cfg(test)]
mod tests {
use super::{cross_site_signal, host_of, CrossSite};
use axum::http::{request::Parts, Request};
fn parts(headers: &[(&str, &str)]) -> Parts {
let mut req = Request::get("/api/w/ws/jobs/run_wait_result/p/hub/1/x");
for (name, value) in headers {
req = req.header(*name, *value);
}
req.body(()).unwrap().into_parts().0
}
#[test]
fn sec_fetch_site_decides_when_present() {
let declared = |site| cross_site_signal(&parts(&[("sec-fetch-site", site)]));
assert!(matches!(declared("cross-site"), Some(CrossSite::Declared)));
for site in ["same-origin", "same-site", "none"] {
assert!(declared(site).is_none(), "{site} is not cross-site");
}
// The header outranks a `Referer` that disagrees with it.
let with_referer = parts(&[
("sec-fetch-site", "same-origin"),
("host", "windmill.example"),
("referer", "https://attacker.example/page"),
]);
assert!(cross_site_signal(&with_referer).is_none());
}
#[test]
fn referer_stands_in_when_sec_fetch_site_is_absent() {
let signal = |headers: &[(&str, &str)]| cross_site_signal(&parts(headers));
assert!(matches!(
signal(&[
("host", "windmill.example"),
("referer", "https://attacker.example/p")
]),
Some(CrossSite::RefererMismatch { .. })
));
// Ports differ between the frontend and the API, and do not make a request cross-site.
assert!(signal(&[
("host", "windmill.example:8000"),
("referer", "http://windmill.example:3000/apps"),
])
.is_none());
// A proxy that rewrote `Host` but forwarded the public name.
assert!(signal(&[
("host", "windmill-server.internal"),
("x-forwarded-host", "windmill.example"),
("referer", "https://windmill.example/apps"),
])
.is_none());
assert!(signal(&[("host", "windmill.example")]).is_none());
}
#[test]
fn host_of_strips_port_brackets_and_proxy_chain() {
assert_eq!(host_of("windmill.example"), Some("windmill.example".into()));
assert_eq!(
host_of("windmill.example:8000"),
Some("windmill.example".into())
);
assert_eq!(host_of("[::1]:8000"), Some("[::1]".into()));
assert_eq!(host_of("[::1]"), Some("[::1]".into()));
assert_eq!(
host_of("windmill.example, proxy.internal"),
Some("windmill.example".into())
);
assert_eq!(host_of(""), None);
assert_eq!(host_of("not a host"), None);
}
}
@@ -0,0 +1,75 @@
/*
* Author: Ruben Fiszel
* 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.
*/
use axum::http::header;
use windmill_common::error::Error;
use windmill_common::users::COOKIE_NAME;
/// For a GET route that acts (posts a message, signs a link) rather than reads: refuses a
/// request that would authenticate on the session cookie, which a browser attaches to a
/// cross-site navigation. Its callers are jobs and scripts, which send a bearer header.
pub async fn require_explicit_credential(
req: axum::extract::Request,
next: axum::middleware::Next,
) -> axum::response::Response {
use axum::response::IntoResponse;
if authenticates_on_session_cookie(req.headers()) {
return Error::PermissionDenied(
"this route does not accept the session cookie: pass a token in the \
`Authorization` header"
.to_string(),
)
.into_response();
}
next.run(req).await
}
/// Mirrors `extract_token`: a bearer header wins, and otherwise a session cookie is used
/// before any `token` query parameter.
fn authenticates_on_session_cookie(headers: &axum::http::HeaderMap) -> bool {
let has_bearer = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("Bearer "));
!has_bearer
&& headers
.get_all(header::COOKIE)
.iter()
.filter_map(|h| h.to_str().ok())
.flat_map(|h| h.split(';'))
.filter_map(|c| tower_cookies::Cookie::parse_encoded(c.trim()).ok())
.any(|c| c.name() == COOKIE_NAME)
}
#[cfg(test)]
mod tests {
use super::authenticates_on_session_cookie;
use axum::http::HeaderMap;
fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap {
let mut map = HeaderMap::new();
for (k, v) in pairs {
map.append(*k, v.parse().unwrap());
}
map
}
#[test]
fn session_cookie_is_refused_unless_a_bearer_header_wins() {
let cookie =
|pairs: &[(&'static str, &str)]| authenticates_on_session_cookie(&headers(pairs));
assert!(cookie(&[("cookie", "a=b; token=abc")]));
assert!(!cookie(&[
("cookie", "token=abc"),
("authorization", "Bearer xyz")
]));
assert!(!cookie(&[("cookie", "other=abc")]));
assert!(!cookie(&[("authorization", "Bearer xyz")]));
assert!(!cookie(&[]));
}
}
+5 -2
View File
@@ -90,6 +90,7 @@ mod azure_proxy_oss;
mod capture;
mod concurrency_groups;
mod csrf;
mod explicit_credential;
mod db;
mod db_health;
mod dbt;
@@ -1058,11 +1059,13 @@ pub async fn run_server(
})
.route(
"/w/{workspace_id}/jobs/slack_approval/{job_id}",
get(slack_approvals::request_slack_approval),
get(slack_approvals::request_slack_approval)
.route_layer(axum::middleware::from_fn(explicit_credential::require_explicit_credential)),
)
.route(
"/w/{workspace_id}/jobs/teams_approval/{job_id}",
get(teams_approvals_oss::request_teams_approval),
get(teams_approvals_oss::request_teams_approval)
.route_layer(axum::middleware::from_fn(explicit_credential::require_explicit_credential)),
)
.nest("/w/{workspace_id}/github_app", {
#[cfg(feature = "enterprise")]
+81 -10
View File
@@ -252,6 +252,21 @@ fn supported_scopes() -> Vec<String> {
scopes
}
/// Splits a requested scope into its scope tokens (RFC 6749 §3.3: separated by spaces).
/// The consent page shows the scopes split on spaces alone, so any other separator or control
/// character is refused: Rust's `split_whitespace` also splits on U+0085 and tabs, which would
/// grant scope tokens the page displayed as part of another one.
fn parse_scope_param(scope: &str) -> std::result::Result<Vec<String>, &'static str> {
if scope.bytes().any(|b| !(0x20..=0x7e).contains(&b)) {
return Err("scope may only hold printable ASCII scope tokens separated by spaces");
}
Ok(scope
.split(' ')
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect())
}
/// GET /.well-known/oauth-authorization-server/api/w/:workspace_id/mcp/oauth/server
///
/// `client_base_url` serves what the MCP client calls itself, `base_url` the authorization
@@ -786,6 +801,16 @@ async fn oauth_authorize_inner(
.into_response();
}
if let Err(e) = parse_scope_param(params.scope.as_deref().unwrap_or_default()) {
return OAuthErrorRedirect::new(
&params.redirect_uri,
"invalid_scope",
Some(e),
params.state.as_deref(),
)
.into_response();
}
let code_challenge = match &params.code_challenge {
Some(challenge) if !challenge.is_empty() => challenge.as_str(),
_ => {
@@ -837,7 +862,6 @@ async fn oauth_authorize_inner(
serde_urlencoded::to_string(&[
(mode_key, mode_value),
("client_id", params.client_id.as_str()),
("client_name", client.client_name.as_str()),
("redirect_uri", params.redirect_uri.as_str()),
("scope", params.scope.as_deref().unwrap_or("mcp:all")),
("state", params.state.as_deref().unwrap_or("")),
@@ -952,11 +976,8 @@ async fn oauth_approve_inner(
let code = format!("mcp-code-{}", rd_string(32));
let mut scopes: Vec<String> = form
.scope
.split_whitespace()
.map(|s| s.to_string())
.collect();
let mut scopes =
parse_scope_param(&form.scope).map_err(|e| Error::BadRequest(e.to_string()))?;
if scopes.iter().any(|s| s == "mcp:all") && !scopes.iter().any(|s| s == SESSION_SCOPE) {
scopes.push(SESSION_SCOPE.to_string());
}
@@ -1146,8 +1167,8 @@ pub async fn gateway_oauth_approve(
workspace_ids.extend(form.workspace_id);
}
// A selection of scripts and flows names paths, which only mean something in one workspace.
if !scope.split_whitespace().any(|s| s == "mcp:all")
&& (form.all_workspaces || workspace_ids.len() > 1)
let requested = parse_scope_param(&scope).map_err(|e| Error::BadRequest(e.to_string()))?;
if !requested.iter().any(|s| s == "mcp:all") && (form.all_workspaces || workspace_ids.len() > 1)
{
return Err(Error::BadRequest(
"Selected scripts and flows come from one workspace: pick one".to_string(),
@@ -1191,6 +1212,33 @@ pub async fn gateway_oauth_approve(
.await
}
#[derive(Debug, Serialize)]
pub struct RegisteredClient {
client_id: String,
client_name: String,
redirect_uris: Vec<String>,
created_at: chrono::DateTime<chrono::Utc>,
}
/// GET /api/mcp/gateway/oauth/server/client/:client_id — what the consent page shows: the
/// authorization URL's own copy of the client name is the client's to choose.
pub async fn get_registered_client(
Extension(db): Extension<DB>,
_authed: ApiAuthed,
Path(client_id): Path<String>,
) -> Result<Json<RegisteredClient>> {
let client = sqlx::query_as!(
RegisteredClient,
"SELECT client_id, client_name, redirect_uris, created_at FROM mcp_oauth_server_client
WHERE client_id = $1",
client_id
)
.fetch_optional(&db)
.await?
.ok_or_else(|| Error::NotFound("Unknown client_id".to_string()))?;
Ok(Json(client))
}
/// Gateway approval form — same as ApprovalForm, plus the workspaces the token reaches:
/// one binds the token to it, several are listed in its scopes.
#[derive(Debug, Deserialize)]
@@ -1245,12 +1293,35 @@ pub fn gateway_unauthed_service() -> Router {
/// Gateway OAuth endpoints that require authentication
/// Mounted at /api/mcp/gateway/oauth/server (inside authenticated section)
pub fn gateway_authed_service() -> Router {
Router::new().route("/approve", post(gateway_oauth_approve))
Router::new()
.route("/approve", post(gateway_oauth_approve))
.route("/client/{client_id}", get(get_registered_client))
}
#[cfg(test)]
mod tests {
use super::{build_oauth_metadata, validate_redirect_uri};
use super::{build_oauth_metadata, parse_scope_param, validate_redirect_uri};
#[test]
fn scope_param_splits_on_spaces_only() {
assert_eq!(
parse_scope_param(" mcp:scripts:f/x/* mcp:runnables_as_tools ").unwrap(),
vec!["mcp:scripts:f/x/*", "mcp:runnables_as_tools"]
);
assert_eq!(parse_scope_param("").unwrap(), Vec::<String>::new());
for scope in [
"mcp:scripts:f/x/*\u{85}mcp:all",
"mcp:scripts:f/x/*\tmcp:all",
"mcp:scripts:f/x/*\nmcp:all",
"mcp:scripts:f/x/*\u{a0}mcp:all",
"mcp:scripts:f/x/*\u{2028}mcp:all",
] {
assert!(
parse_scope_param(scope).is_err(),
"expected {scope:?} to be refused"
);
}
}
#[test]
fn authorization_endpoint_stays_on_base_url() {
+5 -2
View File
@@ -1,5 +1,5 @@
#[cfg(feature = "mcp")]
use axum::routing::{get, post};
use axum::routing::post;
use axum::Router;
/// Wraps the subcrate's workspaced_service with the mcp_tools routes
@@ -9,9 +9,12 @@ pub fn workspaced_service() -> Router {
#[cfg(feature = "mcp")]
use crate::mcp_tools::{call_mcp_tool, get_mcp_tools};
// Listing tools sends the caller's resolved secrets to the URL the resource names, so it
// is a POST: the `SameSite=Lax` session cookie rides on a cross-site link or redirect to a
// GET, which would let anyone who can share a link pick the resource for the caller.
#[cfg(feature = "mcp")]
let router = router
.route("/mcp_tools/{*path}", get(get_mcp_tools))
.route("/mcp_tools/{*path}", post(get_mcp_tools))
.route("/mcp_call_tool/{*path}", post(call_mcp_tool));
router
+47
View File
@@ -93,6 +93,24 @@ impl ScopeDefinition {
}
}
/// Parses the scope an operation on one item needs. Its path is taken whole: a `,` or
/// `*` in a request path is part of the name, not a list or a pattern, so it must not be
/// read with the grant grammar of [`Self::from_scope_string`].
pub fn from_required_scope_string(scope: &str) -> Result<Self> {
let mut def = Self::from_scope_string(scope)?;
if def.resource.is_some() {
let path = scope.rsplit(':').next().unwrap_or_default();
def.resource = Some(vec![path.to_string()]);
}
Ok(def)
}
/// Whether this grant covers `required`, a scope parsed with
/// [`Self::from_required_scope_string`]. Only the grant side is read as a pattern.
pub fn grants(&self, required: &ScopeDefinition) -> bool {
scope_contains(self, required)
}
pub fn as_string(&self) -> String {
match (&self.kind, &self.resource) {
(Some(kind), Some(resource)) => {
@@ -514,6 +532,15 @@ pub fn scope_contains(caller: &ScopeDefinition, requested: &ScopeDefinition) ->
}
match (&caller.resource, &requested.resource) {
// A `resources:` pattern also resolves the variables it matches
// (`check_resource_var_ref_scope`), which a pathless `resources:` scope does not,
// so the pattern is not narrower than it.
(None, Some(requested_resources))
if caller.domain == "resources"
&& requested_resources.iter().any(|r| r.contains('*')) =>
{
false
}
// Caller is unrestricted on resources: covers everything.
(None, _) => true,
// Caller is resource-restricted but the request is not: broader, unless the
@@ -726,6 +753,26 @@ mod job_token_scopes_tests {
);
}
#[test]
fn pathless_resources_scope_does_not_contain_patterns() {
let s = |x: &str| ScopeDefinition::from_scope_string(x).unwrap();
let contains = |caller: &str, requested: &str| scope_contains(&s(caller), &s(requested));
for requested in ["resources:read:*", "resources:read:f/a/*"] {
assert!(!contains("resources:read", requested));
assert!(!contains("resources:write", requested));
}
assert!(contains("resources:read", "resources:read:f/a/b"));
assert!(contains("resources:write:*", "resources:read:f/a/*"));
assert!(contains("variables:read", "variables:read:f/a/*"));
assert_eq!(
intersect_job_token_scopes(
Some(&v(&["resources:read"])),
Some(&v(&["resources:read:*"]))
),
Some(v(&["resources:read"]))
);
}
#[test]
fn empty_effective_scopes_mint_a_scoped_token() {
assert_eq!(
+4
View File
@@ -3530,6 +3530,8 @@ async fn create_resource_type(
Path(w_id): Path<String>,
Json(resource_type): Json<CreateResourceType>,
) -> Result<(StatusCode, String)> {
// Resource types are shared by the whole workspace, so a path-scoped token cannot write them.
check_scopes(&authed, || "resources:write".to_string())?;
if let RuleCheckResult::Blocked(msg) = check_deploy_rules(
&w_id,
AuditAuthorable::username(&authed),
@@ -3641,6 +3643,7 @@ async fn delete_resource_type(
Path((w_id, name)): Path<(String, String)>,
) -> Result<String> {
require_admin(authed.is_admin, &authed.username)?;
check_scopes(&authed, || "resources:write".to_string())?;
if let RuleCheckResult::Blocked(msg) = check_deploy_rules(
&w_id,
AuditAuthorable::username(&authed),
@@ -3705,6 +3708,7 @@ async fn update_resource_type(
Path((w_id, name)): Path<(String, String)>,
Json(ns): Json<EditResourceType>,
) -> Result<String> {
check_scopes(&authed, || "resources:write".to_string())?;
use sql_builder::prelude::*;
if let RuleCheckResult::Blocked(msg) = check_deploy_rules(
&w_id,
+5 -1
View File
@@ -85,9 +85,13 @@ pub fn workspaced_service() -> Router {
async fn list_contextual_variables(
Path(w_id): Path<String>,
ApiAuthed { username, email, .. }: ApiAuthed,
authed: ApiAuthed,
Extension(db): Extension<DB>,
) -> JsonResult<Vec<ContextualVariable>> {
// The list carries the workspace's environment variables with their values, which
// belong to no single path.
check_scopes(&authed, || "variables:read".to_string())?;
let ApiAuthed { username, email, .. } = authed;
Ok(Json(
get_reserved_variables(
&db.into(),
+1 -1
View File
@@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts";
import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts";
import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts";
export const VERSION = "v1.888.0";
export const VERSION = "v1.889.1";
export async function login(email: string, password: string): Promise<string> {
return await windmill.UserService.login({
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@windmill-labs/chat-sdk",
"version": "1.888.0",
"version": "1.889.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@windmill-labs/chat-sdk",
"version": "1.888.0",
"version": "1.889.1",
"license": "Apache-2.0",
"devDependencies": {
"@ai-sdk/react": "^4.0.102",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@windmill-labs/chat-sdk",
"description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app",
"version": "1.888.0",
"version": "1.889.1",
"author": "Ruben Fiszel",
"license": "Apache-2.0",
"homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme",
+2 -4
View File
@@ -102,12 +102,10 @@ export function replaceInlineScripts(
const o: Record<string, any> = v as any;
if (o["content"] && o["content"].startsWith("!inline")) {
const basePath = localPath + o["content"].split(" ")[1];
o["content"] = readInlinePathSync(basePath);
o["content"] = readInlinePathSync(o["content"].split(" ")[1], localPath);
}
if (o["lock"] && o["lock"].startsWith("!inline")) {
const basePath = localPath + o["lock"].split(" ")[1];
o["lock"] = readInlinePathSync(basePath);
o["lock"] = readInlinePathSync(o["lock"].split(" ")[1], localPath);
}
} else {
replaceInlineScripts(v, localPath, addType);
+10 -3
View File
@@ -23,7 +23,13 @@ import {
ScriptLanguage,
workspaceDependenciesLanguages,
} from "../../utils/script_common.ts";
import { generateHash, getHeaders, readTextFile, writeIfChanged } from "../../utils/utils.ts";
import {
generateHash,
getHeaders,
inlinePathWithin,
readTextFile,
writeIfChanged,
} from "../../utils/utils.ts";
import { detectAuthGatewayChallenge } from "../../utils/http_guards.ts";
import { exts } from "../script/script.ts";
import { FSFSElement, yamlOptions, yamlSortedEntries } from "../sync/sync.ts";
@@ -227,9 +233,10 @@ export async function generateAppLocksInternal(
let content = inlineScript.content;
// Resolve !inline references
if (typeof content === "string" && content.startsWith("!inline ")) {
const filePath = appFolder + SEP + content.replace("!inline ", "");
try {
content = await readTextFile(filePath);
content = await readTextFile(
inlinePathWithin(content.replace("!inline ", ""), appFolder),
);
} catch {
return inlineScript;
}
+35 -2
View File
@@ -50,6 +50,7 @@ import {
hasFolderSuffix,
loadNonDottedPathsSetting,
} from "../../utils/resource_folders.ts";
import { isAllowedHostHeader, isJobId } from "../../utils/dev_server_access.ts";
import {
createRecorderShellHTML,
DEV_RECORDER_BUNDLE,
@@ -993,8 +994,28 @@ async function dev(opts: DevOptions, appFolder?: string) {
res.end(createHTML("/dist/bundle.js", "/dist/bundle.css", appCtx));
});
// Create WebSocket server on the same HTTP server
const wss = new WebSocketServer({ server });
// Its messages run runnables, SQL and API calls with the CLI's token, and a
// browser lets a page of any origin open `ws://localhost:<port>`: only the
// page this server serves, reached under a name DNS cannot re-point, may
// upgrade.
const wss = new WebSocketServer({
server,
verifyClient: (info: { req: http.IncomingMessage }) => {
const { origin, host: hostHeader } = info.req.headers;
if (
isOwnOrigin(origin, hostHeader) &&
isAllowedHostHeader(hostHeader, host)
) {
return true;
}
log.warn(
colors.yellow(
`[WebSocket] Refused connection from origin ${JSON.stringify(origin)} (host ${JSON.stringify(hostHeader)})`,
),
);
return false;
},
});
// SQL migration state (defined here so it's accessible in WebSocket handler)
const sqlToApplyPath = path.join(process.cwd(), "sql_to_apply");
@@ -1202,6 +1223,18 @@ async function dev(opts: DevOptions, appFolder?: string) {
return { uuid, result };
};
if (
(type === "waitJob" || type === "getJob" || type === "streamJob") &&
!isJobId(jobId)
) {
respond(
type === "streamJob" ? "streamJobRes" : "backendRes",
{ message: `Invalid job id: ${JSON.stringify(jobId)}` },
true,
);
return;
}
switch (type) {
case "backend": {
// Run a runnable synchronously and wait for result
+99 -21
View File
@@ -9,7 +9,7 @@ import * as http from "node:http";
import * as https from "node:https";
import * as open from "open";
import { access, readdir, realpath, stat, unlink, writeFile } from "node:fs/promises";
import { readTextFile } from "../../utils/utils.ts";
import { inlinePathWithin, readTextFile } from "../../utils/utils.ts";
import { watch } from "node:fs";
import { getTypeStrFromPath, GlobalOptions } from "../../types.ts";
import { ignoreF } from "../sync/sync.ts";
@@ -51,6 +51,12 @@ import * as fs from "node:fs";
import { listSyncCodebases } from "../../utils/codebase.ts";
import { createPreviewLocalScriptReader } from "../../utils/local_path_scripts.ts";
import { resolveBindPort, BIND_HOST } from "../../utils/port-probe.ts";
import {
bindsLocalhost,
isAllowedDevPageOrigin,
isAllowedHostHeader,
isWithinFolder,
} from "../../utils/dev_server_access.ts";
import {
snapshotPathScripts,
tagReplacedPathScripts,
@@ -212,6 +218,7 @@ export interface DevOpts {
proxyPort?: number;
path?: string;
open?: boolean;
host?: string;
}
export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
@@ -266,6 +273,32 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
const ignore = await ignoreF(opts);
const codebases = await listSyncCodebases(opts);
// Paths the dev socket reads and writes come from its client: a message
// names a file, and a flow.yaml (which a message can rewrite) names its
// `!inline` files and the scripts it calls. None may resolve outside the
// checkout. Relative paths resolve against the cwd, which can spell the
// checkout differently from its realpath (a Windows 8.3 short name such as
// `RUNNER~1`, a symlinked parent), so either spelling counts as inside.
const cwd = process.cwd();
const isInCheckout = (p: string) =>
isWithinFolder(base, p) || isWithinFolder(cwd, p);
function inCheckout(p: string): string {
if (!isInCheckout(p)) {
throw new Error(`${p} is outside of ${base}`);
}
return p;
}
const createLocalScriptReader = () => {
const read = createPreviewLocalScriptReader({
exts,
defaultTs: opts.defaultTs,
codebases,
});
// Outside the checkout is not a local script: the deployed one is used.
return (p: string) =>
isInCheckout(p) ? read(p) : Promise.resolve(undefined);
};
// Resolve relative imports from local (not-yet-deployed) content so dev-page
// previews use locally-edited workspace scripts instead of the deployed
// versions. Diverged local scripts are uploaded to temp storage once here
@@ -325,6 +358,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
const rest: string[] = [];
const scriptsWithModules = new Set<string>();
for (const raw of pathsToLoad) {
inCheckout(raw);
const rel = (await realpath(raw).catch(() => raw))
.replace(base + SEP, "")
.replaceAll("\\", "/");
@@ -380,7 +414,8 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
)) as FlowFile;
await replaceInlineScripts(
localFlow.value.modules,
async (path: string) => await readTextFile(localPath + path),
async (path: string) =>
await readTextFile(inlinePathWithin(path, localPath)),
log,
localPath,
SEP,
@@ -390,12 +425,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
// Helpers walk `flowValue` (modules/failure_module/preprocessor_module),
// so pass `.value`, not the FlowFile wrapper.
snapshotPathScripts(localFlow.value);
const localScriptReader = createPreviewLocalScriptReader({
exts,
defaultTs: opts.defaultTs,
codebases,
});
await replaceAllPathScriptsWithLocal(localFlow.value, localScriptReader, log);
await replaceAllPathScriptsWithLocal(localFlow.value, createLocalScriptReader(), log);
tagReplacedPathScripts(localFlow.value);
currentLastEdit = {
type: "flow",
@@ -457,7 +487,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
// Load a resource by its windmill path (e.g., "u/admin/my_script" or "f/my_flow")
async function loadWmPath(wmPath: string): Promise<LastEditScript | LastEditFlow | undefined> {
wmPath = normalizeWmPath(wmPath);
wmPath = inCheckout(normalizeWmPath(wmPath));
// Try as flow — check both dotted and non-dotted suffixes
let flowDir: string | undefined;
let flowYaml: string | undefined;
@@ -475,19 +505,14 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
const localFlow = (await yamlParseFile(flowYaml)) as FlowFile;
await replaceInlineScripts(
localFlow.value.modules,
async (p: string) => await readTextFile(flowDir + p),
async (p: string) => await readTextFile(inlinePathWithin(p, flowDir)),
log,
flowDir,
SEP,
undefined,
);
snapshotPathScripts(localFlow.value);
const localScriptReader = createPreviewLocalScriptReader({
exts,
defaultTs: opts.defaultTs,
codebases,
});
await replaceAllPathScriptsWithLocal(localFlow.value, localScriptReader, log);
await replaceAllPathScriptsWithLocal(localFlow.value, createLocalScriptReader(), log);
tagReplacedPathScripts(localFlow.value);
const edit: LastEditFlow = {
type: "flow",
@@ -577,6 +602,10 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
if (flowDir.includes("://")) {
flowDir = new URL(flowDir).pathname;
}
inCheckout(flowDir);
if (!isFlowFolderName(path.basename(flowDir))) {
throw new Error(`${flowDir} is not a flow folder`);
}
// Restore PathScripts BEFORE extracting so we don't write a file for the
// inlined body of a `type: 'script'` reference.
@@ -637,6 +666,12 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
));
}
// Checked before any write, so a refused edit leaves the folder untouched.
for (const s of allExtracted) {
if (!isWithinFolder(flowDir, flowDir + s.path)) {
throw new Error(`${s.path} is outside of ${flowDir}`);
}
}
for (const s of allExtracted) {
const filePath = flowDir + s.path;
// `!inline foo.ts` is a YAML directive that points at another file —
@@ -697,6 +732,32 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
const connectedClients: Set<WebSocket> = new Set();
const bindHost = opts.host ?? BIND_HOST;
if (!bindsLocalhost(bindHost)) {
throw new Error(
`--host ${bindHost}: the dev page connects to localhost, so bind to a loopback address or to 0.0.0.0 (every interface)`
);
}
// The socket ships the checkout's sources and writes flow edits back to
// disk, and any browser tab can open `ws://localhost:<port>`. The dev page
// is served by the workspace remote (or, with --proxy-port, by this
// machine), and a page cannot forge the Origin it states.
function verifyDevClient(info: { req: http.IncomingMessage }): boolean {
const { origin, host } = info.req.headers;
if (
isAllowedDevPageOrigin(origin, workspace.remote) &&
isAllowedHostHeader(host, bindHost)
) {
return true;
}
log.warn(
`Refused a dev WebSocket connection from origin ${JSON.stringify(origin)} (host ${JSON.stringify(host)}): ` +
`the dev page is served from ${new URL(workspace.remote).origin} or localhost`
);
return false;
}
// Send a message to all connected clients, gated by --path when set so we
// don't spam clients (or risk yanking their view) with edits to unrelated files.
function broadcastChanges(lastEdit: LastEditScript | LastEditFlow) {
@@ -752,7 +813,9 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
}
if (data.type === "load") {
loadPaths([data.path]);
loadPaths([data.path]).catch((err) => {
log.error(`Failed to load ${data.path}: ${err}`);
});
} else if (data.type === "flow") {
pendingFlowMessage = data;
if (flowDebounceTimer) {
@@ -833,12 +896,19 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
const remotePort = remote.port ? parseInt(remote.port) : (isHttps ? 443 : 80);
const httpModule = isHttps ? https : http;
const devWss = new WebSocketServer({ noServer: true });
const devWss = new WebSocketServer({ noServer: true, verifyClient: verifyDevClient });
setupDevWs(devWss);
const proxyWss = new WebSocketServer({ noServer: true });
const proxyServer = http.createServer((clientReq, clientRes) => {
// `/` hands out the workspace token: refuse a name DNS could have
// re-pointed at this machine.
if (!isAllowedHostHeader(clientReq.headers.host, bindHost)) {
clientRes.writeHead(403);
clientRes.end("Forbidden host");
return;
}
const parsedUrl = new URL(clientReq.url ?? "/", `http://localhost`);
if (parsedUrl.pathname === "/" || parsedUrl.pathname === "") {
let devUrl = `/dev?workspace=${workspace.workspaceId}&local=true&wm_token=${workspace.token}&port=${proxyPort}`;
@@ -889,6 +959,10 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
// WebSocket upgrades
proxyServer.on("upgrade", (req, socket, head) => {
if (!isAllowedHostHeader(req.headers.host, bindHost)) {
socket.destroy();
return;
}
const pathname = req.url?.split("?")[0] ?? "";
if (pathname === "/ws_dev" || pathname === "/ws") {
@@ -936,7 +1010,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
});
return new Promise<void>((resolve) => {
proxyServer.listen(proxyPort, BIND_HOST, () => {
proxyServer.listen(proxyPort, bindHost, () => {
console.log(`Dev proxy listening on http://localhost:${proxyPort}`);
if (opts.path) {
console.log(`Watching ${opts.path} — edits will live-reload in the dev page`);
@@ -970,7 +1044,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
res.writeHead(200);
res.end();
});
const wss = new WebSocketServer({ server });
const wss = new WebSocketServer({ server, verifyClient: verifyDevClient });
setupDevWs(wss);
// Probe both IPv4 and IPv6 stacks before binding. Same dual-stack
@@ -999,7 +1073,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) {
);
}
server.listen(port, BIND_HOST, () => {
server.listen(port, bindHost, () => {
console.log(`Dev WebSocket listening on ws://localhost:${port}/ws`);
});
}
@@ -1037,6 +1111,10 @@ const command = new Command()
"--no-open",
"Do not open the browser automatically"
)
.option(
"--host <host:string>",
"Address to bind the dev server to: a loopback address or 0.0.0.0 for every interface (default: 127.0.0.1, this machine only)"
)
.action(dev as any);
export default command;
+9 -3
View File
@@ -8,7 +8,11 @@ import { ciTestBatchDeployed, ciTestBatchSkip } from "../../core/ci_test_batch.t
import { dirname, sep as SEP, resolve as pathResolve } from "node:path";
import { stringify as yamlStringify } from "yaml";
import { yamlParseFile } from "../../utils/yaml.ts";
import { readTextFile, validateRequiredArgs } from "../../utils/utils.ts";
import {
inlinePathWithin,
readTextFile,
validateRequiredArgs,
} from "../../utils/utils.ts";
import * as wmill from "../../../gen/services.gen.ts";
import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
import { buildFolderPath, getMetadataFileName, loadNonDottedPathsSetting } from "../../utils/resource_folders.ts";
@@ -181,7 +185,8 @@ export async function readLocalFlow(
}
const localFlow = (await yamlParseFile(localPath + "flow.yaml")) as FlowFile;
const fileReader = async (path: string) => await readTextFile(localPath + path);
const fileReader = async (path: string) =>
await readTextFile(inlinePathWithin(path, localPath));
const missingFiles: string[] = [];
await replaceInlineScripts(
localFlow.value.modules,
@@ -683,7 +688,8 @@ async function preview(
const localFlow = (await yamlParseFile(flowPath + "flow.yaml")) as FlowFile;
// Replace inline scripts with their actual content
const fileReader = async (path: string) => await readTextFile(flowPath + path);
const fileReader = async (path: string) =>
await readTextFile(inlinePathWithin(path, flowPath));
await replaceInlineScripts(
localFlow.value.modules,
fileReader,
+9 -2
View File
@@ -22,7 +22,13 @@ import { ScriptLanguage } from "../../utils/script_common.ts";
import { extractInlineScripts as extractInlineScriptsForFlows, extractCurrentMapping, legacyLockPathForContent } from "../../../windmill-utils-internal/src/inline-scripts/extractor.ts";
import { newPathAssigner } from "../../../windmill-utils-internal/src/path-utils/path-assigner.ts";
import { generateHash, getHeaders, readTextFile, writeIfChanged } from "../../utils/utils.ts";
import {
generateHash,
getHeaders,
inlinePathWithin,
readTextFile,
writeIfChanged,
} from "../../utils/utils.ts";
import { detectAuthGatewayChallenge } from "../../utils/http_guards.ts";
import { exts } from "../script/script.ts";
import { FSFSElement, yamlOptions } from "../sync/sync.ts";
@@ -246,7 +252,8 @@ export async function generateFlowLockInternal(
if (!noStaleMessage) {
log.info(`Recomputing locks of ${changedScripts.join(", ")} in ${folder}`);
}
const fileReader = async (path: string) => await readTextFile(folder + SEP + path);
const fileReader = async (path: string) =>
await readTextFile(inlinePathWithin(path, folder));
// Capture existing module-ID-to-file-path mapping before replaceInlineScripts
// overwrites the !inline references with actual file content. This preserves
+47 -7
View File
@@ -18,7 +18,11 @@ import { ciTestBatchDeployed, ciTestBatchSkip } from "../../core/ci_test_batch.t
import { sep as SEP } from "node:path";
import * as wmill from "../../../gen/services.gen.ts";
import { Resource } from "../../../gen/types.gen.ts";
import { readInlinePathSync, readTextFile } from "../../utils/utils.ts";
import {
inlinePathWithin,
readInlinePathSync,
readTextFile,
} from "../../utils/utils.ts";
import { isWorkspaceSpecificFile } from "../../core/specific_items.ts";
import { getCurrentGitBranch } from "../../utils/git.ts";
import {
@@ -78,6 +82,38 @@ export function validateFilesetPointer(
}
}
/**
* A synced resource's `!inline` content pointer must name its own
* `<resource path>.resource.file.<ext>`, the only file a pull writes for it.
* The pointer is pulled verbatim from the stored value, so any other target
* would read an unrelated local file into the pushed resource.
*/
export function validateInlineResourcePointer(
ref: string,
remotePath: string,
localPath?: string,
): void {
const normalize = (p: string) => p.replaceAll("\\", "/");
const pointer = normalize(ref);
const bases = [normalize(remotePath.replaceAll(SEP, "/"))];
if (localPath) {
bases.push(normalize(localPath).replace(/\.resource\.(ya?ml|json)$/, ""));
}
const ok = bases.some((base) => {
const prefix = base + ".resource.file.";
const ext = pointer.slice(prefix.length);
return pointer.startsWith(prefix) && ext !== "" && !ext.includes("/");
});
if (!ok) {
const expected = bases[0] + ".resource.file.<ext>";
throw new Error(
`Resource ${bases[0]} uses '!inline ${ref}', but a resource's content ` +
`file must live next to it, at '${expected}'. Move the file there and ` +
`update the '!inline' value to match.`,
);
}
}
export async function pushResource(
workspace: string,
remotePath: string,
@@ -85,10 +121,11 @@ export async function pushResource(
localResource: ResourceFile,
originalLocalPath?: string,
wsSpecific?: boolean,
// Sync pushes reject non-canonical fileset pointers (the diff engine can
// only round-trip the canonical layout); the standalone `resource push`
// command pushes a single explicit file, where any pointer is fine.
enforceCanonicalFileset?: boolean,
// Sync pushes reject non-canonical fileset and content-file pointers (the
// diff engine can only round-trip the canonical layout, and the pointer is
// pulled data); the standalone `resource push` command pushes a single
// explicit file, where any pointer inside the current directory is fine.
enforceCanonicalPointers?: boolean,
permissionedAsContext?: PermissionedAsContext,
): Promise<void> {
remotePath = removeType(remotePath, "resource");
@@ -110,12 +147,15 @@ export async function pushResource(
const resolveInlineContent = async () => {
if (typeof localResource.value === "string" && localResource.value.startsWith("!inline_fileset ")) {
const dirPath = localResource.value.split(" ")[1];
if (enforceCanonicalFileset) {
if (enforceCanonicalPointers) {
validateFilesetPointer(dirPath, remotePath);
}
localResource.value = await readFilesetDirectory(dirPath.replaceAll("/", SEP));
localResource.value = await readFilesetDirectory(inlinePathWithin(dirPath));
} else if (localResource.value["content"]?.startsWith("!inline ")) {
const basePath = localResource.value["content"].split(" ")[1];
if (enforceCanonicalPointers) {
validateInlineResourcePointer(basePath, remotePath, originalLocalPath);
}
// If we're processing a branch-specific metadata file, read from branch-specific resource file
+30 -3
View File
@@ -1169,6 +1169,30 @@ export function rawAppPathWithinFolder(
return resolved;
}
/**
* Join a fileset key or script module name under `baseFolder`. Both are remote
* data written to disk on pull and read back with `/` joins on push, so only a
* plain relative `/`-separated path round-trips; anything else is refused.
*/
export function remoteKeyWithinFolder(
baseFolder: string,
key: string,
): string {
const segments = key.split("/");
if (
key.includes("\0") ||
key.includes("\\") ||
key.startsWith("/") ||
/^[A-Za-z]:/.test(key) ||
segments.some((s) => s === "" || s === "." || s === "..")
) {
throw new Error(
`path ${JSON.stringify(key)} must be a relative path inside ${baseFolder}`,
);
}
return rawAppPathWithinFolder(baseFolder, key);
}
export function ZipFSElement(
zip: JSZip,
useYaml: boolean,
@@ -1819,7 +1843,7 @@ export function ZipFSElement(
// Yield the module content file
yield {
isDirectory: false,
path: path.join(moduleFolderPath, relPath),
path: remoteKeyWithinFolder(moduleFolderPath, relPath),
async *getChildren() {},
async getContentText() {
return mod.content;
@@ -1831,7 +1855,10 @@ export function ZipFSElement(
const baseName = relPath.replace(/\.[^.]+$/, "");
yield {
isDirectory: false,
path: path.join(moduleFolderPath, baseName + ".lock"),
path: remoteKeyWithinFolder(
moduleFolderPath,
baseName + ".lock",
),
async *getChildren() {},
async getContentText() {
return mod.lock!;
@@ -1877,7 +1904,7 @@ export function ZipFSElement(
if (typeof fileContent === "string") {
yield {
isDirectory: false,
path: path.join(filesetBasePath, relPath),
path: remoteKeyWithinFolder(filesetBasePath, relPath),
async *getChildren() {},
async getContentText() {
return fileContent;
+1 -1
View File
@@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork";
// (e.g. utils.ts) can read it without importing main.ts and creating a circular
// dependency (main → workspace → utils → main) that triggers a TDZ.
// Re-exported from main.ts for backwards compatibility.
export const VERSION = "1.888.0";
export const VERSION = "1.889.1";
+1
View File
@@ -9006,6 +9006,7 @@ Watch local file changes and live-reload the dev page for preview. Does NOT depl
- \`--proxy-port <port:number>\` - Port for a localhost reverse proxy to the remote Windmill server
- \`--path <path:string>\` - Watch a specific windmill path (e.g., u/admin/my_script or f/my_flow)
- \`--no-open\` - Do not open the browser automatically
- \`--host <host:string>\` - Address to bind the dev server to: a loopback address or 0.0.0.0 for every interface (default: 127.0.0.1, this machine only)
### digest
+96
View File
@@ -0,0 +1,96 @@
/**
* Who may talk to the local dev servers (`wmill dev`, `wmill app dev`). Their
* WebSockets act on the developer's files and Windmill token, and a browser
* lets a page of any origin open `ws://localhost:<port>`, so the upgrade is
* gated on the headers a page cannot choose: `Origin` and `Host`.
*/
import * as path from "node:path";
import { isIP } from "node:net";
const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
export function isLoopbackHostname(hostname: string): boolean {
return LOOPBACK_HOSTNAMES.has(hostname.toLowerCase());
}
/**
* Whether a server bound to `host` answers on `localhost`, which is where the
* dev page connects: a loopback address, or every interface.
*/
export function bindsLocalhost(host: string): boolean {
return isLoopbackHostname(host) || host === "0.0.0.0" || host === "::" || host === "[::]";
}
/** Whether `origin` is a page served from this machine (any loopback port). */
export function isLoopbackOrigin(origin: string): boolean {
try {
const u = new URL(origin);
return (
(u.protocol === "http:" || u.protocol === "https:") &&
isLoopbackHostname(u.hostname)
);
} catch {
return false;
}
}
/**
* Whether the `Host` header names this server under a name that cannot have
* been re-pointed at it by DNS: a loopback name, an IP literal, or the host
* the server was explicitly bound to. A server bound to a wildcard address is
* reachable by any name the developer chose to expose, so any Host passes.
*/
export function isAllowedHostHeader(
host: string | undefined,
bindHost: string,
): boolean {
if (bindHost === "0.0.0.0" || bindHost === "::") return true;
if (host === undefined) return false;
let hostname: string;
try {
hostname = new URL(`http://${host}`).hostname;
} catch {
return false;
}
const bare = hostname.replace(/^\[|\]$/g, "");
return (
isLoopbackHostname(hostname) ||
isIP(bare) !== 0 ||
hostname.toLowerCase() === bindHost.toLowerCase()
);
}
/**
* Whether a browser page of `origin` may open the `wmill dev` socket: the
* workspace remote (where the dev page is served) or a page on this machine
* (the `--proxy-port` proxy, a locally run frontend). No Origin is a
* non-browser client; a forged one is no worse than no header at all.
*/
export function isAllowedDevPageOrigin(
origin: string | undefined,
remote: string,
): boolean {
if (origin === undefined) return true;
if (isLoopbackOrigin(origin)) return true;
try {
return new URL(origin).origin === new URL(remote).origin;
} catch {
return false;
}
}
/** Whether `p` resolves to `folder` or somewhere below it. Both are taken
* relative to the current directory, as the dev server's paths are. */
export function isWithinFolder(folder: string, p: string): boolean {
const rel = path.relative(path.resolve(folder), path.resolve(p));
return !(rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel));
}
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/** Job ids are UUIDs; anything else must not reach a URL path. */
export function isJobId(id: unknown): id is string {
return typeof id === "string" && UUID_RE.test(id);
}
+4 -3
View File
@@ -33,7 +33,7 @@ import {
} from "./script_common.ts";
import { dbtGeneratedDirs, isUnderGeneratedDir, isBundledModuleFile, getModuleFolderSuffix, isModuleEntryPoint, scriptPathToRemotePath } from "./resource_folders.ts";
import { findCodebase, yamlOptions } from "../commands/sync/sync.ts";
import { generateHash, readInlinePathSync, getHeaders, readTextFile, readTextFileSync } from "./utils.ts";
import { generateHash, inlinePathWithin, readInlinePathSync, getHeaders, readTextFile, readTextFileSync } from "./utils.ts";
import { DBT_DESCRIPTOR_NAME, isMissingDbtDescriptor } from "./resource_folders.ts";
import { detectAuthGatewayChallenge } from "./http_guards.ts";
@@ -169,9 +169,10 @@ export async function filterWorkspaceDependenciesForScripts(
// Resolve !inline reference to actual content
if (content.startsWith("!inline ")) {
const filePath = folder + sep + content.replace("!inline ", "");
try {
content = await readTextFile(filePath);
content = await readTextFile(
inlinePathWithin(content.replace("!inline ", ""), folder),
);
} catch {
continue;
}
+7 -4
View File
@@ -143,8 +143,11 @@ export async function resolveBindPort(
}
/**
* The host string we bind to. Explicit IPv4 — `localhost` resolves to
* 127.0.0.1 first on every platform we care about, and binding both stacks
* relies on platform-specific IPV6_V6ONLY behaviour we don't want to debug.
* The host string `wmill dev` binds to unless `--host` says otherwise.
* Loopback only: the server reads and writes the checkout's files (and, in
* proxy mode, hands out the workspace token), so it must not be reachable from
* the network. Explicit IPv4 — `localhost` resolves to 127.0.0.1 first on
* every platform we care about, and binding both stacks relies on
* platform-specific IPV6_V6ONLY behaviour we don't want to debug.
*/
export const BIND_HOST = "0.0.0.0" as const;
export const BIND_HOST = "127.0.0.1" as const;
+45 -4
View File
@@ -4,9 +4,9 @@
import { colors } from "@cliffy/ansi/colors";
import * as log from "../core/log.ts";
import { sep as SEP } from "node:path";
import nodePath, { sep as SEP } from "node:path";
import crypto from "node:crypto";
import { readFileSync, writeFileSync } from "node:fs";
import { readFileSync, realpathSync, writeFileSync } from "node:fs";
import { readdir, readFile } from "node:fs/promises";
import { fetchVersion } from "../core/context.ts";
import { updateGlobalVersions } from "../commands/sync/global.ts";
@@ -176,9 +176,50 @@ export function readTextFileSync(path: string | URL): string {
return decodeBufferAsUtf8(readFileSync(path), path);
}
export function readInlinePathSync(path: string): string {
function isWithin(base: string, target: string): boolean {
const rel = nodePath.relative(base, target);
return (
rel !== "" &&
rel !== ".." &&
!rel.startsWith(".." + SEP) &&
!nodePath.isAbsolute(rel)
);
}
/**
* Resolve an `!inline` reference against `root` (the sync root by default) and
* refuse one that lands outside it, directly or through a symlink. References
* are tracked data a pull can write verbatim, so following one must never read
* a file the checkout does not hold.
*/
export function inlinePathWithin(ref: string, root: string = "."): string {
const base = nodePath.resolve(root);
const target = nodePath.resolve(base, ref.replaceAll("/", SEP));
let inside = isWithin(base, target);
if (inside) {
let realBase: string;
let realTarget: string;
try {
realBase = realpathSync(base);
realTarget = realpathSync(target);
} catch {
// Nothing to follow yet: the caller's read reports the missing file.
return target;
}
inside = isWithin(realBase, realTarget);
}
if (!inside) {
throw new Error(
`'!inline ${ref}' refers to a file outside ${base}; inline references must stay within it`,
);
}
return target;
}
export function readInlinePathSync(path: string, root: string = "."): string {
const target = inlinePathWithin(path, root);
try {
return readTextFileSync(path.replaceAll("/", SEP));
return readTextFileSync(target);
} catch (error) {
log.warn(`Error reading inline path: ${path}, ${error}`);
return "";
+13
View File
@@ -167,6 +167,19 @@ test(
expect(port).toBeGreaterThan(0);
stdoutReader.releaseLock();
// Only the dev page's origins may open the socket.
const foreignOpened = await new Promise<boolean>((resolve) => {
const foreign = new WebSocket(`ws://localhost:${port}`, {
headers: { Origin: "https://example.com" },
});
foreign.on("open", () => {
foreign.close();
resolve(true);
});
foreign.on("error", () => resolve(false));
});
expect(foreignOpened).toBe(false);
// Connect WebSocket
ws = new WebSocket(`ws://localhost:${port}`);
+67
View File
@@ -0,0 +1,67 @@
/**
* Which clients the local dev servers (`wmill dev`, `wmill app dev`) accept
* on their WebSocket, and which paths and job ids their messages may name.
*/
import { expect, test } from "bun:test";
import * as path from "node:path";
import {
bindsLocalhost,
isAllowedDevPageOrigin,
isAllowedHostHeader,
isJobId,
isWithinFolder,
} from "../src/utils/dev_server_access.ts";
test("the wmill dev socket accepts the dev page's origins only", () => {
const remote = "https://windmill.example.com/";
expect(isAllowedDevPageOrigin("https://windmill.example.com", remote)).toBe(true);
// The --proxy-port page and a locally run frontend are on this machine.
expect(isAllowedDevPageOrigin("http://localhost:3002", remote)).toBe(true);
expect(isAllowedDevPageOrigin("http://127.0.0.1:3000", remote)).toBe(true);
// Non-browser clients send no Origin.
expect(isAllowedDevPageOrigin(undefined, remote)).toBe(true);
expect(isAllowedDevPageOrigin("https://other.example", remote)).toBe(false);
expect(isAllowedDevPageOrigin("http://windmill.example.com", remote)).toBe(false);
expect(isAllowedDevPageOrigin("https://windmill.example.com.other.example", remote)).toBe(false);
expect(isAllowedDevPageOrigin("null", remote)).toBe(false);
});
test("a Host that DNS could re-point is refused on a loopback bind", () => {
expect(isAllowedHostHeader("localhost:3001", "127.0.0.1")).toBe(true);
expect(isAllowedHostHeader("127.0.0.1:3001", "127.0.0.1")).toBe(true);
expect(isAllowedHostHeader("[::1]:3001", "localhost")).toBe(true);
expect(isAllowedHostHeader("192.168.1.5:4000", "localhost")).toBe(true);
expect(isAllowedHostHeader("other.example:3001", "127.0.0.1")).toBe(false);
expect(isAllowedHostHeader(undefined, "127.0.0.1")).toBe(false);
// An explicit --host is a name the developer chose.
expect(isAllowedHostHeader("devbox:4000", "devbox")).toBe(true);
// A wildcard bind is reachable under any name the developer exposed.
expect(isAllowedHostHeader("devbox.lan:3001", "0.0.0.0")).toBe(true);
});
test("message paths stay inside the checkout", () => {
const base = path.resolve("/tmp/checkout");
expect(isWithinFolder(base, path.join(base, "f/foo.flow/a.ts"))).toBe(true);
expect(isWithinFolder(base, base)).toBe(true);
expect(isWithinFolder(base, path.join(base, "f/../../ops/deploy"))).toBe(false);
expect(isWithinFolder(base, "/home/someone/.bashrc")).toBe(false);
expect(isWithinFolder(base, "/tmp/checkout-other/a.ts")).toBe(false);
});
test("only a UUID is taken as a job id", () => {
expect(isJobId("0190c5e4-6b2a-7c3d-8e9f-0123456789ab")).toBe(true);
expect(isJobId("../../variables/list")).toBe(false);
expect(isJobId("0190c5e4-6b2a-7c3d-8e9f-0123456789ab/../x")).toBe(false);
expect(isJobId(undefined)).toBe(false);
});
test("wmill dev binds only addresses the dev page reaches on localhost", () => {
for (const h of ["127.0.0.1", "localhost", "::1", "0.0.0.0", "::"]) {
expect(bindsLocalhost(h)).toBe(true);
}
for (const h of ["127.0.0.2", "192.168.1.10", "example.com"]) {
expect(bindsLocalhost(h)).toBe(false);
}
});
+64
View File
@@ -0,0 +1,64 @@
import { afterAll, describe, expect, test } from "bun:test";
import {
mkdirSync,
mkdtempSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { inlinePathWithin, readInlinePathSync } from "../src/utils/utils.ts";
import { validateInlineResourcePointer } from "../src/commands/resource/resource.ts";
const scratch = mkdtempSync(join(tmpdir(), "wmill-inline-"));
const root = join(scratch, "repo");
const outside = join(scratch, "outside.txt");
mkdirSync(join(root, "f", "res"), { recursive: true });
writeFileSync(join(root, "f", "res", "conf.resource.file.ini"), "inside");
writeFileSync(outside, "outside");
symlinkSync(outside, join(root, "f", "res", "link.resource.file.ini"));
afterAll(() => rmSync(scratch, { recursive: true, force: true }));
describe("inline references", () => {
test("keeps inline references inside the sync directory", () => {
expect(readInlinePathSync("f/res/conf.resource.file.ini", root)).toBe(
"inside",
);
for (const ref of [
"../outside.txt",
"f/../../outside.txt",
outside,
"f/res/link.resource.file.ini",
]) {
expect(() => inlinePathWithin(ref, root)).toThrow(/outside/);
expect(() => readInlinePathSync(ref, root)).toThrow(/outside/);
}
});
test("a missing file inside the directory is left to the reader", () => {
expect(inlinePathWithin("f/res/missing.txt", root)).toBe(
join(root, "f", "res", "missing.txt"),
);
});
test("a synced resource reads only its own content file", () => {
validateInlineResourcePointer("f/res/conf.resource.file.ini", "f/res/conf");
validateInlineResourcePointer(
"f/res/conf.prod.resource.file.ini",
"f/res/conf",
"f/res/conf.prod.resource.yaml",
);
for (const ref of [
"f/res/other.resource.file.ini",
"f/res/conf.resource.file.",
"f/res/conf.resource.file.x/../../y",
"../.config/windmill/remotes.ndjson",
]) {
expect(() => validateInlineResourcePointer(ref, "f/res/conf")).toThrow(
/content file must live next to it/,
);
}
});
});
@@ -0,0 +1,30 @@
import { expect, test } from "bun:test";
import { join } from "node:path";
import { remoteKeyWithinFolder } from "../src/commands/sync/sync.ts";
const FILESET = join("f", "res", "data.fileset");
test("fileset keys and module names land inside their folder", () => {
expect(remoteKeyWithinFolder(FILESET, "q.sql")).toBe(join(FILESET, "q.sql"));
expect(remoteKeyWithinFolder(FILESET, "models/staging/a.sql")).toBe(
join(FILESET, "models", "staging", "a.sql"),
);
});
test("fileset keys that are not plain relative paths are refused", () => {
for (const key of [
"../cleanup.sh",
"a/../../b.sh",
"/etc/cron.d/x",
"C:/x.ts",
"a\\..\\..\\b.ts",
"a\0b",
"a//b",
"./a",
"",
]) {
expect(() => remoteKeyWithinFolder(FILESET, key)).toThrow(
/must be a relative path/,
);
}
});
+10
View File
@@ -5,6 +5,16 @@ Symbols, not line numbers, are cited: they drift less.
- **Credential precedence** (`windmill-api-auth/src/auth.rs` `extract_token`): `Authorization: Bearer`
→ `token` cookie → `?token=` query param. A URL with `?token=` is a credential on every route, but
an existing cookie silently wins over it.
- **The cookie counts only on requests from the instance's own origin**
(`windmill-api-auth/src/request_site.rs`). On a non-GET/HEAD/OPTIONS request `extract_token`
sets the cookie aside unless `Sec-Fetch-Site` is `same-origin` or `none`; without that header
(plain http, old Safari), `Origin`, then `Referer`, must name the request's `Host`,
`X-Forwarded-Host` or `BASE_URL` host (ports ignored); with none of the three the request is
not from a browser page and keeps the cookie. A set-aside request authenticates as if it had
no cookie: on its `?token=` if any, else anonymously on optional-auth routes, else 403. GETs
are not covered except by `CrossSiteGetGuard` (Hub script runs). `same-site` is foreign: the
`SameSite=Lax` cookie reaches every sibling subdomain. `SESSION_COOKIE_TRUSTED_ORIGINS`
(comma-separated hosts or origins, `*` for all) admits named sites for both checks.
- **`AUTH_CACHE`** caches a token's identity for 120 s. Deleting a token row purges it only for
some rows: the delete trigger (`notify_token_invalidation`, last replaced in
`migrations/20261106141303_mcp_oauth_token_delete_revokes_grant.up.sql`) notifies every
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@windmill-labs/components",
"version": "1.888.0",
"version": "1.889.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@windmill-labs/components",
"version": "1.888.0",
"version": "1.889.1",
"hasInstallScript": true,
"license": "AGPL-3.0",
"dependencies": {
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@windmill-labs/components",
"version": "1.888.0",
"version": "1.889.1",
"scripts": {
"dev": "vite dev",
"dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev",
@@ -15,8 +15,8 @@
"format:check": "prettier --ignore-path .gitignore --check --plugin-search-dir=. .",
"format": "prettier --ignore-path .gitignore --write --plugin-search-dir=. .",
"package": "svelte-package -o package && node scripts/package-system-prompts.js && node scripts/fix-svelte-module-imports.js",
"generate-backend-client": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --useOptions --enums javascript --format false",
"generate-backend-client-mac": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --useOptions --enums javascript",
"generate-backend-client": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --request ./scripts/openapi-ts-request.ts --useOptions --enums javascript --format false",
"generate-backend-client-mac": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --request ./scripts/openapi-ts-request.ts --useOptions --enums javascript",
"gen:display-catalog": "WM_GEN_DISPLAY_CATALOG=1 vitest run --project server src/lib/components/display/displayCatalogGen.test.ts",
"gen:mcp-session": "WM_GEN_MCP_SESSION=1 vitest run --project server src/lib/components/copilot/chat/global/mcpSessionGen.test.ts",
"pretest": "tsc --incremental -p tests/tsconfig.json",
+367
View File
@@ -0,0 +1,367 @@
// Custom request module for `openapi-ts --request`: the generated core/request.ts, except that
// getUrl encodes path parameters with encodePathParam (src/lib/apiPathParams.ts).
import { ApiError } from './ApiError'
import type { ApiRequestOptions } from './ApiRequestOptions'
import type { ApiResult } from './ApiResult'
import { CancelablePromise } from './CancelablePromise'
import type { OnCancel } from './CancelablePromise'
import type { OpenAPIConfig } from './OpenAPI'
import { encodePathParam } from '../../apiPathParams'
export const isString = (value: unknown): value is string => {
return typeof value === 'string'
}
export const isStringWithValue = (value: unknown): value is string => {
return isString(value) && value !== ''
}
export const isBlob = (value: any): value is Blob => {
return value instanceof Blob
}
export const isFormData = (value: unknown): value is FormData => {
return value instanceof FormData
}
export const base64 = (str: string): string => {
try {
return btoa(str)
} catch (err) {
// @ts-ignore
return Buffer.from(str).toString('base64')
}
}
export const getQueryString = (params: Record<string, unknown>): string => {
const qs: string[] = []
const append = (key: string, value: unknown) => {
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
}
const encodePair = (key: string, value: unknown) => {
if (value === undefined || value === null) {
return
}
if (value instanceof Date) {
append(key, value.toISOString())
} else if (Array.isArray(value)) {
value.forEach((v) => encodePair(key, v))
} else if (typeof value === 'object') {
Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v))
} else {
append(key, value)
}
}
Object.entries(params).forEach(([key, value]) => encodePair(key, value))
return qs.length ? `?${qs.join('&')}` : ''
}
const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {
const path = options.url
.replace('{api-version}', config.VERSION)
.replace(/{(.*?)}/g, (substring: string, group: string) => {
if (options.path?.hasOwnProperty(group)) {
const value = String(options.path[group])
return config.ENCODE_PATH ? config.ENCODE_PATH(value) : encodePathParam(group, value)
}
return substring
})
const url = config.BASE + path
return options.query ? url + getQueryString(options.query) : url
}
export const getFormData = (options: ApiRequestOptions): FormData | undefined => {
if (options.formData) {
const formData = new FormData()
const process = (key: string, value: unknown) => {
if (isString(value) || isBlob(value)) {
formData.append(key, value)
} else {
formData.append(key, JSON.stringify(value))
}
}
Object.entries(options.formData)
.filter(([, value]) => value !== undefined && value !== null)
.forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((v) => process(key, v))
} else {
process(key, value)
}
})
return formData
}
return undefined
}
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>
export const resolve = async <T>(
options: ApiRequestOptions,
resolver?: T | Resolver<T>
): Promise<T | undefined> => {
if (typeof resolver === 'function') {
return (resolver as Resolver<T>)(options)
}
return resolver
}
export const getHeaders = async (
config: OpenAPIConfig,
options: ApiRequestOptions
): Promise<Headers> => {
const [token, username, password, additionalHeaders] = await Promise.all([
resolve(options, config.TOKEN),
resolve(options, config.USERNAME),
resolve(options, config.PASSWORD),
resolve(options, config.HEADERS)
])
const headers = Object.entries({
Accept: 'application/json',
...additionalHeaders,
...options.headers
})
.filter(([, value]) => value !== undefined && value !== null)
.reduce(
(headers, [key, value]) => ({
...headers,
[key]: String(value)
}),
{} as Record<string, string>
)
if (isStringWithValue(token)) {
headers['Authorization'] = `Bearer ${token}`
}
if (isStringWithValue(username) && isStringWithValue(password)) {
const credentials = base64(`${username}:${password}`)
headers['Authorization'] = `Basic ${credentials}`
}
if (options.body !== undefined) {
if (options.mediaType) {
headers['Content-Type'] = options.mediaType
} else if (isBlob(options.body)) {
headers['Content-Type'] = options.body.type || 'application/octet-stream'
} else if (isString(options.body)) {
headers['Content-Type'] = 'text/plain'
} else if (!isFormData(options.body)) {
headers['Content-Type'] = 'application/json'
}
}
return new Headers(headers)
}
export const getRequestBody = (options: ApiRequestOptions): unknown => {
if (options.body !== undefined) {
if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) {
return JSON.stringify(options.body)
} else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) {
return options.body
} else {
return JSON.stringify(options.body)
}
}
return undefined
}
export const sendRequest = async (
config: OpenAPIConfig,
options: ApiRequestOptions,
url: string,
body: any,
formData: FormData | undefined,
headers: Headers,
onCancel: OnCancel
): Promise<Response> => {
const controller = new AbortController()
let request: RequestInit = {
headers,
body: body ?? formData,
method: options.method,
signal: controller.signal
}
if (config.WITH_CREDENTIALS) {
request.credentials = config.CREDENTIALS
}
for (const fn of config.interceptors.request._fns) {
request = await fn(request)
}
onCancel(() => controller.abort())
return await fetch(url, request)
}
export const getResponseHeader = (
response: Response,
responseHeader?: string
): string | undefined => {
if (responseHeader) {
const content = response.headers.get(responseHeader)
if (isString(content)) {
return content
}
}
return undefined
}
export const getResponseBody = async (response: Response): Promise<unknown> => {
if (response.status !== 204) {
try {
const contentType = response.headers.get('Content-Type')
if (contentType) {
const binaryTypes = [
'application/octet-stream',
'application/pdf',
'application/zip',
'audio/',
'image/',
'video/'
]
if (contentType.includes('application/json') || contentType.includes('+json')) {
return await response.json()
} else if (binaryTypes.some((type) => contentType.includes(type))) {
return await response.blob()
} else if (contentType.includes('multipart/form-data')) {
return await response.formData()
} else if (contentType.includes('text/')) {
return await response.text()
}
}
} catch (error) {
console.error(error)
}
}
return undefined
}
export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => {
const errors: Record<number, string> = {
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Payload Too Large',
414: 'URI Too Long',
415: 'Unsupported Media Type',
416: 'Range Not Satisfiable',
417: 'Expectation Failed',
418: 'Im a teapot',
421: 'Misdirected Request',
422: 'Unprocessable Content',
423: 'Locked',
424: 'Failed Dependency',
425: 'Too Early',
426: 'Upgrade Required',
428: 'Precondition Required',
429: 'Too Many Requests',
431: 'Request Header Fields Too Large',
451: 'Unavailable For Legal Reasons',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
506: 'Variant Also Negotiates',
507: 'Insufficient Storage',
508: 'Loop Detected',
510: 'Not Extended',
511: 'Network Authentication Required',
...options.errors
}
const error = errors[result.status]
if (error) {
throw new ApiError(options, result, error)
}
if (!result.ok) {
const errorStatus = result.status ?? 'unknown'
const errorStatusText = result.statusText ?? 'unknown'
const errorBody = (() => {
try {
return JSON.stringify(result.body, null, 2)
} catch (e) {
return undefined
}
})()
throw new ApiError(
options,
result,
`Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`
)
}
}
/**
* Request method
* @param config The OpenAPI configuration object
* @param options The request options from the service
* @returns CancelablePromise<T>
* @throws ApiError
*/
export const request = <T>(
config: OpenAPIConfig,
options: ApiRequestOptions
): CancelablePromise<T> => {
return new CancelablePromise(async (resolve, reject, onCancel) => {
try {
const url = getUrl(config, options)
const formData = getFormData(options)
const body = getRequestBody(options)
const headers = await getHeaders(config, options)
if (!onCancel.isCancelled) {
let response = await sendRequest(config, options, url, body, formData, headers, onCancel)
for (const fn of config.interceptors.response._fns) {
response = await fn(response)
}
const responseBody = await getResponseBody(response)
const responseHeader = getResponseHeader(response, options.responseHeader)
const result: ApiResult = {
url,
ok: response.ok,
status: response.status,
statusText: response.statusText,
body: responseHeader ?? responseBody
}
catchErrorCodes(options, result)
resolve(result.body)
}
} catch (error) {
reject(error)
}
})
}
+2 -2
View File
@@ -1,5 +1,5 @@
{
"baseUrl": "https://pub-06154ed168a24e73a86ab84db6bf15d8.r2.dev",
"version": "5ae35e6",
"sha256": "cdc948ce65b3ed0befbbfab7c816f2db63ae9207bbd85653d3484516c7ac3238"
"version": "f9da2f8",
"sha256": "fec1b1536fa0f97759314337d79b1f64bd0f5fb6d5e8aee3d5e2a2abb247ca8f"
}
+6
View File
@@ -159,6 +159,12 @@
var pub = /^\/public\/([^/]+)\/([^/]+)\/?$/.exec(path)
var custom = /^\/a\/(.+?)\/?$/.exec(path)
if (!pub && !custom && !/^\/public\//.test(path)) return
// fetch() resolves encoded dot segments and separators, which would take these
// URLs outside their route; such paths are left to the page, which refuses them.
if (/%2e|%2f|%5c|\\/i.test(path)) {
pub = null
custom = null
}
// Dark as PublicApp decides it, painted before any stylesheet so that a dark app
// does not load over a white page.
var dark = false
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest'
import { encodePathParam } from './apiPathParams'
describe('encodePathParam', () => {
it('keeps slashes in path-like values', () => {
expect(encodePathParam('path', 'u/admin/my script')).toBe('u/admin/my%20script')
expect(encodePathParam('path', 'f/folder/a.b_c-d')).toBe('f/folder/a.b_c-d')
})
it('keeps query and fragment characters inside the segment', () => {
expect(encodePathParam('path', 'u/a/b?x=1#y')).toBe('u/a/b%3Fx=1%23y')
})
it('refuses dot segments, plain or percent-encoded', () => {
for (const v of ['u/../../jobs', '..', 'a/./b', 'a/%2e%2e/b', 'a/.%2E/b']) {
expect(() => encodePathParam('path', v)).toThrow()
}
expect(encodePathParam('path', 'a/...')).toBe('a/...')
})
it('encodes a workspace as one segment', () => {
expect(encodePathParam('workspace', 'acme-1_x')).toBe('acme-1_x')
expect(encodePathParam('workspace', 'acme/jobs/run?x=1')).toBe('acme%2Fjobs%2Frun%3Fx%3D1')
expect(() => encodePathParam('workspace', '..')).toThrow()
})
it('encodes percent signs so they are not decoded twice', () => {
expect(encodePathParam('path', 'a/%2e%2e%2fb')).toBe('a/%252e%252e%252fb')
})
})
+41
View File
@@ -0,0 +1,41 @@
// Path parameters are filled into the API route template by the generated client
// (`scripts/openapi-ts-request.ts`). Each value must stay inside its own slot: the browser resolves
// `.`/`..` segments (also as `%2e`) and starts the query at `?` or the fragment at `#`, so an
// unchecked value would address a different route than the one the caller asked for.
/** Parameters whose values are single identifiers and never legitimately contain `/`. */
const SINGLE_SEGMENT_PARAMS = new Set([
'workspace',
'workspace_id',
'target_workspace_id',
'fork_workspace_id',
'client_name',
'client'
])
export class InvalidPathParamError extends Error {
constructor(name: string) {
super(`Invalid value for path parameter "${name}"`)
this.name = 'InvalidPathParamError'
}
}
function isDotSegment(segment: string): boolean {
return /^(\.|%2e){1,2}$/i.test(segment)
}
function encodeSegment(segment: string): string {
return encodeURI(segment).replace(/[?#]/g, (c) => encodeURIComponent(c))
}
/** Encodes one path parameter value. Slashes are kept for path-like values (`u/user/script`),
* but every segment is encoded and `.`/`..` segments are refused. */
export function encodePathParam(name: string, value: string): string {
if (SINGLE_SEGMENT_PARAMS.has(name)) {
if (isDotSegment(value)) throw new InvalidPathParamError(name)
return encodeURIComponent(value)
}
const segments = value.split('/')
if (segments.some(isDotSegment)) throw new InvalidPathParamError(name)
return segments.map(encodeSegment).join('/')
}
+12 -5
View File
@@ -3,6 +3,8 @@
import pLimit from 'p-limit'
import { workspaceStore } from '$lib/stores'
import { get } from 'svelte/store'
import { encodePathParam } from '$lib/apiPathParams'
import { confinedSubpath } from './confinedPath'
// Backend proxy fallback functions
const getBackendProxyUrl = () => {
@@ -10,7 +12,7 @@ const getBackendProxyUrl = () => {
if (!workspace) {
throw new Error('No workspace available')
}
return `/api/w/${workspace}/npm_proxy`
return `/api/w/${encodePathParam('workspace', workspace)}/npm_proxy`
}
const backendProxyApi = async <T>(endpoint: string, resLimit: ResLimit): Promise<T | Error> => {
@@ -153,11 +155,15 @@ export const getDTSFileForModuleWithVersion = (
version: string,
// file comes with a prefix /
file: string
) =>
fromPreferredSource<string>(
() => text(`https://cdn.jsdelivr.net/npm/${moduleName}@${version}${file}`),
) => {
const confinedFile = confinedSubpath(file)
if (confinedFile === undefined) {
return Promise.resolve(new Error(`File ${file} is outside of package ${moduleName}`))
}
return fromPreferredSource<string>(
() => text(`https://cdn.jsdelivr.net/npm/${moduleName}@${version}${confinedFile}`),
async () => {
const proxyUrl = `${getBackendProxyUrl()}/file/${encodeURIComponent(moduleName)}/${encodeURIComponent(version)}${file}`
const proxyUrl = `${getBackendProxyUrl()}/file/${encodeURIComponent(moduleName)}/${encodeURIComponent(version)}${confinedFile}`
const proxied = await text(proxyUrl, { credentials: 'include' })
// The callers in ata/index.ts log a fixed message and drop the value, so a cause
// left inside the returned `Error` is a cause nothing ever prints.
@@ -165,6 +171,7 @@ export const getDTSFileForModuleWithVersion = (
return proxied
}
)
}
/**
* Reading the body can fail as readily as connecting, and both have to surface as a value
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, it } from 'vitest'
import { confinedSubpath, localImportUrl } from './confinedPath'
const ROOT = 'http://localhost/api/scripts_u/tokened_raw/ws/tok'
describe('localImportUrl', () => {
it('resolves relative imports next to the script', () => {
expect(localImportUrl(ROOT, 'u/admin/main', './helper')).toBe(ROOT + '/u/admin/helper')
expect(localImportUrl(ROOT, 'u/admin/main', '../other/lib')).toBe(ROOT + '/u/other/lib')
expect(localImportUrl(ROOT, 'f/folder/main', '/f/shared/util')).toBe(ROOT + '/f/shared/util')
})
it('refuses imports that climb above the root', () => {
expect(localImportUrl(ROOT, 'u/admin/main', '/../../../w/x/jobs')).toBeUndefined()
expect(localImportUrl(ROOT, 'u/admin/main', '../../../../w/x')).toBeUndefined()
})
it('keeps query and fragment characters in the file name', () => {
expect(localImportUrl(ROOT, 'u/admin/main', '/u/a/b?x=1#')).toBe(ROOT + '/u/a/b%3Fx=1%23')
expect(localImportUrl(ROOT, 'u/admin/main', '/u/%2e%2e/%2e%2e')).toBe(
ROOT + '/u/%252e%252e/%252e%252e'
)
})
})
describe('confinedSubpath', () => {
it('normalizes package file paths', () => {
expect(confinedSubpath('/dist/index.d.ts')).toBe('/dist/index.d.ts')
expect(confinedSubpath('/dist/./a/../b.d.ts')).toBe('/dist/b.d.ts')
expect(confinedSubpath('/../../../file')).toBeUndefined()
expect(confinedSubpath('/a\\..\\b')).toBe('/a%5C..%5Cb')
})
})
+35
View File
@@ -0,0 +1,35 @@
/**
* Normalizes a `/`-rooted file path and encodes each segment, so the result appended to a URL
* prefix always names a file below that prefix: `.`/`..` are resolved here rather than by the
* browser's URL parser, and `?`, `#`, `\` and `%` (so no `%2e%2e`) cannot reach the URL
* unencoded. Returns `undefined` when the path climbs above its root.
*/
export function confinedSubpath(path: string): string | undefined {
const out: string[] = []
const segments = path.split('/')
// A leading `/` gives an empty first segment, which is the root itself.
if (segments[0] === '') segments.shift()
for (const segment of segments) {
if (segment === '.') continue
if (segment === '..') {
if (out.length === 0) return undefined
out.pop()
continue
}
out.push(encodeURI(segment).replace(/[?#]/g, (c) => encodeURIComponent(c)))
}
return '/' + out.join('/')
}
/** URL of a script's relative or absolute local import, below the tokened raw-script `root`. */
export function localImportUrl(
root: string,
scriptPath: string,
specifier: string
): string | undefined {
const path = specifier.startsWith('/')
? specifier
: '/' + scriptPath + (specifier.startsWith('../') ? '/../' : '/.') + specifier
const confined = confinedSubpath(path)
return confined === undefined ? undefined : root + confined
}
+3 -4
View File
@@ -1,4 +1,5 @@
import { isTypescriptRelativePath } from '$lib/relative_imports'
import { localImportUrl } from './confinedPath'
import {
getDTSFileForModuleWithVersion,
getFiletreeForModuleWithVersion,
@@ -131,10 +132,8 @@ export const setupTypeAcquisition = (config: ATABootstrapConfig) => {
if (depth == 0) {
const relativeDeps = depsToGet.filter((f) => isTypescriptRelativePath(f.raw))
relativeDeps.forEach(async (f) => {
let path = f.raw.startsWith('/')
? f.raw
: '/' + config.scriptPath + (f.raw.startsWith('../') ? '/../' : '/.') + f.raw
let url = config.root + path
let url = localImportUrl(config.root, config.scriptPath ?? '', f.raw)
if (url === undefined) return
let localPath = f.raw
if ((f.raw.startsWith('.') || f.raw.startsWith('/')) && !f.raw.endsWith('.ts')) {
url += '.ts'
+3 -2
View File
@@ -30,6 +30,7 @@
import { onDestroy, onMount, setContext, untrack } from 'svelte'
import DarkModeToggle from '$lib/components/sidebar/DarkModeToggle.svelte'
import { page } from '$app/state'
import { isFromWindowEmbedder } from '$lib/utils/embedderMessage'
import { getUserExt } from '$lib/user'
import FlowPreviewButtons from './flows/header/FlowPreviewButtons.svelte'
import FlowModuleSchemaMap from './flows/map/FlowModuleSchemaMap.svelte'
@@ -271,8 +272,8 @@
modeInitialized = true
}
const el = (event) => {
// sendUserToast(`Received message from parent ${event.data.type}`, true)
const el = (event: MessageEvent) => {
if (!isFromWindowEmbedder(event)) return
if (event.data.type == 'runTest') {
runTest()
event.preventDefault()
@@ -44,6 +44,12 @@
import Alert from './common/alert/Alert.svelte'
import AutoDataTable from './table/AutoDataTable.svelte'
import Markdown from 'svelte-exmarkdown'
import { markdownPlugins } from './markdownPlugins'
import {
approvalPageHref,
resumeRequestCredentials,
signedResumeUrl
} from '$lib/utils/approvalResultUrls'
import { markdownProse } from './markdownProse'
import Toggle from './Toggle.svelte'
import FileDownload from './common/fileDownload/FileDownload.svelte'
@@ -1162,27 +1168,45 @@
>
</Alert>
{/if}
{:else if !forceJson && resultKind === 'approval'}<div
class="flex flex-col gap-3 mt-2 mx-4"
>
<Button
variant="accent"
on:click={() =>
fetch(result['resume'], {
method: 'POST',
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json' }
})}
>
Resume</Button
>
<Button variant="default" destructive on:click={() => fetch(result['cancel'])}
>Cancel</Button
>
<div class="center-center"
><a rel="noreferrer" target="_blank" href={result['approvalPage']}>Approval Page</a
></div
>
{:else if !forceJson && resultKind === 'approval'}
{@const resumeUrl = signedResumeUrl(result['resume'], 'resume', window.location.href)}
{@const cancelUrl = signedResumeUrl(result['cancel'], 'cancel', window.location.href)}
{@const approvalHref = approvalPageHref(
result['approvalPage'],
window.location.href,
resumeUrl
)}
<div class="flex flex-col gap-3 mt-2 mx-4">
{#if resumeUrl && cancelUrl}
<Button
variant="accent"
on:click={() =>
fetch(resumeUrl, {
method: 'POST',
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json' },
credentials: resumeRequestCredentials(resumeUrl, window.location.href)
})}
>
Resume</Button
>
<Button
variant="default"
destructive
on:click={() =>
fetch(cancelUrl, {
credentials: resumeRequestCredentials(cancelUrl, window.location.href)
})}>Cancel</Button
>
{/if}
{#if approvalHref}
<div class="center-center"
><a rel="noreferrer" target="_blank" href={approvalHref}>Approval Page</a></div
>
{/if}
{#if !(resumeUrl && cancelUrl) && !approvalHref}
<span class="text-xs text-secondary">These are not Windmill approval links.</span>
{/if}
</div>
{:else if !forceJson && resultKind === 'materialized'}
{@const m = parseMaterializedResult(result)}
@@ -1419,7 +1443,7 @@
{/if}
{:else if !forceJson && resultKind === 'markdown'}
<div class={markdownProse.sm}>
<Markdown md={result?.md ?? result?.markdown} />
<Markdown md={result?.md ?? result?.markdown} plugins={markdownPlugins} />
</div>
{:else if largeObject || hasBigInt}
{#if result && typeof result === 'object' && 'file' in result}
@@ -112,6 +112,15 @@
let neverLoaded = $state(true)
// Inline helper code comes from the editor, whose content can be seeded from a link: running it
// as soon as the form mounts would execute code the viewer never chose to run. Wait for the
// dropdown to be opened before loading; deployed helpers keep loading eagerly.
let openedOnce = $state(false)
$effect(() => {
if (open) openedOnce = true
})
let canLoad = $derived(helperScript?.source !== 'inline' || open || openedOnce)
$effect(() => {
if (_items.value && value !== undefined && isSelect) {
if (isMultiple && Array.isArray(value) && Array.isArray(_items.value)) {
@@ -175,6 +184,7 @@
;[filterText, entrypoint, helperScript]
if (
resultJobLoader &&
canLoad &&
(open || neverLoaded || !deepEqual(filterArgs(lastArgs), filterArgs(nargs)))
) {
neverLoaded = false
@@ -193,6 +203,7 @@
bind:value
items={safeSelectItems(items || [])}
placeholder="Select items"
onOpen={() => (openedOnce = true)}
noItemsMsg={_items.status === 'loading' ? 'Loading...' : 'No items found'}
disabled={disabled || _items.status === 'loading'}
/>
+10 -5
View File
@@ -40,7 +40,11 @@
import Password from './Password.svelte'
import TextInput from './text_input/TextInput.svelte'
import { sameTopDomainOrigin } from '$lib/cookies'
import { isValidLogoutRedirect, toSameOriginRelativePath } from '$lib/logoutRedirect'
import {
isValidLogoutRedirect,
toRedirectTarget,
toSameOriginRelativePath
} from '$lib/logoutRedirect'
import InputError from './InputError.svelte'
import {
loginErrorDetail,
@@ -434,8 +438,9 @@
async function redirectUser() {
// Reduce same-origin full URLs to relative paths so deep links from
// e.g. /a/[...path] (which carry the full URL as rd) still navigate
// correctly instead of falling through to the cross-origin branch.
let resolvedRd = toSameOriginRelativePath(rd) ?? rd
// correctly instead of falling through to the cross-origin branch. A value that is
// not a valid target is dropped rather than handed to `goto`.
let resolvedRd = toRedirectTarget(rd) ?? undefined
if (resolvedRd?.startsWith('http')) {
if (isValidLogoutRedirect(resolvedRd)) {
window.location.href = resolvedRd
@@ -911,8 +916,8 @@
{#if enrollSetup && enrollOptional}
<h2 class="text-sm font-semibold text-emphasis">Set up two-factor authentication</h2>
<p class="text-xs text-secondary">
Protect {email} with a code from an authenticator app on top of its password. You can
also do this later from your user settings.
Protect {email} with a code from an authenticator app on top of its password. You can also
do this later from your user settings.
</p>
{:else if enrollSetup}
<h2 class="text-sm font-semibold text-emphasis">Set up two-factor authentication</h2>
@@ -10,6 +10,7 @@
* scoped embed token / opaque isolation.
*/
import { sendUserToast } from '$lib/toast'
import { encodePathParam } from '$lib/apiPathParams'
import PublicApp from '$lib/components/apps/editor/PublicApp.svelte'
import PublicAppFrame from '$lib/components/apps/editor/PublicAppFrame.svelte'
import PageHeaderContent from '$lib/components/PageHeaderContent.svelte'
@@ -124,9 +125,8 @@
headers['Authorization'] = `Bearer ${OpenAPI.TOKEN}`
}
const consent = opts?.sdkConsent ? '?sdk_consent=true' : ''
const res = await fetch(`${OpenAPI.BASE}/w/${workspace}/apps/embed_token/p/${path}${consent}`, {
headers
})
const url = `${OpenAPI.BASE}/w/${encodePathParam('workspace', workspace)}/apps/embed_token/p/${encodePathParam('path', path)}${consent}`
const res = await fetch(url, { headers })
if (!res.ok) {
// Minted for the deployed app under the caller's RLS: a 404 is "nothing deployed here" or
// "not visible to this member", the same reading as `getAppLiteByPath`'s 404 below.
@@ -14,8 +14,10 @@
* - Raw, sandboxed: rendered directly here as a **single** opaque bundle iframe
* (the author bundle is already isolated in its own opaque iframe); no opaque
* viewer / embed token needed.
* - Unsandboxed (default): the app runs same-origin with the viewer's full
* session, the pre-isolation behavior. Rendered directly here.
* - Unsandboxed: the app runs same-origin with the viewer's full session.
* Rendered directly here. Only for a member of the app's workspace viewing an
* app its publisher left unsandboxed; the embed-token response decides it, and
* anyone else gets one of the isolated renders above.
*
* No `PUBLIC_APP_DOMAIN` is required: the opaque origin is, for same-origin-policy
* purposes, as foreign to the main app as a different domain. The opaque viewer's
@@ -28,6 +30,7 @@
import { onDestroy, onMount, setContext, type Snippet } from 'svelte'
import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte'
import { goto } from '$app/navigation'
import { parseHttpUrl, toSameOriginRelativePath } from '$lib/navigationTarget'
import { WINDMILL_RESERVED_QUERY_PARAMS } from '$lib/utils/queryParams'
import { EMBED_NAV_CONTEXT_KEY, type EmbedNav } from '../types'
import { loadAppPreview } from './loadAppPreview'
@@ -316,10 +319,11 @@
let modeChangeRestarts = 0
const MAX_MODE_CHANGE_RESTARTS = 3
// WIN-2006: publisher opted this app into sandbox isolation (alpha). When false
// (the default) the app runs same-origin with the viewer's full session — the
// pre-isolation behavior.
let sandboxed = $state(false)
// Whether the server says this viewer gets the isolated render (the publisher
// opted in, or the viewer is not a member of the app's workspace). Read only from
// the embed-token response, and a response without it counts as isolated: the
// app's own policy must never decide this on the client.
let sandboxed = $state(true)
// WIN-2006 Variant A: raw apps render single-iframe. The author's bundle is
// already isolated in its own opaque iframe (served + CSP-sandboxed by the
@@ -371,7 +375,7 @@
try {
const resp = await fetchEmbedToken()
embedToken = resp.token ?? null
sandboxed = resp.sandbox ?? false
sandboxed = resp.sandbox !== false
isRaw = resp.raw_app ?? false
appPath = resp.app_path ?? undefined
workspaceId = resp.workspace_id ?? undefined
@@ -416,7 +420,7 @@
// response's mode would bypass new isolation or leave the viewer
// unauthenticated. Start over; bounded so redeploys can't bounce forever.
const modeChanged =
(resp.raw_app ?? false) !== wasRaw || (resp.sandbox ?? false) !== wasSandboxed
(resp.raw_app ?? false) !== wasRaw || (resp.sandbox !== false) !== wasSandboxed
if (modeChanged) {
if (modeChangeRestarts < MAX_MODE_CHANGE_RESTARTS) {
modeChangeRestarts++
@@ -428,7 +432,7 @@
status = 'notExists'
return false
}
sandboxed = resp.sandbox ?? false
sandboxed = resp.sandbox !== false
isRaw = resp.raw_app ?? false
appPath = resp.app_path ?? appPath
workspaceId = resp.workspace_id ?? workspaceId
@@ -568,12 +572,16 @@
// the app ran on it pre-sandbox. Same-origin paths use SPA navigation;
// full http(s) URLs do a real load (pre-sandbox apps could already do
// this via window.location, so it grants nothing new). Everything else —
// javascript:, data:, protocol-relative `//host` — is rejected.
// javascript:, data:, protocol-relative `//host`, and this instance's own
// `/api/` routes, which this page would reach as a same-origin request — is
// rejected.
const href = typeof e.data.href === 'string' ? e.data.href : ''
if (href.startsWith('/') && !href.startsWith('//')) {
goto(href)
if (href.startsWith('/')) {
const path = toSameOriginRelativePath(href)
if (path) goto(path)
} else if (/^https?:\/\//i.test(href)) {
window.location.href = href
const url = parseHttpUrl(href)
if (url) window.location.href = url.href
}
}
}
@@ -7,6 +7,7 @@ import { OpenAPI } from '$lib/gen/core/OpenAPI'
import type { AppWithLastVersion, User } from '$lib/gen/types.gen'
import type { UserExt } from '$lib/stores'
import { mapUserToUserExt } from '$lib/userExt'
import { encodePathParam } from '$lib/apiPathParams'
export type PublicAppValue = AppWithLastVersion & { value: any; workspace_id?: string }
@@ -57,7 +58,7 @@ export async function publicGet<T>(path: string): Promise<T> {
export async function getUserExtOrUndefined(workspace: string): Promise<UserExt | undefined> {
try {
return mapUserToUserExt(
await publicGet<User>(`/w/${encodeURI(workspace)}/users/whoami`),
await publicGet<User>(`/w/${encodePathParam('workspace', workspace)}/users/whoami`),
workspace
)
} catch {
@@ -130,8 +130,8 @@
/** The displayed image as PNG bytes, drawn through a canvas. */
function rasterize(): Promise<Blob> {
const canvas = document.createElement('canvas')
canvas.width = natural?.w ?? imgEl!.naturalWidth
canvas.height = natural?.h ?? imgEl!.naturalHeight
canvas.width = view.natural?.w ?? imgEl!.naturalWidth
canvas.height = view.natural?.h ?? imgEl!.naturalHeight
canvas.getContext('2d')!.drawImage(imgEl!, 0, 0, canvas.width, canvas.height)
return new Promise<Blob>((resolve, reject) =>
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('encoding failed'))), 'image/png')
@@ -18,7 +18,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
import Path from '$lib/components/Path.svelte'
import SimpleEditor from '$lib/components/SimpleEditor.svelte'
import Markdown from 'svelte-exmarkdown'
import { gfmPlugin } from 'svelte-exmarkdown/gfm'
import { markdownPlugins } from '$lib/components/markdownPlugins'
import { markdownProse } from '$lib/components/markdownProse'
import {
applySavedWorkspaceCopilotInfo,
@@ -893,7 +893,7 @@ its block on a detail page laid over the list, like a skill in the Skills sectio
<div class="{folderMode === 'view' ? 'block' : 'hidden'} {markdownProse.sm}">
<div class="border rounded-md p-3 overflow-auto space-y-2">
{#if folderContent.trim()}
<Markdown md={folderContent} plugins={[gfmPlugin()]} />
<Markdown md={folderContent} plugins={markdownPlugins} />
{:else}
<span class="text-xs text-hint">Empty.</span>
{/if}
@@ -7,6 +7,7 @@
import CodeDisplay from './script/CodeDisplay.svelte'
import LinkRenderer from './LinkRenderer.svelte'
import MarkdownImage from './MarkdownImage.svelte'
import { messageS3Object } from './messageS3Object'
import {
extractCandidatePaths,
remarkWindmillPaths,
@@ -88,15 +89,7 @@
// A flow step can return a file rather than text; the raw JSON would be
// unreadable, so hand it to the result viewer instead of the markdown renderer.
const s3Object = $derived.by(() => {
if (!message.content.startsWith('{')) return undefined
try {
const parsed = JSON.parse(message.content)
return parsed?.type === 'windmill_s3_object' && parsed?.s3 ? parsed : undefined
} catch {
return undefined
}
})
const s3Object = $derived(messageS3Object(message.content))
const candidatePaths = $derived(extractCandidatePaths(message.content))
const reasoningPlugins = [gfmPlugin(), { renderer: { a: LinkRenderer, img: MarkdownImage } }]
@@ -19,7 +19,7 @@ and the actions that create, edit, import and delete them.
import Path from '$lib/components/Path.svelte'
import SimpleEditor from '$lib/components/SimpleEditor.svelte'
import Markdown from 'svelte-exmarkdown'
import { gfmPlugin } from 'svelte-exmarkdown/gfm'
import { markdownPlugins } from '$lib/components/markdownPlugins'
import { markdownProse } from '$lib/components/markdownProse'
import { userStore } from '$lib/stores'
import { sendUserToast } from '$lib/toast'
@@ -1157,7 +1157,7 @@ What the assistant should do when this skill applies.
<p class="text-xs text-secondary">{parsed.description}</p>
{/if}
<div class="border rounded-md p-3 overflow-auto space-y-2 {markdownProse.sm}">
<Markdown md={parsed.instructions} plugins={[gfmPlugin()]} />
<Markdown md={parsed.instructions} plugins={markdownPlugins} />
</div>
</div>
<div class="{detailMode === 'edit' ? 'flex' : 'hidden'} flex-col gap-3">
@@ -1,5 +1,6 @@
import { WorkspaceService } from '$lib/gen'
import { randomUUID } from '$lib/utils/uuid'
import { uiBuilderFiles } from '$lib/components/raw_apps/utils'
export type RawAppBundle = {
js: string
@@ -91,7 +92,7 @@ export function bundleRawAppFiles({
postToBundler({
type: 'bundleRawApp',
requestId,
files,
files: uiBuilderFiles(files),
sharedUiFiles,
bundlerType
})
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { messageS3Object } from './messageS3Object'
describe('messageS3Object', () => {
it('reads the file of an s3 object answer', () => {
expect(messageS3Object('{"type":"windmill_s3_object","s3":"out/report.pdf"}')).toEqual({
s3: 'out/report.pdf'
})
expect(
messageS3Object('{"type":"windmill_s3_object","s3":"a.png","storage":"secondary"}')
).toEqual({ s3: 'a.png', storage: 'secondary' })
})
it('keeps only the file fields, whatever else the answer carries', () => {
const content = JSON.stringify({
type: 'windmill_s3_object',
s3: 'a.png',
resume: '/x',
cancel: '/y',
approvalPage: 'https://example.com',
wm_renderer: 'html',
html: '<b>hi</b>',
presigned: 'a=b'
})
expect(messageS3Object(content)).toEqual({ s3: 'a.png' })
})
it('leaves any other answer to the text renderer', () => {
expect(messageS3Object('hello')).toBeUndefined()
expect(messageS3Object('{not json')).toBeUndefined()
expect(messageS3Object('{"type":"other","s3":"a.png"}')).toBeUndefined()
expect(messageS3Object('{"type":"windmill_s3_object","s3":{"k":1}}')).toBeUndefined()
expect(messageS3Object('{"type":"windmill_s3_object","s3":""}')).toBeUndefined()
expect(messageS3Object('{"type":"windmill_s3_object","s3":"a.png","storage":3}')).toEqual({
s3: 'a.png'
})
})
})
@@ -0,0 +1,20 @@
/**
* The file a flow step's answer names, when the answer is an S3 object rather than text.
*
* Only `s3` and `storage` are kept: the result viewer picks its renderer from the keys it is
* handed (`approvalPage`, `wm_renderer`, an agent trace, ...), and a stored message must not
* choose how it is displayed.
*/
export function messageS3Object(content: string): { s3: string; storage?: string } | undefined {
if (!content.startsWith('{')) return undefined
let parsed: unknown
try {
parsed = JSON.parse(content)
} catch {
return undefined
}
if (!parsed || typeof parsed !== 'object') return undefined
const { type, s3, storage } = parsed as Record<string, unknown>
if (type !== 'windmill_s3_object' || typeof s3 !== 'string' || !s3) return undefined
return typeof storage === 'string' && storage ? { s3, storage } : { s3 }
}
@@ -32,6 +32,7 @@
import type { FlowEditorContext } from '../types'
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
import Toggle from '$lib/components/Toggle.svelte'
import { hasListedMcpTools, rememberListedMcpTools } from './mcpToolsConsent'
const operatingWorkspace = useOperatingWorkspace()
@@ -62,13 +63,28 @@
let resourcePath = $derived(tool.value.resource_path)
let error = $derived(tools.error?.body?.message || tools.error?.message)
let listedVersion = $state(0)
let mayList = $derived.by(() => {
listedVersion
return !!opWs && resourcePath?.length > 0 && hasListedMcpTools(opWs, resourcePath)
})
function allowListing(path: string | undefined) {
if (!opWs || !path) return
rememberListedMcpTools(opWs, path)
listedVersion += 1
}
$effect(() => {
resourcePath
opWs
refreshCount
const allowed = mayList
untrack(() => {
if (resourcePath?.length > 0) {
if (allowed) {
tools.refresh()
} else {
tools.clear()
}
})
})
@@ -90,6 +106,7 @@
async function handleOAuthConnected(resourcePath: string, resourceName: string) {
await resourcePicker?.refreshResources()
allowListing(resourcePath)
tool.value.resource_path = resourcePath
tool.summary = `MCP: ${resourceName}`
}
@@ -105,6 +122,7 @@
placeholder="Select an MCP resource"
bind:value={tool.value.resource_path}
workspace={opWs}
onValueChange={(path) => allowListing(path)}
/>
</Label>
</div>
@@ -146,7 +164,10 @@
<Button
size="xs"
color="light"
onClick={() => (refreshCount += 1)}
onClick={() => {
allowListing(resourcePath)
refreshCount += 1
}}
startIcon={{ icon: RefreshCw }}
disabled={tools.status === 'loading'}
>
@@ -0,0 +1,21 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
describe('mcpToolsConsent', () => {
beforeEach(() => {
localStorage.clear()
vi.resetModules()
})
it('lists automatically only for a resource listed at the user request, per workspace', async () => {
const { hasListedMcpTools, rememberListedMcpTools } = await import('./mcpToolsConsent')
expect(hasListedMcpTools('ws', 'u/other/mcp')).toBe(false)
rememberListedMcpTools('ws', 'f/team/mcp')
expect(hasListedMcpTools('ws', 'f/team/mcp')).toBe(true)
expect(hasListedMcpTools('other_ws', 'f/team/mcp')).toBe(false)
// Survives a reload, so reopening a saved step lists its tools again.
vi.resetModules()
const reloaded = await import('./mcpToolsConsent')
expect(reloaded.hasListedMcpTools('ws', 'f/team/mcp')).toBe(true)
})
})
@@ -0,0 +1,40 @@
/**
* MCP resources whose tools this browser has listed at the user's request.
*
* Listing tools connects to the URL the resource names and sends it the secrets the
* resource references, resolved as the viewer. A step's resource path can come from a
* flow the viewer did not write (a shared link's hash, a colleague's flow), so the tool
* panel lists automatically only for a resource the viewer picked or listed before.
*/
const STORAGE_KEY = 'mcpToolsListedResources'
const MAX_ENTRIES = 500
function key(workspace: string, path: string): string {
return `${workspace}:${path}`
}
function read(): string[] {
try {
const parsed = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '[]')
return Array.isArray(parsed) ? parsed.filter((e) => typeof e === 'string') : []
} catch {
return []
}
}
const sessionListed = new Set<string>()
export function hasListedMcpTools(workspace: string, path: string): boolean {
const k = key(workspace, path)
return sessionListed.has(k) || read().includes(k)
}
export function rememberListedMcpTools(workspace: string, path: string): void {
const k = key(workspace, path)
sessionListed.add(k)
try {
const entries = read().filter((e) => e !== k)
entries.push(k)
localStorage.setItem(STORAGE_KEY, JSON.stringify(entries.slice(-MAX_ENTRIES)))
} catch {}
}
@@ -36,7 +36,8 @@
rawAppStorageKey,
rawAppCtx,
readRawAppStorage,
applyRawAppStorageOp
applyRawAppStorageOp,
uiBuilderFiles
} from './utils'
import { runDomQueryOnHtml, type RawAppDomQuery, type RawAppDomRequester } from './rawAppDom'
import InlinePrompt from '../copilot/chat/InlinePrompt.svelte'
@@ -1078,9 +1079,7 @@ addEventListener('message', function (e) {
iframeFiles = { ...newFiles }
iframeFocusPending = undefined
buildTracker.start()
const files = Object.fromEntries(
Object.entries(newFiles).filter(([path, _]) => !path.endsWith('/'))
)
const files = uiBuilderFiles(newFiles)
target.postMessage(
{
type: 'setFiles',
@@ -1098,9 +1097,7 @@ addEventListener('message', function (e) {
const focus = iframeFocusPending === pathToSelect
iframeFocusPending = undefined
buildTracker.start()
const files = Object.fromEntries(
Object.entries(newFiles).filter(([path, _]) => !path.endsWith('/'))
)
const files = uiBuilderFiles(newFiles)
target.postMessage(
{
type: 'setFilesAndSelect',
@@ -10,6 +10,7 @@ import {
rawAppCtx,
rawAppPreviewModules,
stripRawAppDiffNoise,
uiBuilderFiles,
type Runnable
} from './utils'
@@ -290,3 +291,20 @@ describe('canonicalRawAppDiffValue', () => {
expect(b.summary).toBe('app EDITED')
})
})
describe('uiBuilderFiles', () => {
it('keeps app sources and drops directory entries and node_modules files', () => {
expect(
uiBuilderFiles({
'/index.tsx': 'a',
'/src/node_modules_helper.ts': 'b',
'/src/': '',
'/node_modules/tailwindcss/dist/lib.mjs': 'x',
'node_modules/pkg/index.js': 'x',
'./node_modules/pkg/index.js': 'x',
'/src/vendor/node_modules/pkg/index.js': 'x',
'\\node_modules\\pkg\\index.js': 'x'
})
).toEqual({ '/index.tsx': 'a', '/src/node_modules_helper.ts': 'b' })
})
})
@@ -448,6 +448,25 @@ function hiddenRunnableToTsType(runnable: Runnable) {
}
}
function isNodeModulesPath(path: string): boolean {
return path
.replace(/^(\.?\/)+/, '')
.split(/[/\\]/)
.includes('node_modules')
}
/**
* The app's stored files as the UI Builder bundler is given them. Its packages come from its
* own install into `node_modules/`, so a stored file under any `node_modules` segment would
* be imported in place of the installed package: such keys, like directory entries, are not
* app sources and stay out.
*/
export function uiBuilderFiles(files: Record<string, string>): Record<string, string> {
return Object.fromEntries(
Object.entries(files).filter(([path]) => !path.endsWith('/') && !isNodeModulesPath(path))
)
}
/** Shown in the file tree, generated by `genWmillTs` — never a key of `files`. */
export const WMILL_TS_PATH = '/wmill.ts'
@@ -4,7 +4,7 @@
* payload and renders it. Each rejection below is a way a caller-supplied recording
* could otherwise reach the DOM or the render loop unbounded.
*/
import { describe, expect, it } from 'vitest'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
MAX_COMPONENT_FANOUT,
MAX_FLOW_MODULES,
@@ -18,6 +18,7 @@ import {
MAX_VALUE_NODES,
MAX_RECORDING_NODES,
MAX_VALUE_STRING_CHARS,
fetchRecording,
isAppRecording,
parseRecording
} from './rawAppRecordingLoad'
@@ -546,3 +547,14 @@ describe('parseRecording', () => {
expect(kindOf(pipeline(sample(10, 20)))).toBe('pipeline')
})
})
describe('fetchRecording', () => {
afterEach(() => vi.unstubAllGlobals())
it("never sends the visitor's cookies to the URL the link names", async () => {
const fetchMock = vi.fn(async () => new Response(JSON.stringify(valid())))
vi.stubGlobal('fetch', fetchMock)
await expect(fetchRecording('/api/w/demo/some/path')).resolves.toEqual(valid())
expect(fetchMock).toHaveBeenCalledWith('/api/w/demo/some/path', { credentials: 'omit' })
})
})
@@ -609,7 +609,9 @@ export async function fetchRecording(
url: string,
onProgress?: (loaded: number, total: number) => void
): Promise<unknown> {
const res = await fetch(url)
// `url` comes from the page's `?src=`, so anyone who can send a link picks it.
// Fetched with the visitor's cookies, a same-origin API URL would run as them.
const res = await fetch(url, { credentials: 'omit' })
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`)
const total = Number(res.headers.get('content-length')) || 0
if (total > MAX_RECORDING_BYTES) throw new Error(`Recording is too large (${total} bytes)`)
@@ -1,16 +1,13 @@
<script lang="ts">
let { text } = $props()
// Function to convert text with URLs to HTML
function linkifyText(text) {
// Regex to match URLs starting with http/https and ending with )
const urlRegex = /\(((https?:\/\/[^\s)]+))\)/g
import { splitLinks } from './linkify'
// Replace matched patterns with anchor tags
return text.replace(urlRegex, '(<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>)')
}
let { text }: { text: string | undefined | null } = $props()
let processedText = $derived(linkifyText(text))
let parts = $derived(splitLinks(text))
</script>
<!-- Use @html to render the HTML -->
{@html processedText}
{#each parts as part, i (i)}{#if part.kind === 'link'}<a
href={part.href}
target="_blank"
rel="noopener noreferrer">{part.href}</a
>{:else}{part.value}{/if}{/each}
@@ -0,0 +1,28 @@
import { describe, expect, it } from 'vitest'
import { splitLinks } from './linkify'
describe('splitLinks', () => {
it('links parenthesised http urls and keeps the rest as text', () => {
expect(splitLinks('see (https://example.com/a?b=1) now')).toEqual([
{ kind: 'text', value: 'see (' },
{ kind: 'link', href: 'https://example.com/a?b=1' },
{ kind: 'text', value: ') now' }
])
})
it('keeps markup in the message as plain text', () => {
const text = 'script not found at name u/a/<img src=x onerror=alert(1)>'
expect(splitLinks(text)).toEqual([{ kind: 'text', value: text }])
})
it('does not link other schemes', () => {
expect(splitLinks('(javascript:alert(1))')).toEqual([
{ kind: 'text', value: '(javascript:alert(1))' }
])
})
it('handles empty input', () => {
expect(splitLinks(undefined)).toEqual([])
expect(splitLinks('')).toEqual([])
})
})
@@ -0,0 +1,29 @@
export type LinkifyPart = { kind: 'text'; value: string } | { kind: 'link'; href: string }
// Only URLs wrapped in parentheses are turned into links, matching how alert messages quote them.
const URL_IN_PARENS = /\((https?:\/\/[^\s)]+)\)/g
export function splitLinks(text: string | undefined | null): LinkifyPart[] {
const source = text ?? ''
const parts: LinkifyPart[] = []
let last = 0
for (const match of source.matchAll(URL_IN_PARENS)) {
const href = match[1]
const start = match.index! + 1
if (!isHttpUrl(href)) continue
if (start > last) parts.push({ kind: 'text', value: source.slice(last, start) })
parts.push({ kind: 'link', href })
last = start + href.length
}
if (last < source.length) parts.push({ kind: 'text', value: source.slice(last) })
return parts
}
function isHttpUrl(value: string): boolean {
try {
const url = new URL(value)
return url.protocol === 'http:' || url.protocol === 'https:'
} catch {
return false
}
}
@@ -5,13 +5,14 @@
import { workspaceStore } from '$lib/stores'
import { goto } from '$app/navigation'
import { page } from '$app/state'
import { toSameOriginRelativePath } from '$lib/logoutRedirect'
interface Props {
isFork?: boolean
}
let { isFork = false }: Props = $props()
const rd = page.url.searchParams.get('rd')
const rd = toSameOriginRelativePath(page.url.searchParams.get('rd'))
</script>
<CenteredModal title="{isFork ? 'Forking' : 'New'} Workspace" centerVertically={false}>
+124 -1
View File
@@ -1,5 +1,13 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { isValidLogoutRedirect, parseHttpUrl, toSameOriginRelativePath } from './logoutRedirect'
import {
isBackendApiPath,
isValidLogoutRedirect,
parseHttpUrl,
toRedirectTarget,
toSameOriginRelativePath
} from './logoutRedirect'
import { hubBaseUrlStore } from './stores'
import { DEFAULT_HUB_BASE_URL } from './hub'
describe('parseHttpUrl', () => {
it('accepts http and https URLs', () => {
@@ -14,6 +22,18 @@ describe('parseHttpUrl', () => {
expect(parseHttpUrl('/relative')).toBeUndefined()
expect(parseHttpUrl(null)).toBeUndefined()
})
it('rejects routes of the backend serving this page', () => {
vi.stubGlobal('window', { location: { origin: 'http://localhost:3000' } })
try {
expect(parseHttpUrl('http://localhost:3000/api/w/ws/x')).toBeUndefined()
expect(parseHttpUrl('http://localhost:3000/%61pi/w/ws/x')).toBeUndefined()
expect(parseHttpUrl('http://localhost:3000/runs')?.pathname).toBe('/runs')
expect(parseHttpUrl('https://example.com/api/cb')?.pathname).toBe('/api/cb')
} finally {
vi.unstubAllGlobals()
}
})
})
describe('isValidLogoutRedirect', () => {
@@ -38,6 +58,41 @@ describe('isValidLogoutRedirect', () => {
expect(isValidLogoutRedirect('https://app.windmill.dev/foo')).toBe(true)
})
it('rejects non-web schemes whatever host they name', () => {
vi.stubGlobal('window', { location: { origin: 'https://app.windmill.dev' } })
const targets = [
'javascript://windmill.dev/%0aalert(1)',
'javascript://app.windmill.dev/%0aalert(1)',
'javascript://hub.windmill.dev/%0aalert(1)',
'JAVASCRIPT://windmill.dev/%0aalert(1)',
'JavaScript://app.windmill.dev/%0aalert(1)',
' javascript://windmill.dev/%0aalert(1)',
'java\tscript://windmill.dev/%0aalert(1)',
'data:text/html,<script>alert(1)</script>',
'data://windmill.dev/x',
'vbscript://windmill.dev/x',
'blob:https://app.windmill.dev/x',
'file://windmill.dev/etc/passwd'
]
for (const t of targets) {
expect(isValidLogoutRedirect(t), t).toBe(false)
expect(toRedirectTarget(t), t).toBeNull()
}
expect(isValidLogoutRedirect('https://app.windmill.dev/runs')).toBe(true)
})
it('rejects non-web schemes naming a custom hub host', () => {
hubBaseUrlStore.set('https://hub.example.com')
try {
expect(isValidLogoutRedirect('https://hub.example.com/scripts')).toBe(true)
expect(isValidLogoutRedirect('javascript://hub.example.com/%0aalert(1)')).toBe(false)
expect(isValidLogoutRedirect('JAVASCRIPT://hub.example.com/%0aalert(1)')).toBe(false)
expect(isValidLogoutRedirect('data://hub.example.com/x')).toBe(false)
} finally {
hubBaseUrlStore.set(DEFAULT_HUB_BASE_URL)
}
})
it('rejects cross-origin and protocol-relative', () => {
expect(isValidLogoutRedirect('https://evil.com/')).toBe(false)
expect(isValidLogoutRedirect('//evil.com')).toBe(false)
@@ -56,6 +111,16 @@ describe('toSameOriginRelativePath', () => {
vi.unstubAllGlobals()
})
it('keeps a same-origin URL with a doubled leading slash on this origin', () => {
expect(toSameOriginRelativePath('http://localhost:3000//evil.example/x')).toBe(
'/evil.example/x'
)
expect(toSameOriginRelativePath('http://localhost:3000/a/..//evil.example')).toBe(
'/evil.example'
)
expect(toRedirectTarget('http://localhost:3000//evil.example')).toBe('/evil.example')
})
it('returns same-origin relative paths as-is', () => {
expect(toSameOriginRelativePath('/a/nucleus/chat')).toBe('/a/nucleus/chat')
expect(toSameOriginRelativePath('/runs?workspace=foo')).toBe('/runs?workspace=foo')
@@ -111,3 +176,61 @@ describe('toSameOriginRelativePath', () => {
expect(toSameOriginRelativePath('http://localhost:3000/')).toBe('/')
})
})
describe('backend routes as redirect targets', () => {
beforeEach(() => {
vi.stubGlobal('window', { location: { origin: 'http://localhost:3000' } })
})
afterEach(() => {
vi.unstubAllGlobals()
})
const backendPaths = [
'/api/w/ws/jobs/run_wait_result/p/hub/1/x?a=1',
'/api',
'/api?x=1',
'/API/w/ws/x',
'/%61pi/w/ws/x',
'/%2561pi/w/ws/x',
'/./api/w/ws/x',
'/%2e/api/w/ws/x',
'/foo/../api/w/ws/x',
'/foo/%2e%2e/api/w/ws/x',
'/.//api/w/ws/x',
'/api%2fw/ws/x',
'api/w/ws/x',
'http://localhost:3000/api/w/ws/x',
'http://localhost:3000/%61pi/w/ws/x'
]
it('isBackendApiPath matches api routes only', () => {
expect(isBackendApiPath('/api/w/x')).toBe(true)
expect(isBackendApiPath('/%61pi/x')).toBe(true)
expect(isBackendApiPath('/apis')).toBe(false)
expect(isBackendApiPath('/apps/get/u/admin/x')).toBe(false)
expect(isBackendApiPath('/x/api/y')).toBe(false)
expect(isBackendApiPath('/')).toBe(false)
})
it('toSameOriginRelativePath refuses them', () => {
for (const p of backendPaths) expect(toSameOriginRelativePath(p), p).toBeNull()
})
it('isValidLogoutRedirect refuses them, on any accepted host', () => {
for (const p of backendPaths) expect(isValidLogoutRedirect(p), p).toBe(false)
expect(isValidLogoutRedirect('https://app.windmill.dev/api/w/ws/x')).toBe(false)
expect(isValidLogoutRedirect('/\\evil.com')).toBe(false)
})
it('toRedirectTarget refuses them and keeps app targets', () => {
for (const p of backendPaths) expect(toRedirectTarget(p), p).toBeNull()
expect(toRedirectTarget('/runs?workspace=foo')).toBe('/runs?workspace=foo')
expect(toRedirectTarget('http://localhost:3000/apps/get/x')).toBe('/apps/get/x')
expect(toRedirectTarget('https://app.windmill.dev/foo')).toBe('https://app.windmill.dev/foo')
expect(toRedirectTarget('https://evil.com/foo')).toBeNull()
expect(toRedirectTarget('//evil.com')).toBeNull()
expect(toRedirectTarget('javascript:alert(1)')).toBeNull()
expect(toRedirectTarget(null)).toBeNull()
})
})
+21 -50
View File
@@ -1,12 +1,23 @@
import { get } from 'svelte/store'
import { hubBaseUrlStore } from './stores'
import { hasControlChar, isBackendApiPath, toSameOriginRelativePath } from './navigationTarget'
export {
isBackendApiPath,
isSameOriginBackendUrl,
parseHttpUrl,
toSameOriginRelativePath
} from './navigationTarget'
export function isValidLogoutRedirect(url: string): boolean {
if (url.startsWith('/') && !url.startsWith('//')) {
return true
return toSameOriginRelativePath(url) !== null
}
try {
const parsed = new URL(url)
// Before any host check: `javascript://windmill.dev/%0a…` has hostname `windmill.dev`.
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false
if (isBackendApiPath(parsed.pathname)) return false
// Same-origin absolute URLs are always safe: the user can only be sent
// back to the site they're already on, which is never an open redirect.
// Mirrors toSameOriginRelativePath()'s same-origin handling, and lets a
@@ -30,55 +41,15 @@ export function isValidLogoutRedirect(url: string): boolean {
}
/**
* Reduces a redirect target to a safe same-origin relative path.
*
* Returns the path (`/foo?bar#baz`) when the input is either:
* - already an absolute-but-relative path (`/foo`) that isn't protocol-relative
* (`//evil.com`) or a back-slash trick (`/\\evil.com`), or
* - a full URL whose origin matches the current page's origin.
*
* Returns `null` for anything else (cross-origin URLs, protocol-relative paths,
* malformed input). Used to sanitize values flowing into `RelayState`,
* `localStorage.rd`, and post-login redirects so we don't either lose a valid
* same-origin deep link or open-redirect into a foreign origin.
* Reduces a post-login `rd` to a target the app may navigate to: a same-origin relative path
* (as {@link toSameOriginRelativePath}), or an absolute http(s) URL {@link isValidLogoutRedirect}
* accepts, kept as is for `window.location`. Anything else is `null`, never the raw value:
* a refused relative path handed on to `goto` would still be navigated to.
*/
export function toSameOriginRelativePath(rd: string | null | undefined): string | null {
if (!rd) return null
if (rd.length > 2048) return null
if (hasControlChar(rd)) return null
if (rd.startsWith('/')) {
if (rd.startsWith('//') || rd.startsWith('/\\')) return null
return rd
}
if (typeof window === 'undefined') return null
try {
const url = new URL(rd, window.location.origin)
if (url.origin !== window.location.origin) return null
const path = url.pathname + url.search + url.hash
return path || '/'
} catch {
export function toRedirectTarget(rd: string | null | undefined): string | null {
const relative = toSameOriginRelativePath(rd)
if (relative) return relative
if (!rd || !(rd.startsWith('http://') || rd.startsWith('https://')) || hasControlChar(rd))
return null
}
}
/**
* Parses a navigation target taken from the page URL, accepting only `http:` and `https:`.
* A target from page input must go through this before it is assigned to `window.location`.
*/
export function parseHttpUrl(raw: string | null | undefined): URL | undefined {
if (!raw) return undefined
try {
const url = new URL(raw)
return url.protocol === 'http:' || url.protocol === 'https:' ? url : undefined
} catch {
return undefined
}
}
function hasControlChar(s: string): boolean {
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i)
if (c < 0x20 || c === 0x7f) return true
}
return false
return isValidLogoutRedirect(rd) ? rd : null
}
+20
View File
@@ -0,0 +1,20 @@
import { describe, it, expect, vi } from 'vitest'
vi.mock('$lib/gen', () => ({ SettingService: {}, WorkspaceService: {} }))
import { parseScopeParam } from './mcpAuth'
describe('parseScopeParam', () => {
it('splits on spaces as the server does', () => {
expect(parseScopeParam(' mcp:scripts:f/x/* mcp:runnables_as_tools ')).toEqual([
'mcp:scripts:f/x/*',
'mcp:runnables_as_tools'
])
})
it('refuses separators the server does not split on', () => {
for (const sep of ['\u0085', '\t', '\n', ' ', '
']) {
expect(parseScopeParam(`mcp:scripts:f/x/*${sep}mcp:all`)).toBeUndefined()
}
})
})
+10
View File
@@ -1,5 +1,15 @@
import { SettingService, WorkspaceService } from '$lib/gen'
/**
* The scope tokens of an OAuth `scope` parameter, split on spaces as the server splits them, or
* undefined when it holds anything but printable ASCII: the server refuses those, and a separator
* only one side honours (U+0085, a tab) would let the page show other scopes than the grant's.
*/
export function parseScopeParam(scope: string): string[] | undefined {
if (!/^[\x20-\x7e]*$/.test(scope)) return undefined
return scope.split(' ').filter((s) => s.length > 0)
}
/** Every live workspace of the instance, for a superadmin granting an MCP token their rights. */
export async function listEveryWorkspace(): Promise<{ id: string; name: string }[]> {
const all: { id: string; name: string; deleted?: boolean }[] = []
+109
View File
@@ -0,0 +1,109 @@
// Store-free on purpose: the opaque public-app viewer imports this, and its bundle must not
// statically pull in `$lib/stores` or the generated client (see publicAppApi.ts).
/**
* Whether a URL path addresses the backend (`/api/...`) rather than a page of the app.
*
* A navigation the app starts itself reaches the backend as same-origin, which is what its
* cross-site GET checks trust, so a redirect target taken from a link must never be one. The
* path is decoded and re-normalized until stable, so `/%61pi`, `/./api`, `//api` and `/API`
* are caught whichever way the server ends up reading them.
*/
export function isBackendApiPath(pathname: string): boolean {
let p = pathname
for (let i = 0; i < 8; i++) {
let decoded: string
try {
decoded = decodeURIComponent(p)
} catch {
return true
}
const collapsed = decoded.replace(/[\\/]+/g, '/')
let next: string
try {
next = new URL(collapsed.startsWith('/') ? collapsed : '/' + collapsed, 'http://n').pathname
} catch {
return true
}
next = next.toLowerCase()
if (next === p) break
p = next
}
return p === '/api' || p.startsWith('/api/')
}
/** Whether `url` is a backend route of the instance this page is served from. */
export function isSameOriginBackendUrl(url: URL): boolean {
return (
typeof window !== 'undefined' &&
url.origin === window.location?.origin &&
isBackendApiPath(url.pathname)
)
}
/**
* Reduces a redirect target to a safe same-origin relative path.
*
* Returns the path (`/foo?bar#baz`) when the input is either:
* - already an absolute-but-relative path (`/foo`) that isn't protocol-relative
* (`//evil.com`) or a back-slash trick (`/\\evil.com`), or
* - a full URL whose origin matches the current page's origin,
* and the path is not a backend route ({@link isBackendApiPath}).
*
* Returns `null` for anything else (cross-origin URLs, protocol-relative paths,
* malformed input). Used to sanitize values flowing into `RelayState`,
* `localStorage.rd`, and post-login redirects so we don't either lose a valid
* same-origin deep link or open-redirect into a foreign origin.
*/
export function toSameOriginRelativePath(rd: string | null | undefined): string | null {
if (!rd) return null
if (rd.length > 2048) return null
if (hasControlChar(rd)) return null
if (rd.startsWith('/')) {
if (rd.startsWith('//') || rd.startsWith('/\\')) return null
try {
if (isBackendApiPath(new URL(rd, 'http://n').pathname)) return null
} catch {
return null
}
return rd
}
if (typeof window === 'undefined') return null
try {
const url = new URL(rd, window.location.origin)
// A `blob:` URL takes the origin of the URL it wraps, which its pathname then holds.
if (url.protocol !== 'http:' && url.protocol !== 'https:') return null
if (url.origin !== window.location.origin) return null
if (isBackendApiPath(url.pathname)) return null
// `https://<this host>//evil.example` has the pathname `//evil.example`, which on its own
// is a protocol-relative URL to another host.
const pathname = url.pathname.replace(/^[/\\]+/, '/')
return pathname + url.search + url.hash
} catch {
return null
}
}
/**
* Parses a navigation target taken from the page URL, accepting only `http:` and `https:`.
* A target from page input must go through this before it is assigned to `window.location`.
* A backend route of this instance is refused too (see {@link isBackendApiPath}).
*/
export function parseHttpUrl(raw: string | null | undefined): URL | undefined {
if (!raw) return undefined
try {
const url = new URL(raw)
if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined
return isSameOriginBackendUrl(url) ? undefined : url
} catch {
return undefined
}
}
export function hasControlChar(s: string): boolean {
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i)
if (c < 0x20 || c === 0x7f) return true
}
return false
}
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest'
import { approvalPageHref, resumeRequestCredentials, signedResumeUrl } from './approvalResultUrls'
const base = 'https://wm.example.com/run/abc?workspace=demo'
const job = '01a2230e-229e-7897-1356-31f6444b03e6'
const sig = 'ab'.repeat(32)
const resume = `https://wm.example.com/api/w/demo/jobs_u/resume/${job}/0/${sig}`
const cancel = `https://wm.example.com/api/w/demo/jobs_u/cancel/${job}/0/${sig}`
const otherResume = `https://wm-internal.example.net/api/w/demo/jobs_u/resume/${job}/0/${sig}`
describe('signedResumeUrl', () => {
it('accepts the signed urls the instance generates, on any origin', () => {
expect(signedResumeUrl(resume, 'resume', base)).toBe(resume)
expect(signedResumeUrl(cancel, 'cancel', base)).toBe(cancel)
expect(signedResumeUrl(otherResume, 'resume', base)).toBe(otherResume)
expect(signedResumeUrl(`${resume}?approver=bob%40x.com`, 'resume', base)).toBe(
`${resume}?approver=bob%40x.com`
)
expect(signedResumeUrl(`/api/w/demo/jobs_u/resume/${job}/3/${sig}`, 'resume', base)).toBe(
`https://wm.example.com/api/w/demo/jobs_u/resume/${job}/3/${sig}`
)
})
it('refuses any other url', () => {
for (const value of [
undefined,
'',
42,
cancel, // wrong operation for the button
`/api/w/demo/jobs_u/flow/resume_suspended/${job}`,
'/api/w/demo/workspaces/archive',
`/api/w/demo/jobs_u/resume/${job}/0/${sig}/../../../../workspaces/archive`,
`/api/w/demo/jobs_u/resume/${job}/0/${sig}?x=1`,
`/api/w/demo/jobs_u/resume/${job}/0/${sig}#x`,
`/api/w/demo/jobs_u/resume/${job}/0/nothex`,
`/api/w/demo/jobs_u/resume/not-a-uuid/0/${sig}`,
`ftp://wm.example.com/api/w/demo/jobs_u/resume/${job}/0/${sig}`,
`javascript:fetch('/api/w/demo/jobs_u/resume/${job}/0/${sig}')`
]) {
expect(signedResumeUrl(value, 'resume', base)).toBeUndefined()
}
})
})
describe('resumeRequestCredentials', () => {
it('sends the session only to this instance', () => {
expect(resumeRequestCredentials(resume, base)).toBe('same-origin')
expect(resumeRequestCredentials(otherResume, base)).toBe('omit')
})
})
describe('approvalPageHref', () => {
it('keeps a link to this instance or to the resume url instance', () => {
const page = `https://wm.example.com/approve/demo/${job}?token=t`
expect(approvalPageHref(page, base, undefined)).toBe(page)
expect(approvalPageHref(`/approve/demo/${job}`, base, undefined)).toBe(
`https://wm.example.com/approve/demo/${job}`
)
const internal = `https://wm-internal.example.net/approve/demo/${job}?token=t`
expect(approvalPageHref(internal, base, otherResume)).toBe(internal)
})
it('drops a link elsewhere or with another scheme', () => {
expect(approvalPageHref('javascript:alert(1)', base, resume)).toBeUndefined()
expect(approvalPageHref('data:text/html,hi', base, resume)).toBeUndefined()
expect(approvalPageHref('https://other.example.com/approve', base, resume)).toBeUndefined()
expect(approvalPageHref('//other.example.com/approve', base, undefined)).toBeUndefined()
expect(approvalPageHref(undefined, base, resume)).toBeUndefined()
})
})
@@ -0,0 +1,62 @@
import { safeHref } from './safeHref'
const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
// The shape `build_resume_url` (backend jobs.rs) signs: workspace, job, resume id, hex HMAC.
const SIGNED_PATH = {
resume: new RegExp(`^/api/w/[\\w-]+/jobs_u/resume/${UUID}/\\d+/[0-9a-f]{64}$`, 'i'),
cancel: new RegExp(`^/api/w/[\\w-]+/jobs_u/cancel/${UUID}/\\d+/[0-9a-f]{64}$`, 'i')
}
function httpUrl(value: unknown, base: string): URL | undefined {
if (typeof value !== 'string' || !value) return undefined
try {
const url = new URL(value, base)
return ['http:', 'https:'].includes(url.protocol) ? url : undefined
} catch {
return undefined
}
}
/**
* The resume or cancel URL of an approval result, when it has the shape of a signed
* `jobs_u/resume|cancel` URL. A job result is written by whoever ran the job and the button
* sends the request from the viewer's browser, so any other URL is refused. The origin is free:
* the instance's BASE_URL need not be the address it is browsed at.
*/
export function signedResumeUrl(
value: unknown,
op: 'resume' | 'cancel',
base: string
): string | undefined {
const url = httpUrl(value, base)
if (!url || url.hash || !SIGNED_PATH[op].test(url.pathname)) return undefined
let otherParam = false
url.searchParams.forEach((_, k) => {
if (k !== 'approver') otherParam = true
})
if (otherParam) return undefined
return url.href
}
/**
* The signature alone authorizes a resume; the session only names the approver, so it goes
* only to this instance.
*/
export function resumeRequestCredentials(url: string, base: string): RequestCredentials {
return new URL(url, base).origin === new URL(base).origin ? 'same-origin' : 'omit'
}
/**
* The approval page link of an approval result, kept only when it is an http(s) link to this
* instance or to the instance its signed resume URL points to.
*/
export function approvalPageHref(
value: unknown,
base: string,
resumeUrl: string | undefined
): string | undefined {
const url = httpUrl(value, base)
if (!url) return undefined
const allowed = [new URL(base).origin, ...(resumeUrl ? [new URL(resumeUrl).origin] : [])]
return allowed.includes(url.origin) ? safeHref(url.href, base) : undefined
}
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest'
import { isFromEmbedder } from './embedderMessage'
const self = {} as Window
const parent = {} as Window
const other = {} as Window
const ownOrigin = 'https://wm.example'
describe('isFromEmbedder', () => {
it('accepts a same-origin embedder', () => {
expect(
isFromEmbedder(
{ source: parent, origin: ownOrigin },
{ self, parent, ownOrigin, hasUrlToken: false }
)
).toBe(true)
})
it('accepts a cross-origin embedder only when the page carries a url token', () => {
const event = { source: parent, origin: 'vscode-webview://abc' }
expect(isFromEmbedder(event, { self, parent, ownOrigin, hasUrlToken: true })).toBe(true)
expect(isFromEmbedder(event, { self, parent, ownOrigin, hasUrlToken: false })).toBe(false)
})
it('ignores messages from windows other than the embedder', () => {
expect(
isFromEmbedder(
{ source: other, origin: 'https://elsewhere.example' },
{ self, parent, ownOrigin, hasUrlToken: true }
)
).toBe(false)
})
it('ignores everything when the page is not embedded', () => {
expect(
isFromEmbedder(
{ source: self, origin: ownOrigin },
{ self, parent: self, ownOrigin, hasUrlToken: true }
)
).toBe(false)
})
})
+29
View File
@@ -0,0 +1,29 @@
type EmbedderMessageContext = {
self: Window
parent: Window | null
ownOrigin: string
// The page was opened with a `wm_token`, so its API calls carry that token rather than the
// session cookie.
hasUrlToken: boolean
}
// The dev pages are driven by whatever embeds them (the VS Code extension's webview). Only that
// embedder may drive them, and a cross-origin one only when it handed the page a token: without
// one, the page acts with the session cookie, which another site must never steer.
export function isFromEmbedder(
event: Pick<MessageEvent, 'source' | 'origin'>,
ctx: EmbedderMessageContext
): boolean {
if (!ctx.parent || ctx.parent === ctx.self) return false
if (event.source !== ctx.parent) return false
return event.origin === ctx.ownOrigin || ctx.hasUrlToken
}
export function isFromWindowEmbedder(event: MessageEvent): boolean {
return isFromEmbedder(event, {
self: window,
parent: window.parent,
ownOrigin: window.location.origin,
hasUrlToken: !!new URLSearchParams(window.location.search).get('wm_token')
})
}
@@ -5,13 +5,18 @@
<script lang="ts">
import { page } from '$app/state'
import CenteredModal from '$lib/components/CenteredModal.svelte'
import { Button } from '$lib/components/common'
import { Badge, Button } from '$lib/components/common'
import MultiSelect from '$lib/components/select/MultiSelect.svelte'
import Select from '$lib/components/select/Select.svelte'
import Toggle from '$lib/components/Toggle.svelte'
import McpAccessPicker, { type McpAccess } from '$lib/components/mcp/McpAccessPicker.svelte'
import { UserService, WorkspaceService } from '$lib/gen'
import { listEveryWorkspace } from '$lib/mcpAuth'
import {
McpOauthService,
UserService,
WorkspaceService,
type GetMcpOauthServerClientResponse
} from '$lib/gen'
import { listEveryWorkspace, parseScopeParam } from '$lib/mcpAuth'
import { sendUserToast } from '$lib/toast'
import { copyToClipboard } from '$lib/utils'
import Copy from 'lucide-svelte/icons/copy'
@@ -21,12 +26,23 @@
let isGateway = page.url.searchParams.get('gateway') === 'true'
let workspaceId = $state(page.url.searchParams.get('workspace_id') || '')
let clientId = page.url.searchParams.get('client_id') || ''
let clientName = page.url.searchParams.get('client_name') || 'Unknown Client'
let redirectUri = page.url.searchParams.get('redirect_uri') || ''
// The name and redirect URIs come from the client's registration, not from the URL: anyone
// can link here, and the client picked its own name when it registered itself.
let client = $state<GetMcpOauthServerClientResponse>()
let clientLookupFailed = $state(false)
const clientName = $derived(client?.client_name ?? '')
const redirectRegistered = $derived(client?.redirect_uris.includes(redirectUri) ?? false)
McpOauthService.getMcpOauthServerClient({ clientId })
.then((c) => (client = c))
.catch((e) => {
// Logged out: the root layout is already sending the browser to the login page.
if (e?.status === 401) return
clientLookupFailed = true
})
// What the client asked for seeds the access picker; what is approved is the picker's.
const askedScopes = (page.url.searchParams.get('scope') || 'mcp:all')
.split(' ')
.filter((s) => s.startsWith('mcp:'))
const parsedScopes = parseScopeParam(page.url.searchParams.get('scope') || 'mcp:all')
const askedScopes = (parsedScopes ?? []).filter((s) => s.startsWith('mcp:'))
// Both narrowings at once is a client requesting every scope it was offered, not a choice.
const requestedScopes =
askedScopes.includes('mcp:all') &&
@@ -45,9 +61,20 @@
// browser-executable schemes here too — this also neutralizes any client rows
// registered before the backend fix.
const DISALLOWED_REDIRECT_SCHEMES = ['javascript:', 'data:', 'vbscript:', 'blob:', 'file:']
// The code lands on `redirectUri` as a top-level GET, so this instance's own API is no
// callback either.
function isOwnApiUrl(url: URL): boolean {
if (url.origin !== window.location.origin) return false
try {
return /^\/+api(\/|$)/i.test(decodeURIComponent(url.pathname))
} catch {
return true
}
}
function isSafeRedirectUri(uri: string): boolean {
try {
return !DISALLOWED_REDIRECT_SCHEMES.includes(new URL(uri).protocol.toLowerCase())
const url = new URL(uri)
return !DISALLOWED_REDIRECT_SCHEMES.includes(url.protocol.toLowerCase()) && !isOwnApiUrl(url)
} catch {
return false
}
@@ -72,7 +99,12 @@
}
}
const loopbackRedirect = redirectUriValid && isLoopbackUri(redirectUri)
const redirectOrigin = redirectUriValid ? new URL(redirectUri).origin : ''
// Where the code goes. A private-use scheme (vscode://, cursor://) has an opaque origin.
function redirectDestination(uri: string): string {
const url = new URL(uri)
return url.origin !== 'null' ? url.origin : `${url.protocol}//${url.host}`
}
const redirectOrigin = redirectUriValid ? redirectDestination(redirectUri) : ''
let loading = $state(false)
let success = $state(false)
@@ -145,7 +177,7 @@
}
function onDeny() {
if (!redirectUriValid) return
if (!redirectUriValid || !redirectRegistered) return
// Redirect to client with error
const params = new URLSearchParams({
error: 'access_denied',
@@ -158,7 +190,7 @@
}
async function onApprove() {
if (!redirectUriValid) return
if (!redirectUriValid || !redirectRegistered) return
if (!grantsWorkspace) {
sendUserToast('Please select a workspace', true)
return
@@ -223,6 +255,20 @@
<CenteredModal title="Authorization Request">
<p class="text-center text-sm text-primary"> Error: invalid or unsafe redirect_uri </p>
</CenteredModal>
{:else if clientLookupFailed || (client && !redirectRegistered)}
<CenteredModal title="Authorization Request">
<p class="text-center text-sm text-primary">
Error: unknown client, or a redirect_uri it did not register
</p>
</CenteredModal>
{:else if !client}
<CenteredModal title="Authorization Request">
<p class="text-center text-sm text-secondary">Loading...</p>
</CenteredModal>
{:else if !parsedScopes}
<CenteredModal title="Authorization Request">
<p class="text-center text-sm text-primary">Error: invalid scope</p>
</CenteredModal>
{:else if !isGateway && !workspaceId}
<CenteredModal title="Authorization Request">
<p class="text-center text-sm text-primary">Error: missing workspace_id</p>
@@ -276,8 +322,9 @@
{/if}
</div>
{:else}
<p class="text-center text-sm text-primary mb-6">
<p class="text-center text-sm text-primary mb-2">
<span class="font-semibold text-accent">{clientName}</span>
<Badge color="yellow" small>Unverified app</Badge>
is requesting access to
{#if isGateway}
your Windmill workspaces.
@@ -287,12 +334,15 @@
workspace.
{/if}
</p>
{#if loopbackRedirect}
<p class="text-center text-xs text-secondary -mt-4 mb-6">
After you approve, {clientName} receives the sign-in at
<span class="font-mono">{redirectOrigin}</span>, an address on this computer.
</p>
{/if}
<p class="text-center text-xs text-secondary mb-2">
After you approve, the sign-in is sent to
<span class="font-mono font-semibold text-emphasis break-all">{redirectOrigin}</span
>{#if loopbackRedirect}, an address on this computer{/if}.
</p>
<p class="text-center text-2xs text-tertiary mb-6">
The app registered itself under this name, and Windmill has not checked who runs it. Approve
only if you started this sign-in and you recognize the address above.
</p>
{#if isGateway}
<div class="mb-6 flex flex-col gap-2">
@@ -1,5 +1,5 @@
<script lang="ts">
import { run } from 'svelte/legacy';
import { run } from 'svelte/legacy'
import { goto } from '$lib/navigation'
@@ -9,13 +9,13 @@
import { usersWorkspaceStore, workspaceStore } from '$lib/stores'
import CenteredModal from '$lib/components/CenteredModal.svelte'
import { Button } from '$lib/components/common'
import { toSameOriginRelativePath } from '$lib/logoutRedirect'
let workspace_id = $page.url.searchParams.get('workspace') ?? ''
let username = $state('')
let errorUsername = $state('')
let checking = $state(false)
async function acceptInvite(): Promise<void> {
await UserService.acceptInvite({
requestBody: {
@@ -25,7 +25,7 @@
})
usersWorkspaceStore.set(await WorkspaceService.listUserWorkspaces())
workspaceStore.set(workspace_id)
goto($page.url.searchParams.get('rd') ?? '/')
goto(toSameOriginRelativePath($page.url.searchParams.get('rd')) ?? '/')
}
async function validateName(username: string): Promise<void> {
@@ -67,7 +67,7 @@
getAutomateUsernameCreationSetting()
run(() => {
validateName(username)
});
})
</script>
<!-- Enable submit form on enter -->

Some files were not shown because too many files have changed in this diff Show More