diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 2092c4b0ee..f239cc398b 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.888.0" + ".": "1.889.1" } diff --git a/CHANGELOG.md b/CHANGELOG.md index ec0fd3cd17..660a666f04 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/backend/.sqlx/query-99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465.json b/backend/.sqlx/query-99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465.json new file mode 100644 index 0000000000..06d87660f8 --- /dev/null +++ b/backend/.sqlx/query-99acb6ee58e9289e5f10f535859290da9bd333a79aa71f0bc3118381aaeae465.json @@ -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" +} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 1098970b7d..7fcac83266 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -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", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 4c272e669f..7f433ec1b6 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -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 "] edition = "2021" diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 2ede280219..7d9858a566 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -88fac323b86968314ffe60900dcff26fff7cb33a +5a35e6f2a01650b4cc846eba8997837bb307bf71 diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index fa794df669..41d38f4da7 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -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", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index a0463da55c..467523dc42 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-parser-wasm/Cargo.toml @@ -12,7 +12,7 @@ resolver = "2" members = ["."] [workspace.package] -version = "1.888.0" +version = "1.889.1" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/tests/app_render_isolation_for_visitors.rs b/backend/tests/app_render_isolation_for_visitors.rs new file mode 100644 index 0000000000..b9da991e19 --- /dev/null +++ b/backend/tests/app_render_isolation_for_visitors.rs @@ -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 { + 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) -> 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(()) +} diff --git a/backend/tests/autoscaling_count.rs b/backend/tests/autoscaling_count.rs new file mode 100644 index 0000000000..31bbb0c726 --- /dev/null +++ b/backend/tests/autoscaling_count.rs @@ -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) -> 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, 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) -> 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) -> anyhow::Result> { + 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) -> 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) -> 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) -> 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) -> 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(()) +} diff --git a/backend/tests/jobs_cross_site_get.rs b/backend/tests/jobs_cross_site_get.rs index 5b6151c328..db602da9a6 100644 --- a/backend/tests/jobs_cross_site_get.rs +++ b/backend/tests/jobs_cross_site_get.rs @@ -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) -> 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) -> 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) -> 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!({})), ), ]; diff --git a/backend/tests/mcp_header_var_refs.rs b/backend/tests/mcp_header_var_refs.rs index 270ae35449..1a4eec2d5f 100644 --- a/backend/tests/mcp_header_var_refs.rs +++ b/backend/tests/mcp_header_var_refs.rs @@ -91,7 +91,7 @@ async fn test_mcp_header_var_ref_requires_variable_scope(db: Pool) -> 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) -> .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() )) diff --git a/backend/tests/mcp_token_exfil.rs b/backend/tests/mcp_token_exfil.rs index 1d36ba9546..a1862b7198 100644 --- a/backend/tests/mcp_token_exfil.rs +++ b/backend/tests/mcp_token_exfil.rs @@ -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) -> 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) -> 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, diff --git a/backend/windmill-api-auth/Cargo.toml b/backend/windmill-api-auth/Cargo.toml index c2cd3a1674..474b8710ea 100644 --- a/backend/windmill-api-auth/Cargo.toml +++ b/backend/windmill-api-auth/Cargo.toml @@ -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 diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index f1a55f9cf5..7c2893ed46 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -1159,6 +1159,36 @@ async fn pick_live_session_token( 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::().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(parts: &mut Parts, state: &S) -> Option { let auth_header = parts .headers @@ -1170,7 +1200,7 @@ pub(crate) async fn extract_token(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::::from_request_parts(parts, state) @@ -1181,7 +1211,8 @@ pub(crate) async fn extract_token(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::().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::().is_some() { + return Err(( + Error::PermissionDenied(FOREIGN_COOKIE_REFUSED.to_string()), + parts, + )); + } BRUTE_FORCE_COUNTER.increment().await; Err((Error::NotAuthorized("Unauthorized".to_string()), parts)) } diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index e75732202a..0d07bbce6d 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -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); diff --git a/backend/windmill-api-auth/src/request_site.rs b/backend/windmill-api-auth/src/request_site.rs new file mode 100644 index 0000000000..733963b41d --- /dev/null +++ b/backend/windmill-api-auth/src/request_site.rs @@ -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 `.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, +} + +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 }, + /// No `Sec-Fetch-Site` and no `Origin`; `Referer` names another host. + Referer { referer: String, instance_hosts: Vec }, +} + +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_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 { + 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 + '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 { + 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 { + 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 { + 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 { + 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 { + 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); + } +} diff --git a/backend/windmill-api-auth/src/scopes.rs b/backend/windmill-api-auth/src/scopes.rs index 9247411bb2..beaa253780 100644 --- a/backend/windmill-api-auth/src/scopes.rs +++ b/backend/windmill-api-auth/src/scopes.rs @@ -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, diff --git a/backend/windmill-api-integration-tests/tests/resources.rs b/backend/windmill-api-integration-tests/tests/resources.rs index 9f465eed26..f4d6e73c6b 100644 --- a/backend/windmill-api-integration-tests/tests/resources.rs +++ b/backend/windmill-api-integration-tests/tests/resources.rs @@ -946,25 +946,35 @@ async fn test_mcp_tools(db: Pool) -> 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) -> 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!( diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index 883a6d3195..6d6f7ae7d6 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -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 { - 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 diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 404f81b0c2..24ba86cd5d 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -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 diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 64cf65dfb7..8887dc1834 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -1703,6 +1703,7 @@ pub async fn build_embed_token_response( sdk_consent: bool, job_id: Option, ) -> Result { + 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 { + 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 diff --git a/backend/windmill-api/src/csrf.rs b/backend/windmill-api/src/csrf.rs index 6a8ec4a6fd..a5e1637e86 100644 --- a/backend/windmill-api/src/csrf.rs +++ b/backend/windmill-api/src/csrf.rs @@ -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:` or `$res:` 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:` or `$res:` 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); +/// 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); 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 FromRequestParts 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 FromRequestParts for CrossSiteGetGuard { Ok(CrossSiteGetGuard(has_session_cookie.then_some(signal))) } } - -enum CrossSite { - Declared, - RefererMismatch { referer: String, instance_hosts: Vec }, -} - -fn cross_site_signal(parts: &Parts) -> Option { - 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 = 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 { - 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 { - 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 { - 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 { - 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 { - 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); - } -} diff --git a/backend/windmill-api/src/explicit_credential.rs b/backend/windmill-api/src/explicit_credential.rs new file mode 100644 index 0000000000..13fb95df99 --- /dev/null +++ b/backend/windmill-api/src/explicit_credential.rs @@ -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(&[])); + } +} diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index e3d5b2a717..7794653bf5 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -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")] diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index fdce7b4907..08a58b353f 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -252,6 +252,21 @@ fn supported_scopes() -> Vec { 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, &'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( + ¶ms.redirect_uri, + "invalid_scope", + Some(e), + params.state.as_deref(), + ) + .into_response(); + } + let code_challenge = match ¶ms.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 = 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, + created_at: chrono::DateTime, +} + +/// 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, + _authed: ApiAuthed, + Path(client_id): Path, +) -> Result> { + 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::::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() { diff --git a/backend/windmill-api/src/resources.rs b/backend/windmill-api/src/resources.rs index 803927e43c..49518c4a4d 100644 --- a/backend/windmill-api/src/resources.rs +++ b/backend/windmill-api/src/resources.rs @@ -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 diff --git a/backend/windmill-common/src/scopes.rs b/backend/windmill-common/src/scopes.rs index 8549e673ba..bf834a9968 100644 --- a/backend/windmill-common/src/scopes.rs +++ b/backend/windmill-common/src/scopes.rs @@ -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 { + 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!( diff --git a/backend/windmill-store/src/resources.rs b/backend/windmill-store/src/resources.rs index 01ff46bd1d..fd5ae7958c 100644 --- a/backend/windmill-store/src/resources.rs +++ b/backend/windmill-store/src/resources.rs @@ -3530,6 +3530,8 @@ async fn create_resource_type( Path(w_id): Path, Json(resource_type): Json, ) -> 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 { 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, ) -> Result { + check_scopes(&authed, || "resources:write".to_string())?; use sql_builder::prelude::*; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, diff --git a/backend/windmill-store/src/variables.rs b/backend/windmill-store/src/variables.rs index aff754e3c1..dafef639a7 100644 --- a/backend/windmill-store/src/variables.rs +++ b/backend/windmill-store/src/variables.rs @@ -85,9 +85,13 @@ pub fn workspaced_service() -> Router { async fn list_contextual_variables( Path(w_id): Path, - ApiAuthed { username, email, .. }: ApiAuthed, + authed: ApiAuthed, Extension(db): Extension, ) -> JsonResult> { + // 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(), diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 0d9861cfb3..19234a3acc 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -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 { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 5a88f18d4c..c9e8389af3 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -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", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index 789cb2861d..657c1cf9ee 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -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", diff --git a/cli/src/commands/app/app.ts b/cli/src/commands/app/app.ts index b4d8230bdb..a8353d2316 100644 --- a/cli/src/commands/app/app.ts +++ b/cli/src/commands/app/app.ts @@ -102,12 +102,10 @@ export function replaceInlineScripts( const o: Record = 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); diff --git a/cli/src/commands/app/app_metadata.ts b/cli/src/commands/app/app_metadata.ts index 9513256d2d..f611efd392 100644 --- a/cli/src/commands/app/app_metadata.ts +++ b/cli/src/commands/app/app_metadata.ts @@ -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; } diff --git a/cli/src/commands/app/dev.ts b/cli/src/commands/app/dev.ts index 11fb5793bd..997acdba54 100644 --- a/cli/src/commands/app/dev.ts +++ b/cli/src/commands/app/dev.ts @@ -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:`: 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 diff --git a/cli/src/commands/dev/dev.ts b/cli/src/commands/dev/dev.ts index 562c38233e..0769f57b17 100644 --- a/cli/src/commands/dev/dev.ts +++ b/cli/src/commands/dev/dev.ts @@ -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(); 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 { - 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 = 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:`. 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((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 ", + "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; diff --git a/cli/src/commands/flow/flow.ts b/cli/src/commands/flow/flow.ts index 94944d3f06..8d419e38f0 100644 --- a/cli/src/commands/flow/flow.ts +++ b/cli/src/commands/flow/flow.ts @@ -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, diff --git a/cli/src/commands/flow/flow_metadata.ts b/cli/src/commands/flow/flow_metadata.ts index 180491ea90..03a5c2c659 100644 --- a/cli/src/commands/flow/flow_metadata.ts +++ b/cli/src/commands/flow/flow_metadata.ts @@ -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 diff --git a/cli/src/commands/resource/resource.ts b/cli/src/commands/resource/resource.ts index 4470daa276..80a10902de 100644 --- a/cli/src/commands/resource/resource.ts +++ b/cli/src/commands/resource/resource.ts @@ -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.file.`, 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."; + 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 { 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 diff --git a/cli/src/commands/sync/sync.ts b/cli/src/commands/sync/sync.ts index 63521289c8..ec5e7a6615 100644 --- a/cli/src/commands/sync/sync.ts +++ b/cli/src/commands/sync/sync.ts @@ -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; diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index af13d0a08d..27ad93ce52 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -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"; diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index ff00734e20..268e8b8879 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -9006,6 +9006,7 @@ Watch local file changes and live-reload the dev page for preview. Does NOT depl - \`--proxy-port \` - Port for a localhost reverse proxy to the remote Windmill server - \`--path \` - Watch a specific windmill path (e.g., u/admin/my_script or f/my_flow) - \`--no-open\` - Do not open the browser automatically +- \`--host \` - 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 diff --git a/cli/src/utils/dev_server_access.ts b/cli/src/utils/dev_server_access.ts new file mode 100644 index 0000000000..f20268c0e1 --- /dev/null +++ b/cli/src/utils/dev_server_access.ts @@ -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:`, 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); +} diff --git a/cli/src/utils/metadata.ts b/cli/src/utils/metadata.ts index 394ea607e7..8f5490815c 100644 --- a/cli/src/utils/metadata.ts +++ b/cli/src/utils/metadata.ts @@ -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; } diff --git a/cli/src/utils/port-probe.ts b/cli/src/utils/port-probe.ts index 3495e5de96..cfff4cfd10 100644 --- a/cli/src/utils/port-probe.ts +++ b/cli/src/utils/port-probe.ts @@ -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; diff --git a/cli/src/utils/utils.ts b/cli/src/utils/utils.ts index a37de385a2..69b42f5f89 100644 --- a/cli/src/utils/utils.ts +++ b/cli/src/utils/utils.ts @@ -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 ""; diff --git a/cli/test/dev_server.test.ts b/cli/test/dev_server.test.ts index b4f630b3fa..75dbc3700e 100644 --- a/cli/test/dev_server.test.ts +++ b/cli/test/dev_server.test.ts @@ -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((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}`); diff --git a/cli/test/dev_server_access_unit.test.ts b/cli/test/dev_server_access_unit.test.ts new file mode 100644 index 0000000000..a39527e386 --- /dev/null +++ b/cli/test/dev_server_access_unit.test.ts @@ -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); + } +}); diff --git a/cli/test/inline_path_within_unit.test.ts b/cli/test/inline_path_within_unit.test.ts new file mode 100644 index 0000000000..1cd7834e8a --- /dev/null +++ b/cli/test/inline_path_within_unit.test.ts @@ -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/, + ); + } + }); +}); diff --git a/cli/test/remote_key_within_folder_unit.test.ts b/cli/test/remote_key_within_folder_unit.test.ts new file mode 100644 index 0000000000..7c9b5962a4 --- /dev/null +++ b/cli/test/remote_key_within_folder_unit.test.ts @@ -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/, + ); + } +}); diff --git a/docs/auth-surface.md b/docs/auth-surface.md index 87a92717d9..e80f59761a 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -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 diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 24db83fc7c..786de9d4da 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -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": { diff --git a/frontend/package.json b/frontend/package.json index 3c0d590b83..53d4d52a1b 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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", diff --git a/frontend/scripts/openapi-ts-request.ts b/frontend/scripts/openapi-ts-request.ts new file mode 100644 index 0000000000..12f6a24304 --- /dev/null +++ b/frontend/scripts/openapi-ts-request.ts @@ -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 => { + 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 = (options: ApiRequestOptions) => Promise + +export const resolve = async ( + options: ApiRequestOptions, + resolver?: T | Resolver +): Promise => { + if (typeof resolver === 'function') { + return (resolver as Resolver)(options) + } + return resolver +} + +export const getHeaders = async ( + config: OpenAPIConfig, + options: ApiRequestOptions +): Promise => { + 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 + ) + + 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 => { + 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 => { + 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 = { + 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 + * @throws ApiError + */ +export const request = ( + config: OpenAPIConfig, + options: ApiRequestOptions +): CancelablePromise => { + 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) + } + }) +} diff --git a/frontend/scripts/ui_builder_artifact.json b/frontend/scripts/ui_builder_artifact.json index 1194fe79df..56b749d22e 100644 --- a/frontend/scripts/ui_builder_artifact.json +++ b/frontend/scripts/ui_builder_artifact.json @@ -1,5 +1,5 @@ { "baseUrl": "https://pub-06154ed168a24e73a86ab84db6bf15d8.r2.dev", - "version": "5ae35e6", - "sha256": "cdc948ce65b3ed0befbbfab7c816f2db63ae9207bbd85653d3484516c7ac3238" + "version": "f9da2f8", + "sha256": "fec1b1536fa0f97759314337d79b1f64bd0f5fb6d5e8aee3d5e2a2abb247ca8f" } diff --git a/frontend/src/app.html b/frontend/src/app.html index 29d55331c3..385b927b18 100644 --- a/frontend/src/app.html +++ b/frontend/src/app.html @@ -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 diff --git a/frontend/src/lib/apiPathParams.test.ts b/frontend/src/lib/apiPathParams.test.ts new file mode 100644 index 0000000000..f7ae08a9df --- /dev/null +++ b/frontend/src/lib/apiPathParams.test.ts @@ -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') + }) +}) diff --git a/frontend/src/lib/apiPathParams.ts b/frontend/src/lib/apiPathParams.ts new file mode 100644 index 0000000000..735776ed9a --- /dev/null +++ b/frontend/src/lib/apiPathParams.ts @@ -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('/') +} diff --git a/frontend/src/lib/ata/apis.ts b/frontend/src/lib/ata/apis.ts index a1fb914660..66d4ec3f99 100644 --- a/frontend/src/lib/ata/apis.ts +++ b/frontend/src/lib/ata/apis.ts @@ -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 (endpoint: string, resLimit: ResLimit): Promise => { @@ -153,11 +155,15 @@ export const getDTSFileForModuleWithVersion = ( version: string, // file comes with a prefix / file: string -) => - fromPreferredSource( - () => 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( + () => 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 diff --git a/frontend/src/lib/ata/confinedPath.test.ts b/frontend/src/lib/ata/confinedPath.test.ts new file mode 100644 index 0000000000..5df555d343 --- /dev/null +++ b/frontend/src/lib/ata/confinedPath.test.ts @@ -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') + }) +}) diff --git a/frontend/src/lib/ata/confinedPath.ts b/frontend/src/lib/ata/confinedPath.ts new file mode 100644 index 0000000000..b0c7861d33 --- /dev/null +++ b/frontend/src/lib/ata/confinedPath.ts @@ -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 +} diff --git a/frontend/src/lib/ata/index.ts b/frontend/src/lib/ata/index.ts index 004fe7f6df..c920696362 100644 --- a/frontend/src/lib/ata/index.ts +++ b/frontend/src/lib/ata/index.ts @@ -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' diff --git a/frontend/src/lib/components/Dev.svelte b/frontend/src/lib/components/Dev.svelte index d6185c00e2..6515807dde 100644 --- a/frontend/src/lib/components/Dev.svelte +++ b/frontend/src/lib/components/Dev.svelte @@ -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() diff --git a/frontend/src/lib/components/DisplayResult.svelte b/frontend/src/lib/components/DisplayResult.svelte index b73c255eb2..ca5b700177 100644 --- a/frontend/src/lib/components/DisplayResult.svelte +++ b/frontend/src/lib/components/DisplayResult.svelte @@ -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 @@ > {/if} - {:else if !forceJson && resultKind === 'approval'}
- - - + {: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 + )} +
+ {#if resumeUrl && cancelUrl} + + + {/if} + {#if approvalHref} + + {/if} + {#if !(resumeUrl && cancelUrl) && !approvalHref} + These are not Windmill approval links. + {/if}
{:else if !forceJson && resultKind === 'materialized'} {@const m = parseMaterializedResult(result)} @@ -1419,7 +1443,7 @@ {/if} {:else if !forceJson && resultKind === 'markdown'}
- +
{:else if largeObject || hasBigInt} {#if result && typeof result === 'object' && 'file' in result} diff --git a/frontend/src/lib/components/DynamicInput.svelte b/frontend/src/lib/components/DynamicInput.svelte index 76395f397f..a1e7ee0e37 100644 --- a/frontend/src/lib/components/DynamicInput.svelte +++ b/frontend/src/lib/components/DynamicInput.svelte @@ -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'} /> diff --git a/frontend/src/lib/components/Login.svelte b/frontend/src/lib/components/Login.svelte index 0f32f4568c..45e7199df6 100644 --- a/frontend/src/lib/components/Login.svelte +++ b/frontend/src/lib/components/Login.svelte @@ -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}

Set up two-factor authentication

- 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.

{:else if enrollSetup}

Set up two-factor authentication

diff --git a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte index 1795cbe841..008c26638d 100644 --- a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte +++ b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte @@ -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. diff --git a/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte b/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte index 4c391c0336..05cbdfc441 100644 --- a/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte +++ b/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte @@ -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 } } } diff --git a/frontend/src/lib/components/apps/editor/publicAppApi.ts b/frontend/src/lib/components/apps/editor/publicAppApi.ts index 674cb0b622..ad35261c57 100644 --- a/frontend/src/lib/components/apps/editor/publicAppApi.ts +++ b/frontend/src/lib/components/apps/editor/publicAppApi.ts @@ -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(path: string): Promise { export async function getUserExtOrUndefined(workspace: string): Promise { try { return mapUserToUserExt( - await publicGet(`/w/${encodeURI(workspace)}/users/whoami`), + await publicGet(`/w/${encodePathParam('workspace', workspace)}/users/whoami`), workspace ) } catch { diff --git a/frontend/src/lib/components/common/image/ImageViewer.svelte b/frontend/src/lib/components/common/image/ImageViewer.svelte index 8c6595c0de..1fe157d04a 100644 --- a/frontend/src/lib/components/common/image/ImageViewer.svelte +++ b/frontend/src/lib/components/common/image/ImageViewer.svelte @@ -130,8 +130,8 @@ /** The displayed image as PNG bytes, drawn through a canvas. */ function rasterize(): Promise { 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((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('encoding failed'))), 'image/png') diff --git a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte index 082760f12f..9aeec52b6d 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte @@ -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
{#if folderContent.trim()} - + {:else} Empty. {/if} diff --git a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte index 841966a687..1e4e0d28e2 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte @@ -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 } }] diff --git a/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte index 947fb562d3..172c67ab73 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantSkillsSection.svelte @@ -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.

{parsed.description}

{/if}
- +
diff --git a/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts b/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts index 62dce8af5c..00a87e7657 100644 --- a/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts +++ b/frontend/src/lib/components/copilot/chat/global/rawAppBundlerBridge.ts @@ -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 }) diff --git a/frontend/src/lib/components/copilot/chat/messageS3Object.test.ts b/frontend/src/lib/components/copilot/chat/messageS3Object.test.ts new file mode 100644 index 0000000000..6d7f9306d0 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/messageS3Object.test.ts @@ -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: 'hi', + 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' + }) + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/messageS3Object.ts b/frontend/src/lib/components/copilot/chat/messageS3Object.ts new file mode 100644 index 0000000000..14e3dba431 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/messageS3Object.ts @@ -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 + if (type !== 'windmill_s3_object' || typeof s3 !== 'string' || !s3) return undefined + return typeof storage === 'string' && storage ? { s3, storage } : { s3 } +} diff --git a/frontend/src/lib/components/flows/content/McpToolEditor.svelte b/frontend/src/lib/components/flows/content/McpToolEditor.svelte index 18d69dcb63..edea884c7a 100644 --- a/frontend/src/lib/components/flows/content/McpToolEditor.svelte +++ b/frontend/src/lib/components/flows/content/McpToolEditor.svelte @@ -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)} />
@@ -146,7 +164,10 @@ @@ -490,9 +482,9 @@ diff --git a/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte b/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte index 8c9b7d3ade..59fd0a9ae0 100644 --- a/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/cli/+page.svelte @@ -16,7 +16,19 @@ const port = rawPort == 0 || Number.isNaN(rawPort) ? 80 : rawPort const host = page.url.searchParams.get('host') || 'localhost' const scheme = page.url.searchParams.get('scheme') || 'http' - const callbackUrl = parseHttpUrl(`${scheme}://${host}:${port}`) + // Exactly a scheme name: anything longer (`https://other.host/?`) would let the value + // itself pick the host the token is posted to, while the prompt shows `host`. + const callbackUrl = + scheme === 'http' || scheme === 'https' + ? parseHttpUrl(`${scheme}://${host}:${port}`) + : undefined + + // `host` may legitimately name a remote machine (a CLI run over SSH), so it is not refused, + // only flagged: the token then leaves the machine the user is sitting at. + function isLoopback(hostname: string): boolean { + const h = hostname.toLowerCase() + return h === 'localhost' || h === '[::1]' || /^127(\.\d{1,3}){3}$/.test(h) + } const DEFAULT_DAYS = 30 const CHOICES_DAYS = [1, 7, 30, 90, 365] @@ -171,6 +183,12 @@ {/if}
{/if} + {#if callbackUrl && !isLoopback(callbackUrl.hostname)} + + This will send a new token to {callbackUrl.host}, not to your machine. Only continue if + you started this login from a CLI running on that host. + + {/if}