diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6f66e1e10b..3714717023 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.837.0" + ".": "1.841.0" } diff --git a/AGENTS.md b/AGENTS.md index 8c30fed2f9..6516e0e095 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,6 +33,9 @@ Open-source platform for internal tools, workflows, API integrations, background administers behind `external_instance` data tables and Ducklake catalogs: its invariants (one lifecycle lock, managed-object markers, the setup gate, per-cluster roles, fork copy ownership) and how to run one locally +- **Fork object storage**: `docs/fork-object-storage.md` — how a fork's object keys map under + `__wm_forks//` with read-through to its ancestors, where the mapping must be applied, + and why `__wm_forks/` is reachable only through a workspace's own chain - **Data table viewer roles**: `docs/datatable-viewer-roles.md`, on what a connection naming no role holds: the default role as a floor, whose roles are added (the job's own, or its viewer's for an inline app runnable that opts in), why an admin's roles are not added, the per-role-set diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e1db486d4..659adb9e25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,81 @@ # Changelog +## [1.841.0](https://github.com/windmill-labs/windmill/compare/v1.840.0...v1.841.0) (2026-10-18) + + +### Features + +* let agent workers authenticate with a workload identity token ([#11858](https://github.com/windmill-labs/windmill/issues/11858)) ([be23abb](https://github.com/windmill-labs/windmill/commit/be23abb3602ed9c45f1c66c98d5f84e7676dccfa)) +* let ALLOW_PRIVATE_MCP_SERVER_URLS name the private hosts it allows ([#11869](https://github.com/windmill-labs/windmill/issues/11869)) ([5c205fa](https://github.com/windmill-labs/windmill/commit/5c205fa46915de9e5fde731a117ba8571cfa56f7)) +* probe nsjail with a real jail and add a gVisor compat mode ([#11865](https://github.com/windmill-labs/windmill/issues/11865)) ([69d36f7](https://github.com/windmill-labs/windmill/commit/69d36f77daceb25cc903c7ea014ba8d487650b18)) + + +### Bug Fixes + +* insert ApiAuthed into request extensions in no-auth mode ([#11868](https://github.com/windmill-labs/windmill/issues/11868)) ([a7561fd](https://github.com/windmill-labs/windmill/commit/a7561fd8bde5c4a766a050507c2d9b9823c08bcc)) +* reject out-of-range integer args to narrow SQL types instead of wrapping ([#11864](https://github.com/windmill-labs/windmill/issues/11864)) ([19ec5d3](https://github.com/windmill-labs/windmill/commit/19ec5d3cd8a36600c8896a895d0e566735f729a9)) +* warn when an autoscaled worker group has no tags to count ([#11859](https://github.com/windmill-labs/windmill/issues/11859)) ([8b14a78](https://github.com/windmill-labs/windmill/commit/8b14a78822f95fb045d80940dfd9197f79ea88cc)) + +## [1.840.0](https://github.com/windmill-labs/windmill/compare/v1.839.0...v1.840.0) (2026-10-17) + + +### Features + +* add a no_network annotation for sandboxed jobs ([#11844](https://github.com/windmill-labs/windmill/issues/11844)) ([feb7b1a](https://github.com/windmill-labs/windmill/commit/feb7b1ad906046f4cf6ea53a85506f42b1b66e93)) +* warn at worker startup when WHITELIST_ENVS forwards a secret-shaped variable ([#11838](https://github.com/windmill-labs/windmill/issues/11838)) ([16c8be2](https://github.com/windmill-labs/windmill/commit/16c8be2355b919878091769810749c54c2f0a09d)) + + +### Bug Fixes + +* keep script and flow deploys off a second pool connection ([#11843](https://github.com/windmill-labs/windmill/issues/11843)) ([2684156](https://github.com/windmill-labs/windmill/commit/268415623b515280b99bd5d9e32876868821dc4f)) +* let ALLOW_PRIVATE_AI_BASE_URLS name the private hosts it allows ([#11841](https://github.com/windmill-labs/windmill/issues/11841)) ([b0c97b3](https://github.com/windmill-labs/windmill/commit/b0c97b34caa6343db278a9c5c09228248acf970c)) +* mount python script modules into the nsjail sandbox ([#11846](https://github.com/windmill-labs/windmill/issues/11846)) ([7a8cb62](https://github.com/windmill-labs/windmill/commit/7a8cb62fa135bff04522f4bbd93aba194e33b121)) +* refuse dot segments in AI proxy paths ([#11837](https://github.com/windmill-labs/windmill/issues/11837)) ([89f36a7](https://github.com/windmill-labs/windmill/commit/89f36a73d16675fd5f0d57daa2baf616ee95cbf5)) +* run bun and npm installs under nsjail sandboxing ([#11845](https://github.com/windmill-labs/windmill/issues/11845)) ([6646c86](https://github.com/windmill-labs/windmill/commit/6646c86351f188d9b7e355dfb46e87bfa5c81846)) +* scope delete_jobs side-table deletes to the request workspace ([#11836](https://github.com/windmill-labs/windmill/issues/11836)) ([09a5911](https://github.com/windmill-labs/windmill/commit/09a59110d941a8c306a0d89e99d34d509545059f)) +* skip the fork lock when a fork creation has no storage to purge ([#11842](https://github.com/windmill-labs/windmill/issues/11842)) ([0b54ebc](https://github.com/windmill-labs/windmill/commit/0b54ebc73d3d9541d2521857adc27766c4342000)) + + +### Performance Improvements + +* clone sqlx test databases from a migrated template ([#11848](https://github.com/windmill-labs/windmill/issues/11848)) ([4ed6c1a](https://github.com/windmill-labs/windmill/commit/4ed6c1a6ce1b6d53ea9ee965214da0c3adb3f3bd)) + +## [1.839.0](https://github.com/windmill-labs/windmill/compare/v1.838.0...v1.839.0) (2026-10-16) + + +### Features + +* add a Require isolated forks protection rule ([#11834](https://github.com/windmill-labs/windmill/issues/11834)) ([ab4e790](https://github.com/windmill-labs/windmill/commit/ab4e790a216b92f789e130955d7cd180b394d1fe)) +* isolate fork object storage under a per-fork prefix ([#11829](https://github.com/windmill-labs/windmill/issues/11829)) ([9375805](https://github.com/windmill-labs/windmill/commit/9375805fdf7501347a4dfb37e58f1be7fa2c5658)) +* one Entra app for the Teams bot and ms_teams Graph connect ([#11718](https://github.com/windmill-labs/windmill/issues/11718)) ([e7088e7](https://github.com/windmill-labs/windmill/commit/e7088e7f4766cd662890cdf61f2b6a5a0fce06a8)) +* route python S3 client settings through the S3 proxy ([#11819](https://github.com/windmill-labs/windmill/issues/11819)) ([de340ee](https://github.com/windmill-labs/windmill/commit/de340eed6f5520414b59166f8dc16938f7ac6c36)) + + +### Bug Fixes + +* verify Bot Framework JWT on incoming Teams activities ([#11818](https://github.com/windmill-labs/windmill/issues/11818)) ([0b1935f](https://github.com/windmill-labs/windmill/commit/0b1935f251605926760565fb7693f345f1a56312)) + +## [1.838.0](https://github.com/windmill-labs/windmill/compare/v1.837.0...v1.838.0) (2026-10-16) + + +### Features + +* accept Ed25519-signed license keys alongside RSA ([#11810](https://github.com/windmill-labs/windmill/issues/11810)) ([33d4049](https://github.com/windmill-labs/windmill/commit/33d4049db029e1dc478b1251c562232f0127fc8a)) +* make the frontend installable as a progressive web app ([#11805](https://github.com/windmill-labs/windmill/issues/11805)) ([b86909f](https://github.com/windmill-labs/windmill/commit/b86909fc81b21447414266f47a83a43492204e50)) +* name mcp script and flow tools after their last path segment ([#11817](https://github.com/windmill-labs/windmill/issues/11817)) ([d1a13d9](https://github.com/windmill-labs/windmill/commit/d1a13d9054d5994b5ed9c0f8566b86154662caa0)) +* route dev workspace and fork jobs to their own worker groups ([#11811](https://github.com/windmill-labs/windmill/issues/11811)) ([6e565b0](https://github.com/windmill-labs/windmill/commit/6e565b0dcb0fb56b69131c262d482c82bb6c527b)) + + +### Bug Fixes + +* **ai-chat:** tell the session chat that an agent is an ai_agent resource ([#11798](https://github.com/windmill-labs/windmill/issues/11798)) ([a521548](https://github.com/windmill-labs/windmill/commit/a52154877caa5c3e473ee56c1eaf040b7da2375f)) +* emit a single email claim in job OIDC tokens ([#11804](https://github.com/windmill-labs/windmill/issues/11804)) ([2ef0c0d](https://github.com/windmill-labs/windmill/commit/2ef0c0d8e14fcd5ff1c06f6113ffaf2792b9d4c9)) +* give inline script runs their own job dir ([#11822](https://github.com/windmill-labs/windmill/issues/11822)) ([6aec448](https://github.com/windmill-labs/windmill/commit/6aec4488ebe8f377b4ea9bb4948649831cba0dbc)) +* hold mcp token references to resource reference scopes ([#11803](https://github.com/windmill-labs/windmill/issues/11803)) ([c09038b](https://github.com/windmill-labs/windmill/commit/c09038b10698042209fd6aa26c466fb53d6dc7d0)) +* let deployed low-code apps run database studio queries again ([#11816](https://github.com/windmill-labs/windmill/issues/11816)) ([7c63a30](https://github.com/windmill-labs/windmill/commit/7c63a30edd650f49eff85066dcc7916cec1b7010)) +* truncate long row titles instead of wrapping ([#11815](https://github.com/windmill-labs/windmill/issues/11815)) ([153a871](https://github.com/windmill-labs/windmill/commit/153a871550e3ae9ad6282aa59b3a4f9897fec6c1)) +* use the session workspace's user in three AI session places ([#11808](https://github.com/windmill-labs/windmill/issues/11808)) ([19fc07f](https://github.com/windmill-labs/windmill/commit/19fc07faa95a8a2247e726f9d0a2adc3cfa42bd2)) + ## [1.837.0](https://github.com/windmill-labs/windmill/compare/v1.836.0...v1.837.0) (2026-10-15) diff --git a/Dockerfile b/Dockerfile index 80de6d4d16..79f9d05734 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,7 +18,9 @@ RUN apt-get -y update \ pkg-config=1.8.* \ protobuf-compiler=3.21.* -RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 +COPY docker/nsjail-patches/ /nsjail-patches/ +RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 \ + && git apply /nsjail-patches/*.patch RUN make FROM ${RUST_IMAGE} AS rust_base @@ -254,6 +256,11 @@ RUN curl -sL https://deb.nodesource.com/setup_24.x | bash - RUN apt-get -y update && apt-get install -y --no-install-recommends curl procps nodejs awscli && apt-get clean \ && rm -rf /var/lib/apt/lists/* +# The npm bundled with nodejs is replaced by a pinned one: it is what `//npm` scripts install with +# (NPM_PATH=/usr/bin/npm). npm 12 skips dependency install scripts not covered by an allowScripts +# policy (package.json or .npmrc). +RUN npm install -g npm@12.2.0 && npm cache clean --force + # go build is slower the first time it is ran, so we prewarm it in the build # This mirrors Windmill's Go wrapper structure: main.go imports inner package, uses encoding/json, os, fmt RUN export GOCACHE=/tmp/build_cache/go && \ diff --git a/backend/.cargo/config.toml b/backend/.cargo/config.toml index f8b0a5e32a..2b90b4bb23 100644 --- a/backend/.cargo/config.toml +++ b/backend/.cargo/config.toml @@ -24,4 +24,14 @@ rustflags = [ ] [net] -git-fetch-with-cli = true \ No newline at end of file +git-fetch-with-cli = true + +[env] +# `#[sqlx::test]` clones each test database from a template migrated once, instead of running +# every migration per test. The `_sqlx_tmpl_*` databases it leaves on the server are reused. +SQLX_TEST_TEMPLATE = "true" +# All `#[sqlx::test]` pools of a test binary share this many connections, and each keeps the +# ones it took until it ends: below 5 per test thread, concurrent tests can split them all and +# wait on each other until their acquire times out. 50 covers CI's `--test-threads=10`; a run +# with more threads over a binary of more than 10 tests needs 5 per thread. +SQLX_TEST_MAX_CONNECTIONS = "50" diff --git a/backend/.sqlx/query-009fd85c1aa55ea36454eafffbf62505461eb1cc8b9af85a2e2ab6e7dbe950c6.json b/backend/.sqlx/query-009fd85c1aa55ea36454eafffbf62505461eb1cc8b9af85a2e2ab6e7dbe950c6.json deleted file mode 100644 index c687589db1..0000000000 --- a/backend/.sqlx/query-009fd85c1aa55ea36454eafffbf62505461eb1cc8b9af85a2e2ab6e7dbe950c6.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock, ws_error_handler_muted)\n VALUES ('test-workspace', $1, 'f/test/muted_failing_script', 'export function main() { throw new Error(\"fail\"); }', 'bun', 'script', 'test-user', '{}', '', '', E'{}\\n//bun.lock\\n', true)\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8" - ] - }, - "nullable": [] - }, - "hash": "009fd85c1aa55ea36454eafffbf62505461eb1cc8b9af85a2e2ab6e7dbe950c6" -} diff --git a/backend/.sqlx/query-0fb0fea54a1580d4b7ffd37ca43e169f51dbbdc3584d3522f25e97e180e307fd.json b/backend/.sqlx/query-0fb0fea54a1580d4b7ffd37ca43e169f51dbbdc3584d3522f25e97e180e307fd.json new file mode 100644 index 0000000000..2afefc7ab8 --- /dev/null +++ b/backend/.sqlx/query-0fb0fea54a1580d4b7ffd37ca43e169f51dbbdc3584d3522f25e97e180e307fd.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT config FROM config WHERE name LIKE 'worker\\_\\_%'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "config", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + true + ] + }, + "hash": "0fb0fea54a1580d4b7ffd37ca43e169f51dbbdc3584d3522f25e97e180e307fd" +} diff --git a/backend/.sqlx/query-1043947475822c27f73b5357e6ec0d527d999f2865ff5de75186b49004a3565e.json b/backend/.sqlx/query-1043947475822c27f73b5357e6ec0d527d999f2865ff5de75186b49004a3565e.json deleted file mode 100644 index a0847ae2ca..0000000000 --- a/backend/.sqlx/query-1043947475822c27f73b5357e6ec0d527d999f2865ff5de75186b49004a3565e.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', $1, 'f/test/simple_script', $2, 'bun', 'script', 'test-user', '{}', 'Simple test script', 'A simple test script', E'{}\\n//bun.lock\\n')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8", - "Text" - ] - }, - "nullable": [] - }, - "hash": "1043947475822c27f73b5357e6ec0d527d999f2865ff5de75186b49004a3565e" -} diff --git a/backend/.sqlx/query-12c3101e02f197ad731b66f539fe677ad25520fcc9c5a2378a293122956bed4c.json b/backend/.sqlx/query-12c3101e02f197ad731b66f539fe677ad25520fcc9c5a2378a293122956bed4c.json deleted file mode 100644 index 1a5b16143b..0000000000 --- a/backend/.sqlx/query-12c3101e02f197ad731b66f539fe677ad25520fcc9c5a2378a293122956bed4c.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT error_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "?column?", - "type_info": "Text" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "12c3101e02f197ad731b66f539fe677ad25520fcc9c5a2378a293122956bed4c" -} diff --git a/backend/.sqlx/query-18d1a6ac94f2c87d5ea8c48a228f061135be4065dca33fbc429d8b0186c5ccb3.json b/backend/.sqlx/query-18d1a6ac94f2c87d5ea8c48a228f061135be4065dca33fbc429d8b0186c5ccb3.json deleted file mode 100644 index 8bd9bc4712..0000000000 --- a/backend/.sqlx/query-18d1a6ac94f2c87d5ea8c48a228f061135be4065dca33fbc429d8b0186c5ccb3.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET error_handler = '{\"path\": \"script/f/test/error_handler\", \"extra_args\": {\"notify\": true}, \"muted_on_cancel\": true, \"muted_on_user_path\": false}'::jsonb\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "18d1a6ac94f2c87d5ea8c48a228f061135be4065dca33fbc429d8b0186c5ccb3" -} diff --git a/backend/.sqlx/query-1f21ef9dfa502b425b85d2acb6b3af1694ee60157089ce0c823d6c1351b8ed2c.json b/backend/.sqlx/query-1f21ef9dfa502b425b85d2acb6b3af1694ee60157089ce0c823d6c1351b8ed2c.json new file mode 100644 index 0000000000..329c44540b --- /dev/null +++ b/backend/.sqlx/query-1f21ef9dfa502b425b85d2acb6b3af1694ee60157089ce0c823d6c1351b8ed2c.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id FROM v2_job WHERE workspace_id = $1 AND id = ANY($2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Text", + "UuidArray" + ] + }, + "nullable": [ + false + ] + }, + "hash": "1f21ef9dfa502b425b85d2acb6b3af1694ee60157089ce0c823d6c1351b8ed2c" +} diff --git a/backend/.sqlx/query-25bf3956b4365a4d4f96368bcc6e33817ae284ab26c195eee53d988d74263e86.json b/backend/.sqlx/query-25bf3956b4365a4d4f96368bcc6e33817ae284ab26c195eee53d988d74263e86.json deleted file mode 100644 index f7d03b7ebe..0000000000 --- a/backend/.sqlx/query-25bf3956b4365a4d4f96368bcc6e33817ae284ab26c195eee53d988d74263e86.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT (error_handler->>'muted_on_cancel')::boolean FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "bool", - "type_info": "Bool" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "25bf3956b4365a4d4f96368bcc6e33817ae284ab26c195eee53d988d74263e86" -} diff --git a/backend/.sqlx/query-28b8264a427e8c19be823d2b8e40736a7b7675780672b503d91737cd0c617657.json b/backend/.sqlx/query-28b8264a427e8c19be823d2b8e40736a7b7675780672b503d91737cd0c617657.json deleted file mode 100644 index 4a34503aaa..0000000000 --- a/backend/.sqlx/query-28b8264a427e8c19be823d2b8e40736a7b7675780672b503d91737cd0c617657.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT (error_handler->>'muted_on_user_path')::boolean FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "bool", - "type_info": "Bool" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "28b8264a427e8c19be823d2b8e40736a7b7675780672b503d91737cd0c617657" -} diff --git a/backend/.sqlx/query-28f3dfb70aed943ad3d64da608168c027c645afb73dfc2360245b68ba593cab4.json b/backend/.sqlx/query-28f3dfb70aed943ad3d64da608168c027c645afb73dfc2360245b68ba593cab4.json deleted file mode 100644 index 3eb58e590f..0000000000 --- a/backend/.sqlx/query-28f3dfb70aed943ad3d64da608168c027c645afb73dfc2360245b68ba593cab4.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET success_handler = '{\"path\": \"script/f/test/success_handler\", \"extra_args\": {\"key\": \"value\"}}'::jsonb\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "28f3dfb70aed943ad3d64da608168c027c645afb73dfc2360245b68ba593cab4" -} diff --git a/backend/.sqlx/query-2c2ed5c91a4893966e94305df8b9f8ac904c8d0781a83fdea66c918320fb5601.json b/backend/.sqlx/query-2c2ed5c91a4893966e94305df8b9f8ac904c8d0781a83fdea66c918320fb5601.json deleted file mode 100644 index 4b692f11a2..0000000000 --- a/backend/.sqlx/query-2c2ed5c91a4893966e94305df8b9f8ac904c8d0781a83fdea66c918320fb5601.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET success_handler = NULL\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "2c2ed5c91a4893966e94305df8b9f8ac904c8d0781a83fdea66c918320fb5601" -} diff --git a/backend/.sqlx/query-2d22fe27288580cb727e43b2abe3be2e6e6e3b03e61ce8f2879627115224c8cf.json b/backend/.sqlx/query-2d22fe27288580cb727e43b2abe3be2e6e6e3b03e61ce8f2879627115224c8cf.json new file mode 100644 index 0000000000..95fd9a3a2f --- /dev/null +++ b/backend/.sqlx/query-2d22fe27288580cb727e43b2abe3be2e6e6e3b03e61ce8f2879627115224c8cf.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT config FROM config WHERE name = $1 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "config", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true + ] + }, + "hash": "2d22fe27288580cb727e43b2abe3be2e6e6e3b03e61ce8f2879627115224c8cf" +} diff --git a/backend/.sqlx/query-344c08104d62d9bcd3f9117abb574e73a6fb364e4ab3e3916958c2e493673b1d.json b/backend/.sqlx/query-344c08104d62d9bcd3f9117abb574e73a6fb364e4ab3e3916958c2e493673b1d.json deleted file mode 100644 index 37f090c2b4..0000000000 --- a/backend/.sqlx/query-344c08104d62d9bcd3f9117abb574e73a6fb364e4ab3e3916958c2e493673b1d.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', 3333333333, 'f/test/error_handler', 'export function main() { return \"handled\"; }', 'bun', 'script', 'test-user', '{}', '', '', E'{}\\n//bun.lock\\n')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "344c08104d62d9bcd3f9117abb574e73a6fb364e4ab3e3916958c2e493673b1d" -} diff --git a/backend/.sqlx/query-3a71ab02239d8dd4e2f440a35155459a7d5091c125a0998e79d89f8c560a3fd3.json b/backend/.sqlx/query-3a71ab02239d8dd4e2f440a35155459a7d5091c125a0998e79d89f8c560a3fd3.json deleted file mode 100644 index 1c370d3ccf..0000000000 --- a/backend/.sqlx/query-3a71ab02239d8dd4e2f440a35155459a7d5091c125a0998e79d89f8c560a3fd3.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO group_ (workspace_id, name, summary, extra_perms)\n VALUES ('test-workspace', 'success_handler', 'The group the success handler acts on behalf of', '{\"u/test-user\": true}')\n ON CONFLICT DO NOTHING\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "3a71ab02239d8dd4e2f440a35155459a7d5091c125a0998e79d89f8c560a3fd3" -} diff --git a/backend/.sqlx/query-42250637493a623850ca76fe5a705fe4acef039f38a5e76da8d09f2f7e755779.json b/backend/.sqlx/query-42250637493a623850ca76fe5a705fe4acef039f38a5e76da8d09f2f7e755779.json deleted file mode 100644 index 402a406820..0000000000 --- a/backend/.sqlx/query-42250637493a623850ca76fe5a705fe4acef039f38a5e76da8d09f2f7e755779.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', 1234567890, 'f/test/success_handler', $1, 'bun', 'script', 'test-user', '{}', 'Success handler script', 'Handles successful job completions', E'{}\\n//bun.lock\\n')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text" - ] - }, - "nullable": [] - }, - "hash": "42250637493a623850ca76fe5a705fe4acef039f38a5e76da8d09f2f7e755779" -} diff --git a/backend/.sqlx/query-45b73345f2009122142f3410736b2d57a07e2047a704d9a7d8eab3416ff1d9d5.json b/backend/.sqlx/query-45b73345f2009122142f3410736b2d57a07e2047a704d9a7d8eab3416ff1d9d5.json new file mode 100644 index 0000000000..2c22ae1d7e --- /dev/null +++ b/backend/.sqlx/query-45b73345f2009122142f3410736b2d57a07e2047a704d9a7d8eab3416ff1d9d5.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM fork_storage_namespace WHERE workspace_id = ANY($1))\n AND EXISTS (SELECT 1 FROM workspace WHERE parent_workspace_id = $2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "TextArray", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "45b73345f2009122142f3410736b2d57a07e2047a704d9a7d8eab3416ff1d9d5" +} diff --git a/backend/.sqlx/query-4640ac69b297127cd0f5c369fa4a49857237cd57134dbc467b53601c1ec942d2.json b/backend/.sqlx/query-4640ac69b297127cd0f5c369fa4a49857237cd57134dbc467b53601c1ec942d2.json new file mode 100644 index 0000000000..5ad778d3c0 --- /dev/null +++ b/backend/.sqlx/query-4640ac69b297127cd0f5c369fa4a49857237cd57134dbc467b53601c1ec942d2.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM fork_storage_namespace WHERE workspace_id = $1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "4640ac69b297127cd0f5c369fa4a49857237cd57134dbc467b53601c1ec942d2" +} diff --git a/backend/.sqlx/query-5f5bdd667f699a5a1c05e07d805a97afb06252541d06b4785063819c3893b674.json b/backend/.sqlx/query-5f5bdd667f699a5a1c05e07d805a97afb06252541d06b4785063819c3893b674.json deleted file mode 100644 index 812fed8f23..0000000000 --- a/backend/.sqlx/query-5f5bdd667f699a5a1c05e07d805a97afb06252541d06b4785063819c3893b674.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO group_ (workspace_id, name, summary, extra_perms)\n VALUES ('test-workspace', 'error_handler', 'The group the error handler acts on behalf of', '{\"u/test-user\": true}')\n ON CONFLICT DO NOTHING\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "5f5bdd667f699a5a1c05e07d805a97afb06252541d06b4785063819c3893b674" -} diff --git a/backend/.sqlx/query-65016ea993fb40d4ab6b0a6f15c2082e8dfbaada01243bae07065c089bc42fa9.json b/backend/.sqlx/query-65016ea993fb40d4ab6b0a6f15c2082e8dfbaada01243bae07065c089bc42fa9.json deleted file mode 100644 index c0e9198953..0000000000 --- a/backend/.sqlx/query-65016ea993fb40d4ab6b0a6f15c2082e8dfbaada01243bae07065c089bc42fa9.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET success_handler = '{\"path\": \"script/f/test/success_handler\"}'::jsonb\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "65016ea993fb40d4ab6b0a6f15c2082e8dfbaada01243bae07065c089bc42fa9" -} diff --git a/backend/.sqlx/query-69e1c04c246c42a3a1d7202b6fb349d0ac779431993e225945ddfb91489cb927.json b/backend/.sqlx/query-69e1c04c246c42a3a1d7202b6fb349d0ac779431993e225945ddfb91489cb927.json deleted file mode 100644 index 751b727d0f..0000000000 --- a/backend/.sqlx/query-69e1c04c246c42a3a1d7202b6fb349d0ac779431993e225945ddfb91489cb927.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', 1111111111, 'f/test/error_handler', $1, 'bun', 'script', 'test-user', '{}', 'Error handler script', 'Handles failed job completions', E'{}\\n//bun.lock\\n')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text" - ] - }, - "nullable": [] - }, - "hash": "69e1c04c246c42a3a1d7202b6fb349d0ac779431993e225945ddfb91489cb927" -} diff --git a/backend/.sqlx/query-7796f40e349bf0771cceff037fa2224ab49659213638230be7f9acbf82d8e1b0.json b/backend/.sqlx/query-7796f40e349bf0771cceff037fa2224ab49659213638230be7f9acbf82d8e1b0.json new file mode 100644 index 0000000000..cf9dc458c2 --- /dev/null +++ b/backend/.sqlx/query-7796f40e349bf0771cceff037fa2224ab49659213638230be7f9acbf82d8e1b0.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT storage, storage_ref FROM fork_storage_namespace WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "storage", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "storage_ref", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false + ] + }, + "hash": "7796f40e349bf0771cceff037fa2224ab49659213638230be7f9acbf82d8e1b0" +} diff --git a/backend/.sqlx/query-79648f03eb50385183c34d57bda1ac984cf6502609df9ee51b7d684b585b8447.json b/backend/.sqlx/query-79648f03eb50385183c34d57bda1ac984cf6502609df9ee51b7d684b585b8447.json deleted file mode 100644 index fbf0c98de4..0000000000 --- a/backend/.sqlx/query-79648f03eb50385183c34d57bda1ac984cf6502609df9ee51b7d684b585b8447.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET error_handler = NULL\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "79648f03eb50385183c34d57bda1ac984cf6502609df9ee51b7d684b585b8447" -} diff --git a/backend/.sqlx/query-7ec099041134ee34057b57e86b35c67fad4532904ed633b85c3bbc627367ef0c.json b/backend/.sqlx/query-7ec099041134ee34057b57e86b35c67fad4532904ed633b85c3bbc627367ef0c.json new file mode 100644 index 0000000000..bb026c9b31 --- /dev/null +++ b/backend/.sqlx/query-7ec099041134ee34057b57e86b35c67fad4532904ed633b85c3bbc627367ef0c.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH RECURSIVE chain AS (\n SELECT id, parent_workspace_id, is_dev_workspace, deleted, 0 AS depth\n FROM workspace WHERE id = $1\n UNION ALL\n SELECT w.id, w.parent_workspace_id, w.is_dev_workspace, w.deleted, chain.depth + 1\n FROM workspace w\n JOIN chain ON w.id = chain.parent_workspace_id\n WHERE chain.depth < 20\n )\n SELECT\n (SELECT id FROM chain\n WHERE parent_workspace_id IS NULL\n OR (is_dev_workspace AND id NOT LIKE 'wm-fork-%')\n ORDER BY depth LIMIT 1) AS id,\n (SELECT parent_workspace_id IS NOT NULL FROM chain WHERE depth = 0) AS has_parent,\n (SELECT bool_or(is_dev_workspace\n OR (parent_workspace_id IS NULL AND id LIKE 'wm-fork-%')\n OR (deleted AND parent_workspace_id IS NOT NULL))\n FROM chain) AS in_dev_lineage\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "has_parent", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "in_dev_lineage", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null, + null, + null + ] + }, + "hash": "7ec099041134ee34057b57e86b35c67fad4532904ed633b85c3bbc627367ef0c" +} diff --git a/backend/.sqlx/query-8511e096394edb1433f6572d50b66d8558866af53d829d83fa634f12a90733c0.json b/backend/.sqlx/query-8511e096394edb1433f6572d50b66d8558866af53d829d83fa634f12a90733c0.json deleted file mode 100644 index 3420b8c337..0000000000 --- a/backend/.sqlx/query-8511e096394edb1433f6572d50b66d8558866af53d829d83fa634f12a90733c0.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', $1, 'f/test/success_script', 'export function main() { return \"ok\"; }', 'bun', 'script', 'test-user', '{}', '', '', E'{}\\n//bun.lock\\n')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8" - ] - }, - "nullable": [] - }, - "hash": "8511e096394edb1433f6572d50b66d8558866af53d829d83fa634f12a90733c0" -} diff --git a/backend/.sqlx/query-87044e1466cd114cbef336620e96dc29f3f930149fedc240d44c614dfc794ff7.json b/backend/.sqlx/query-87044e1466cd114cbef336620e96dc29f3f930149fedc240d44c614dfc794ff7.json deleted file mode 100644 index 9915fbf6c8..0000000000 --- a/backend/.sqlx/query-87044e1466cd114cbef336620e96dc29f3f930149fedc240d44c614dfc794ff7.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT success_handler->'extra_args' FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "?column?", - "type_info": "Jsonb" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "87044e1466cd114cbef336620e96dc29f3f930149fedc240d44c614dfc794ff7" -} diff --git a/backend/.sqlx/query-92b011eda2a652af714b08137b447753bc03ec35f6daa8ca245b1c8ed34c405f.json b/backend/.sqlx/query-92b011eda2a652af714b08137b447753bc03ec35f6daa8ca245b1c8ed34c405f.json deleted file mode 100644 index 794f62e49d..0000000000 --- a/backend/.sqlx/query-92b011eda2a652af714b08137b447753bc03ec35f6daa8ca245b1c8ed34c405f.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "DELETE FROM zombie_job_counter WHERE job_id IN (SELECT id FROM v2_job WHERE workspace_id = $1 AND id = ANY($2))", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "UuidArray" - ] - }, - "nullable": [] - }, - "hash": "92b011eda2a652af714b08137b447753bc03ec35f6daa8ca245b1c8ed34c405f" -} diff --git a/backend/.sqlx/query-98aebe8ead7d3f6e84ad88e6d006309b24b658cac3c99d8d0bdb84cdd00c413a.json b/backend/.sqlx/query-98aebe8ead7d3f6e84ad88e6d006309b24b658cac3c99d8d0bdb84cdd00c413a.json new file mode 100644 index 0000000000..f81b66ccb0 --- /dev/null +++ b/backend/.sqlx/query-98aebe8ead7d3f6e84ad88e6d006309b24b658cac3c99d8d0bdb84cdd00c413a.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT large_file_storage, ducklake FROM workspace_settings WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "large_file_storage", + "type_info": "Jsonb" + }, + { + "ordinal": 1, + "name": "ducklake", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true, + true + ] + }, + "hash": "98aebe8ead7d3f6e84ad88e6d006309b24b658cac3c99d8d0bdb84cdd00c413a" +} diff --git a/backend/.sqlx/query-a37dec4e86f537880d45da01ce872ae5b7858a087cb4eb5869573fff69c1c6b9.json b/backend/.sqlx/query-a37dec4e86f537880d45da01ce872ae5b7858a087cb4eb5869573fff69c1c6b9.json new file mode 100644 index 0000000000..7733ad9fa5 --- /dev/null +++ b/backend/.sqlx/query-a37dec4e86f537880d45da01ce872ae5b7858a087cb4eb5869573fff69c1c6b9.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT c.id AS \"id!\", ws.large_file_storage,\n EXISTS (SELECT 1 FROM fork_storage_namespace f\n WHERE f.workspace_id = c.id AND f.storage = $2) AS \"isolated!\"\n FROM unnest($1::text[]) WITH ORDINALITY AS c(id, ord)\n LEFT JOIN workspace_settings ws ON ws.workspace_id = c.id\n ORDER BY c.ord", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "large_file_storage", + "type_info": "Jsonb" + }, + { + "ordinal": 2, + "name": "isolated!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "TextArray", + "Text" + ] + }, + "nullable": [ + null, + true, + null + ] + }, + "hash": "a37dec4e86f537880d45da01ce872ae5b7858a087cb4eb5869573fff69c1c6b9" +} diff --git a/backend/.sqlx/query-b0c10d17ed684af4dc79db7a199d4438ea003b5762178f25ff12ef23c1a8f46a.json b/backend/.sqlx/query-b0c10d17ed684af4dc79db7a199d4438ea003b5762178f25ff12ef23c1a8f46a.json deleted file mode 100644 index a5a8c00494..0000000000 --- a/backend/.sqlx/query-b0c10d17ed684af4dc79db7a199d4438ea003b5762178f25ff12ef23c1a8f46a.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', $1, 'f/test/failing_script', $2, 'bun', 'script', 'test-user', '{}', 'Failing test script', 'A script that always fails', E'{}\\n//bun.lock\\n')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8", - "Text" - ] - }, - "nullable": [] - }, - "hash": "b0c10d17ed684af4dc79db7a199d4438ea003b5762178f25ff12ef23c1a8f46a" -} diff --git a/backend/.sqlx/query-ba0c3dad5d2a77922821c9c6d58e06a65e6666e197f3e59b880470df35c27bec.json b/backend/.sqlx/query-ba0c3dad5d2a77922821c9c6d58e06a65e6666e197f3e59b880470df35c27bec.json deleted file mode 100644 index 7c4fe34428..0000000000 --- a/backend/.sqlx/query-ba0c3dad5d2a77922821c9c6d58e06a65e6666e197f3e59b880470df35c27bec.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO group_ (workspace_id, name, summary, extra_perms)\n VALUES ('test-workspace', 'error_handler', 'Error handler group', '{\"u/test-user\": true}')\n ON CONFLICT DO NOTHING\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "ba0c3dad5d2a77922821c9c6d58e06a65e6666e197f3e59b880470df35c27bec" -} diff --git a/backend/.sqlx/query-bb4cde84157126f29680cb36075848e7cde2ab7c6b7f0861becd4c0b8c330a8d.json b/backend/.sqlx/query-bb4cde84157126f29680cb36075848e7cde2ab7c6b7f0861becd4c0b8c330a8d.json deleted file mode 100644 index 4c4e0b71a4..0000000000 --- a/backend/.sqlx/query-bb4cde84157126f29680cb36075848e7cde2ab7c6b7f0861becd4c0b8c330a8d.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET error_handler = '{\"path\": \"script/f/test/error_handler\"}'::jsonb\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "bb4cde84157126f29680cb36075848e7cde2ab7c6b7f0861becd4c0b8c330a8d" -} diff --git a/backend/.sqlx/query-bdc39bdd63c38217834a0c0d858f6db33d63ff7bf55329452dc84dae2560c23e.json b/backend/.sqlx/query-bdc39bdd63c38217834a0c0d858f6db33d63ff7bf55329452dc84dae2560c23e.json new file mode 100644 index 0000000000..cb595ad5b3 --- /dev/null +++ b/backend/.sqlx/query-bdc39bdd63c38217834a0c0d858f6db33d63ff7bf55329452dc84dae2560c23e.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM workspace WHERE id = $1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "bdc39bdd63c38217834a0c0d858f6db33d63ff7bf55329452dc84dae2560c23e" +} diff --git a/backend/.sqlx/query-c2f271bcea1f11b2979152cc743559236fd875192b7b7f4824c63675fdc6a551.json b/backend/.sqlx/query-c2f271bcea1f11b2979152cc743559236fd875192b7b7f4824c63675fdc6a551.json deleted file mode 100644 index c621e4b903..0000000000 --- a/backend/.sqlx/query-c2f271bcea1f11b2979152cc743559236fd875192b7b7f4824c63675fdc6a551.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET success_handler = '{\"path\": \"flow/f/test/success_flow\"}'::jsonb\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "c2f271bcea1f11b2979152cc743559236fd875192b7b7f4824c63675fdc6a551" -} diff --git a/backend/.sqlx/query-c37f34ea3603af1496825ec54a3415fe710c5fbbc7380c5088c7069fa2caf990.json b/backend/.sqlx/query-c37f34ea3603af1496825ec54a3415fe710c5fbbc7380c5088c7069fa2caf990.json new file mode 100644 index 0000000000..bb82fbf97e --- /dev/null +++ b/backend/.sqlx/query-c37f34ea3603af1496825ec54a3415fe710c5fbbc7380c5088c7069fa2caf990.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM fork_storage_namespace WHERE workspace_id = $1 AND storage = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "c37f34ea3603af1496825ec54a3415fe710c5fbbc7380c5088c7069fa2caf990" +} diff --git a/backend/.sqlx/query-cc719da4da98b6fe9612a4cc2f42dd19834a3e0d0be593ea6bc1239fe5453a74.json b/backend/.sqlx/query-cc719da4da98b6fe9612a4cc2f42dd19834a3e0d0be593ea6bc1239fe5453a74.json deleted file mode 100644 index 91cacf4123..0000000000 --- a/backend/.sqlx/query-cc719da4da98b6fe9612a4cc2f42dd19834a3e0d0be593ea6bc1239fe5453a74.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', 5555555555, 'f/test/error_handler', 'export function main() { return \"handled\"; }', 'bun', 'script', 'test-user', '{}', '', '', E'{}\\n//bun.lock\\n')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "cc719da4da98b6fe9612a4cc2f42dd19834a3e0d0be593ea6bc1239fe5453a74" -} diff --git a/backend/.sqlx/query-d5f1a2bfbac206a33b991d58f9ff4b8e8e4a3840ea1c65d409576379dede41ed.json b/backend/.sqlx/query-d5f1a2bfbac206a33b991d58f9ff4b8e8e4a3840ea1c65d409576379dede41ed.json deleted file mode 100644 index c6eb9e16a3..0000000000 --- a/backend/.sqlx/query-d5f1a2bfbac206a33b991d58f9ff4b8e8e4a3840ea1c65d409576379dede41ed.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT error_handler->'extra_args' FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "?column?", - "type_info": "Jsonb" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "d5f1a2bfbac206a33b991d58f9ff4b8e8e4a3840ea1c65d409576379dede41ed" -} diff --git a/backend/.sqlx/query-e4c9f3bca6bd636c3ee31fc643182ed5ca48a45da895fb992d820682f5169f7c.json b/backend/.sqlx/query-e4c9f3bca6bd636c3ee31fc643182ed5ca48a45da895fb992d820682f5169f7c.json deleted file mode 100644 index 63ce99a139..0000000000 --- a/backend/.sqlx/query-e4c9f3bca6bd636c3ee31fc643182ed5ca48a45da895fb992d820682f5169f7c.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT id\n FROM v2_job\n WHERE workspace_id = 'test-workspace'\n AND permissioned_as_email = 'error_handler@windmill.dev'\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id", - "type_info": "Uuid" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - false - ] - }, - "hash": "e4c9f3bca6bd636c3ee31fc643182ed5ca48a45da895fb992d820682f5169f7c" -} diff --git a/backend/.sqlx/query-e9808cc152e1ce4717260ebb42f203ca16321a4550073258734a6208b83c00c2.json b/backend/.sqlx/query-e9808cc152e1ce4717260ebb42f203ca16321a4550073258734a6208b83c00c2.json deleted file mode 100644 index 91479f0583..0000000000 --- a/backend/.sqlx/query-e9808cc152e1ce4717260ebb42f203ca16321a4550073258734a6208b83c00c2.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT success_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "?column?", - "type_info": "Text" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "e9808cc152e1ce4717260ebb42f203ca16321a4550073258734a6208b83c00c2" -} diff --git a/backend/.sqlx/query-eb6dc43ac53a853eab20ef804a092249e32b1184a146463094289c604bbd0332.json b/backend/.sqlx/query-eb6dc43ac53a853eab20ef804a092249e32b1184a146463094289c604bbd0332.json new file mode 100644 index 0000000000..b69c453bef --- /dev/null +++ b/backend/.sqlx/query-eb6dc43ac53a853eab20ef804a092249e32b1184a146463094289c604bbd0332.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO fork_storage_namespace (workspace_id, storage, storage_ref)\n VALUES ($1, $2, $3)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "eb6dc43ac53a853eab20ef804a092249e32b1184a146463094289c604bbd0332" +} diff --git a/backend/.sqlx/query-fdf0a16a72bc2eca2025d64750e2e6a7e7ff90b5ad4b42e6aab53992b447a20e.json b/backend/.sqlx/query-fdf0a16a72bc2eca2025d64750e2e6a7e7ff90b5ad4b42e6aab53992b447a20e.json deleted file mode 100644 index 69497769d7..0000000000 --- a/backend/.sqlx/query-fdf0a16a72bc2eca2025d64750e2e6a7e7ff90b5ad4b42e6aab53992b447a20e.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT\n id,\n runnable_path,\n permissioned_as_email,\n parent_job\n FROM v2_job\n WHERE workspace_id = 'test-workspace'\n AND permissioned_as_email = 'error_handler@windmill.dev'\n ORDER BY created_at DESC\n LIMIT 1\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id", - "type_info": "Uuid" - }, - { - "ordinal": 1, - "name": "runnable_path", - "type_info": "Varchar" - }, - { - "ordinal": 2, - "name": "permissioned_as_email", - "type_info": "Varchar" - }, - { - "ordinal": 3, - "name": "parent_job", - "type_info": "Uuid" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - false, - true, - false, - true - ] - }, - "hash": "fdf0a16a72bc2eca2025d64750e2e6a7e7ff90b5ad4b42e6aab53992b447a20e" -} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index f2571ecd5c..3f2dfbffec 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -243,9 +243,9 @@ dependencies = [ [[package]] name = "arc-swap" -version = "1.9.2" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" dependencies = [ "rustversion", ] @@ -7700,9 +7700,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.190" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libffi-sys" @@ -7771,7 +7771,7 @@ dependencies = [ "bitflags 2.13.2", "libc", "plain", - "redox_syscall 0.9.4", + "redox_syscall 0.9.5", ] [[package]] @@ -10735,9 +10735,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "737970939a87c6fa31e7acad13307bccbb017a073b695b6089a2c484f929e20e" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" dependencies = [ "bitflags 2.13.2", ] @@ -11709,9 +11709,9 @@ checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -12610,7 +12610,7 @@ dependencies = [ [[package]] name = "sqlx" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "sqlx-core", "sqlx-macros", @@ -12622,7 +12622,7 @@ dependencies = [ [[package]] name = "sqlx-core" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "base64 0.22.1", "bigdecimal", @@ -12660,7 +12660,7 @@ dependencies = [ [[package]] name = "sqlx-macros" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "proc-macro2", "quote", @@ -12672,7 +12672,7 @@ dependencies = [ [[package]] name = "sqlx-macros-core" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "dotenvy", "either", @@ -12696,7 +12696,7 @@ dependencies = [ [[package]] name = "sqlx-mysql" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "atoi", "base64 0.22.1", @@ -12740,7 +12740,7 @@ dependencies = [ [[package]] name = "sqlx-postgres" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "atoi", "base64 0.22.1", @@ -12780,7 +12780,7 @@ dependencies = [ [[package]] name = "sqlx-sqlite" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "atoi", "chrono", @@ -14876,9 +14876,9 @@ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-normalization" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" dependencies = [ "tinyvec", ] @@ -15486,7 +15486,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-nats", @@ -15576,7 +15576,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.837.0" +version = "1.841.0" dependencies = [ "async-stream", "async-trait", @@ -15611,7 +15611,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -15624,7 +15624,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "argon2", @@ -15767,7 +15767,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -15782,6 +15782,7 @@ dependencies = [ "tracing", "uuid", "windmill-api-auth", + "windmill-audit", "windmill-common", "windmill-parser-py-imports", "windmill-queue", @@ -15790,7 +15791,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -15807,7 +15808,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "axum", @@ -15833,7 +15834,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.837.0" +version = "1.841.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -15843,7 +15844,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -15860,7 +15861,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "base64 0.22.1", @@ -15882,7 +15883,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "axum", @@ -15905,7 +15906,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -15921,7 +15922,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -15943,7 +15944,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -15965,7 +15966,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -15979,7 +15980,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-nats", @@ -16015,7 +16016,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "axum", @@ -16041,7 +16042,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -16069,7 +16070,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "axum", @@ -16091,7 +16092,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -16111,7 +16112,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "axum", @@ -16153,7 +16154,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "axum", @@ -16183,7 +16184,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.837.0" +version = "1.841.0" dependencies = [ "lazy_static", "serde", @@ -16195,7 +16196,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.837.0" +version = "1.841.0" dependencies = [ "argon2", "axum", @@ -16219,7 +16220,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -16229,11 +16230,12 @@ dependencies = [ "uuid", "windmill-api-auth", "windmill-common", + "windmill-queue", ] [[package]] name = "windmill-api-workspaces" -version = "1.837.0" +version = "1.841.0" dependencies = [ "axum", "chrono", @@ -16272,7 +16274,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.837.0" +version = "1.841.0" dependencies = [ "chrono", "lazy_static", @@ -16287,7 +16289,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "axum", @@ -16306,7 +16308,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.837.0" +version = "1.841.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16344,8 +16346,10 @@ dependencies = [ "hex", "hkdf", "hmac 0.12.1", + "http 1.5.0", "hyper 1.12.0", "indexmap 2.14.2", + "ipnet", "itertools 0.14.0", "jsonwebtoken 10.4.0", "lazy_static", @@ -16422,7 +16426,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.837.0" +version = "1.841.0" dependencies = [ "chrono", "futures", @@ -16442,7 +16446,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.837.0" +version = "1.841.0" dependencies = [ "regex", "serde", @@ -16459,7 +16463,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16486,7 +16490,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "futures", @@ -16503,7 +16507,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.837.0" +version = "1.841.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16519,7 +16523,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -16541,7 +16545,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -16572,7 +16576,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "arc-swap", @@ -16597,7 +16601,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-stream", @@ -16633,7 +16637,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "futures", @@ -16652,7 +16656,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.837.0" +version = "1.841.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16661,7 +16665,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16673,7 +16677,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -16685,7 +16689,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "gosyn", @@ -16697,7 +16701,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16709,7 +16713,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -16721,7 +16725,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "nu-parser", @@ -16732,7 +16736,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16743,7 +16747,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16755,7 +16759,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16766,7 +16770,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-recursion", @@ -16789,7 +16793,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -16801,7 +16805,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16815,7 +16819,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16832,7 +16836,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16845,7 +16849,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "serde", @@ -16857,7 +16861,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16875,7 +16879,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16891,7 +16895,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16908,7 +16912,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16922,7 +16926,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-recursion", @@ -16961,7 +16965,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "const_format", @@ -16999,7 +17003,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.837.0" +version = "1.841.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17010,7 +17014,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-recursion", @@ -17045,7 +17049,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17069,7 +17073,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17102,7 +17106,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17129,7 +17133,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17162,7 +17166,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17182,7 +17186,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17216,7 +17220,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17253,7 +17257,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17276,7 +17280,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17300,7 +17304,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-nats", @@ -17324,7 +17328,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17359,7 +17363,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17387,7 +17391,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -17412,7 +17416,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17431,7 +17435,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-once-cell", @@ -17549,7 +17553,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.837.0" +version = "1.841.0" dependencies = [ "bytes", "futures", @@ -18371,9 +18375,9 @@ dependencies = [ [[package]] name = "zip" -version = "7.2.0" +version = "7.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c42e33efc22a0650c311c2ef19115ce232583abbe80850bc8b66509ebef02de0" +checksum = "cc12baa6db2b15a140161ce53d72209dacea594230798c24774139b54ecaa980" dependencies = [ "crc32fast", "indexmap 2.14.2", @@ -18426,9 +18430,9 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.1.1+zstd.1.5.7" +version = "2.1.2+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aeec9eaf2dffbbd09201e23bd0ffcbaa33bb8e9266a10734fd7ed90a85eca078" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" dependencies = [ "cc", "pkg-config", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 3daf4af371..1851f386c2 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.837.0" +version = "1.841.0" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.837.0" +version = "1.841.0" authors = ["Ruben Fiszel "] edition = "2021" @@ -226,7 +226,12 @@ all_sqlx_features = ["all_languages", "enterprise", "enterprise_saml", "embeddin "windmill-git-sync/all_sqlx_features"] [patch.crates-io] -# v0.8.6 plus one commit: `Pool::begin` is not cancel-safe on Postgres. sqlx raises the +# v0.8.6 plus the fix below and two `#[sqlx::test]`-only changes, both set in .cargo/config.toml: +# `SQLX_TEST_TEMPLATE` clones each test database from a template migrated once per migration +# set instead of migrating it per test, and `SQLX_TEST_MAX_CONNECTIONS` lifts the cap on the +# connections all test pools share. The rev is tagged `windmill-0.8.6-test-template-c1c5f1f` in +# the fork so it stays fetchable. +# The fix: `Pool::begin` is not cancel-safe on Postgres. sqlx raises the # transaction depth its rollback-on-drop guard keys on only *after* the BEGIN round trip, so # a cancelled caller (a disconnecting API client, a `timeout`, an aborted task) leaves the # session in a transaction nothing will end, and the pool hands that connection out again — @@ -239,13 +244,13 @@ all_sqlx_features = ["all_languages", "enterprise", "enterprise_saml", "embeddin # Changing any of this — a bump, a rebase of the fork, dropping these lines — still compiles # clean, so run the guard that actually checks the behaviour is still there: # cargo test -p windmill-common --test sqlx_begin_cancel_safe -- --ignored -sqlx = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-core = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-macros = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-macros-core = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-postgres = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-mysql = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-sqlite = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } +sqlx = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-core = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-macros = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-macros-core = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-postgres = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-mysql = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-sqlite = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } object_store = { git = "https://github.com/apache/arrow-rs-object-store", rev = "36752c975d4f29e20b57c91f81a10872dcd48ae7" } # Use tiberius main branch for libgssapi 0.8.1 fix (https://github.com/prisma/tiberius/issues/343) tiberius = { git = "https://github.com/prisma/tiberius", rev = "59db57960a14b422fb3a1309aa4aa47880896ff8" } @@ -501,6 +506,7 @@ mail-send = { version = "0.4.0", features = ["builder"], default-features=false urlencoding = "^2" quick-xml = { version = "^0.37", features = ["serialize"] } url = { version = "^2" , features = ["serde"]} +ipnet = "2" async-oauth2 = "0.5.1" reqwest = { version = "^0.13", features = ["json", "stream", "gzip", "multipart", "query", "form"] } # The reqwest object_store builds its HTTP clients with, for a custom `HttpConnector`. diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index b40437560a..37990aa852 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -664708fff04d4f9e0660bcae3edb307fb2c9481b +e922599943c472a6d0f736f629ae04081f866686 diff --git a/backend/migrations/20261016120000_ms_teams_oauth_key.down.sql b/backend/migrations/20261016120000_ms_teams_oauth_key.down.sql new file mode 100644 index 0000000000..77a3e3dc5f --- /dev/null +++ b/backend/migrations/20261016120000_ms_teams_oauth_key.down.sql @@ -0,0 +1,4 @@ +-- Fold edits made under ms_teams back into `teams`, which the previous version reads. +UPDATE global_settings +SET value = (value - 'ms_teams') || jsonb_build_object('teams', value -> 'ms_teams') +WHERE name = 'oauths' AND value ? 'ms_teams'; diff --git a/backend/migrations/20261016120000_ms_teams_oauth_key.up.sql b/backend/migrations/20261016120000_ms_teams_oauth_key.up.sql new file mode 100644 index 0000000000..ab2462db8b --- /dev/null +++ b/backend/migrations/20261016120000_ms_teams_oauth_key.up.sql @@ -0,0 +1,6 @@ +-- The Teams Entra app now lives under oauths.ms_teams (bot + Graph connect). Copy the old +-- `teams` entry and keep it, so servers still on the previous version keep working during a +-- rolling upgrade. +UPDATE global_settings +SET value = value || jsonb_build_object('ms_teams', value -> 'teams') +WHERE name = 'oauths' AND value ? 'teams' AND NOT value ? 'ms_teams'; diff --git a/backend/migrations/20261016160346_fork_storage_namespace.down.sql b/backend/migrations/20261016160346_fork_storage_namespace.down.sql new file mode 100644 index 0000000000..47c6b58649 --- /dev/null +++ b/backend/migrations/20261016160346_fork_storage_namespace.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS fork_storage_namespace; diff --git a/backend/migrations/20261016160346_fork_storage_namespace.up.sql b/backend/migrations/20261016160346_fork_storage_namespace.up.sql new file mode 100644 index 0000000000..247a9e2da9 --- /dev/null +++ b/backend/migrations/20261016160346_fork_storage_namespace.up.sql @@ -0,0 +1,24 @@ +-- Workspace storages a fork/dev workspace isolates from its parent: its writes land under +-- `__wm_forks//` of that storage, and its reads fall back to the parent's keys. +-- One row per (fork, storage) chosen isolated at fork creation; forks created before this +-- table have none and keep sharing the parent's keys. +-- +-- Deliberately NO foreign key to workspace(id), like fork_ducklake_namespace: rows are also the +-- cleanup ledger and must OUTLIVE the workspace row when deleting the prefix fails after the +-- delete commits. A recreated same-id fork would otherwise read the deleted fork's objects +-- under the deterministic prefix; fork creation retries leftover rows and refuses to proceed +-- while they cannot be cleaned. +CREATE TABLE fork_storage_namespace ( + workspace_id VARCHAR(50) NOT NULL, + -- '' = the default storage, else a `secondary_storage` name. + storage TEXT NOT NULL, + -- The storage's resolved identity at fork creation (`:`), so cleanup deletes the prefix from the storage the fork wrote to even if the + -- name is repointed later. + storage_ref TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (workspace_id, storage) +); + +GRANT ALL ON fork_storage_namespace TO windmill_user; +GRANT ALL ON fork_storage_namespace TO windmill_admin; diff --git a/backend/oauth_connect.json b/backend/oauth_connect.json index d3ac7a3809..611e3f7c17 100644 --- a/backend/oauth_connect.json +++ b/backend/oauth_connect.json @@ -317,6 +317,14 @@ "type": "web_server" } }, + "asana": { + "auth_url": "https://app.asana.com/-/oauth_authorize", + "token_url": "https://app.asana.com/-/oauth_token", + "scopes": ["default"], + "scope_options": [ + { "value": "default", "label": "Full permissions (the Asana app must be registered with Full permissions)" } + ] + }, "notion": { "auth_url": "https://api.notion.com/v1/oauth/authorize", "token_url": "https://api.notion.com/v1/oauth/token", @@ -380,6 +388,20 @@ } } }, + "shopify": { + "grant_types": ["client_credentials"], + "connect_config_template": { + "display_name": "Shopify", + "label": "Shopify store", + "placeholder": "your-store", + "help_url": "https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens/client-credentials-grant", + "token_url": "https://{instance}.myshopify.com/admin/oauth/access_token", + "strip_suffix": ".myshopify.com", + "resource_mapping": { + "store_name": "{instance}" + } + } + }, "sage_intacct": { "auth_url": "https://api.intacct.com/ia/api/v1/oauth2/authorize", "token_url": "https://api.intacct.com/ia/api/v1/oauth2/token", @@ -478,6 +500,101 @@ } } }, + "ms_teams": { + "req_body_auth": true, + "scopes": [ + "offline_access", + "User.Read", + "Team.ReadBasic.All", + "Channel.ReadBasic.All", + "ChannelMessage.Send", + "Chat.ReadWrite", + "OnlineMeetings.ReadWrite" + ], + "scope_options": [ + { + "value": "offline_access", + "label": "Stay connected (refresh token)" + }, + { + "value": "User.Read", + "label": "Read your profile" + }, + { + "value": "Team.ReadBasic.All", + "label": "List your teams" + }, + { + "value": "Channel.ReadBasic.All", + "label": "List channels" + }, + { + "value": "ChannelMessage.Send", + "label": "Post and reply in channels" + }, + { + "value": "Chat.ReadWrite", + "label": "Read, create and send in your chats" + }, + { + "value": "Chat.ReadBasic", + "label": "List your chats" + }, + { + "value": "Chat.Read", + "label": "Read your chat messages" + }, + { + "value": "Chat.Create", + "label": "Create chats" + }, + { + "value": "ChatMessage.Send", + "label": "Send chat messages" + }, + { + "value": "OnlineMeetings.ReadWrite", + "label": "Create and read online meetings" + }, + { + "value": "ChannelMessage.Read.All", + "label": "Read channel messages (admin consent)" + }, + { + "value": "ChannelMember.Read.All", + "label": "List channel members (admin consent)" + }, + { + "value": "TeamMember.Read.All", + "label": "List team members (admin consent)" + }, + { + "value": "Channel.Create", + "label": "Create channels (admin consent)" + }, + { + "value": "Schedule.Read.All", + "label": "Read Shifts schedules (admin consent)" + } + ], + "connect_config_template": { + "label": "Microsoft Entra tenant", + "placeholder": "organizations, or your tenant id", + "help_url": "https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols#endpoints", + "auth_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/authorize", + "token_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/token", + "req_body_auth": true, + "scopes": [ + "offline_access", + "User.Read", + "Team.ReadBasic.All", + "Channel.ReadBasic.All", + "ChannelMessage.Send", + "Chat.ReadWrite", + "OnlineMeetings.ReadWrite" + ] + } + }, "netsuite": { "connect_config_template": { "display_name": "NetSuite", @@ -593,5 +710,29 @@ "optional_scope": "tickets crm.objects.line_items.read crm.objects.line_items.write e-commerce crm.objects.quotes.read crm.objects.quotes.write crm.objects.leads.read crm.objects.leads.write crm.objects.custom.read crm.objects.custom.write crm.schemas.custom.read crm.lists.read crm.lists.write sales-email-read forms files content crm.objects.marketing_events.read marketing.campaigns.read communication_preferences.read_write automation automation.sequences.read automation.sequences.enrollments.write conversations.read conversations.write scheduler.meetings.meeting-link.read" }, "req_body_auth": true + }, + "zendesk": { + "grant_types": ["authorization_code", "client_credentials"], + "scopes": ["read", "write"], + "cc_scopes": ["read", "write"], + "scope_options": [ + { "value": "read", "label": "Read tickets, users, organizations and Help Center content" }, + { "value": "write", "label": "Create, update and delete tickets, users, organizations and Help Center content" } + ], + "req_body_auth": true, + "connect_config_template": { + "display_name": "Zendesk", + "label": "Zendesk subdomain", + "placeholder": "yourcompany (from yourcompany.zendesk.com)", + "help_url": "https://developer.zendesk.com/documentation/api-basics/authentication/oauth-migration/", + "auth_url": "https://{instance}.zendesk.com/oauth/authorizations/new", + "token_url": "https://{instance}.zendesk.com/oauth/tokens", + "scopes": ["read", "write"], + "req_body_auth": true, + "strip_suffix": ".zendesk.com", + "resource_mapping": { + "subdomain": "{instance}" + } + } } } diff --git a/backend/parsers/windmill-parser-bash/Cargo.toml b/backend/parsers/windmill-parser-bash/Cargo.toml index 4c7db23313..62f0c3fac3 100644 --- a/backend/parsers/windmill-parser-bash/Cargo.toml +++ b/backend/parsers/windmill-parser-bash/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_bash" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] regex-lite.workspace = true diff --git a/backend/parsers/windmill-parser-csharp/Cargo.toml b/backend/parsers/windmill-parser-csharp/Cargo.toml index 07b0259224..3a283d5895 100644 --- a/backend/parsers/windmill-parser-csharp/Cargo.toml +++ b/backend/parsers/windmill-parser-csharp/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_csharp" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-go/Cargo.toml b/backend/parsers/windmill-parser-go/Cargo.toml index ecba62cff4..4e8805aad7 100644 --- a/backend/parsers/windmill-parser-go/Cargo.toml +++ b/backend/parsers/windmill-parser-go/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_go" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-graphql/Cargo.toml b/backend/parsers/windmill-parser-graphql/Cargo.toml index 7f0a93b6f3..557fb56402 100644 --- a/backend/parsers/windmill-parser-graphql/Cargo.toml +++ b/backend/parsers/windmill-parser-graphql/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_graphql" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] regex-lite.workspace = true diff --git a/backend/parsers/windmill-parser-java/Cargo.toml b/backend/parsers/windmill-parser-java/Cargo.toml index 19809e3120..5a575b891b 100644 --- a/backend/parsers/windmill-parser-java/Cargo.toml +++ b/backend/parsers/windmill-parser-java/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_java" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-nu/Cargo.toml b/backend/parsers/windmill-parser-nu/Cargo.toml index c8c3e0d616..78034a3a79 100644 --- a/backend/parsers/windmill-parser-nu/Cargo.toml +++ b/backend/parsers/windmill-parser-nu/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_parser_nu" path = "./src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-php/Cargo.toml b/backend/parsers/windmill-parser-php/Cargo.toml index 8bd3182f91..37fcb70957 100644 --- a/backend/parsers/windmill-parser-php/Cargo.toml +++ b/backend/parsers/windmill-parser-php/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_php" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-py-asset/Cargo.toml b/backend/parsers/windmill-parser-py-asset/Cargo.toml index 84562dcf0e..46d5c55a42 100644 --- a/backend/parsers/windmill-parser-py-asset/Cargo.toml +++ b/backend/parsers/windmill-parser-py-asset/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_py_asset" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-py-imports/Cargo.toml b/backend/parsers/windmill-parser-py-imports/Cargo.toml index 2ef83f5ac9..be0c1062b7 100644 --- a/backend/parsers/windmill-parser-py-imports/Cargo.toml +++ b/backend/parsers/windmill-parser-py-imports/Cargo.toml @@ -7,6 +7,9 @@ authors.workspace = true [lib] name = "windmill_parser_py_imports" path = "./src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] regex-lite.workspace = true diff --git a/backend/parsers/windmill-parser-py/Cargo.toml b/backend/parsers/windmill-parser-py/Cargo.toml index 6971fe8fcd..1f34643572 100644 --- a/backend/parsers/windmill-parser-py/Cargo.toml +++ b/backend/parsers/windmill-parser-py/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_py" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-r/Cargo.toml b/backend/parsers/windmill-parser-r/Cargo.toml index 42701f9c12..d489bc966d 100644 --- a/backend/parsers/windmill-parser-r/Cargo.toml +++ b/backend/parsers/windmill-parser-r/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_r" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-ruby/Cargo.toml b/backend/parsers/windmill-parser-ruby/Cargo.toml index 779b0116a0..ca996528b1 100644 --- a/backend/parsers/windmill-parser-ruby/Cargo.toml +++ b/backend/parsers/windmill-parser-ruby/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_ruby" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-rust/Cargo.toml b/backend/parsers/windmill-parser-rust/Cargo.toml index e1dcf84449..e4654590ff 100644 --- a/backend/parsers/windmill-parser-rust/Cargo.toml +++ b/backend/parsers/windmill-parser-rust/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_rust" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-sql-asset/Cargo.toml b/backend/parsers/windmill-parser-sql-asset/Cargo.toml index 73835b2c06..5b22c38350 100644 --- a/backend/parsers/windmill-parser-sql-asset/Cargo.toml +++ b/backend/parsers/windmill-parser-sql-asset/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_sql_asset" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-sql/Cargo.toml b/backend/parsers/windmill-parser-sql/Cargo.toml index 143b02a2cc..7963de819c 100644 --- a/backend/parsers/windmill-parser-sql/Cargo.toml +++ b/backend/parsers/windmill-parser-sql/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_sql" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] regex-lite.workspace = true diff --git a/backend/parsers/windmill-parser-ts-asset/Cargo.toml b/backend/parsers/windmill-parser-ts-asset/Cargo.toml index f1c668d4eb..17a0279bdc 100644 --- a/backend/parsers/windmill-parser-ts-asset/Cargo.toml +++ b/backend/parsers/windmill-parser-ts-asset/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_ts_asset" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen.workspace = true diff --git a/backend/parsers/windmill-parser-ts/Cargo.toml b/backend/parsers/windmill-parser-ts/Cargo.toml index 5f04b14f3b..36dce90090 100644 --- a/backend/parsers/windmill-parser-ts/Cargo.toml +++ b/backend/parsers/windmill-parser-ts/Cargo.toml @@ -8,6 +8,9 @@ authors.workspace = true [lib] name = "windmill_parser_ts" path = "./src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen.workspace = true diff --git a/backend/parsers/windmill-parser-ts/src/lib.rs b/backend/parsers/windmill-parser-ts/src/lib.rs index ac75080994..8059851707 100644 --- a/backend/parsers/windmill-parser-ts/src/lib.rs +++ b/backend/parsers/windmill-parser-ts/src/lib.rs @@ -189,7 +189,20 @@ pub fn parse_expr_for_imports(code: &str, skip_type_only: bool) -> anyhow::Resul /// // Returns: ["f/utils"] /// ``` pub fn parse_relative_imports(code: &str, path: &str) -> anyhow::Result> { - let imports = parse_expr_for_imports(code, false)?; + resolve_relative_imports(code, path, false) +} + +/// [`parse_relative_imports`] without type-only imports, which are erased before the code runs. +pub fn parse_runtime_relative_imports(code: &str, path: &str) -> anyhow::Result> { + resolve_relative_imports(code, path, true) +} + +fn resolve_relative_imports( + code: &str, + path: &str, + skip_type_only: bool, +) -> anyhow::Result> { + let imports = parse_expr_for_imports(code, skip_type_only)?; let script_dir = path.rsplit_once('/').map(|(dir, _)| dir).unwrap_or(""); let mut resolved: Vec = imports diff --git a/backend/parsers/windmill-parser-ts/tests/tests.rs b/backend/parsers/windmill-parser-ts/tests/tests.rs index b4abc23488..8b9587d3a2 100644 --- a/backend/parsers/windmill-parser-ts/tests/tests.rs +++ b/backend/parsers/windmill-parser-ts/tests/tests.rs @@ -4,7 +4,7 @@ mod tests { use windmill_parser::{Arg, MainArgSignature, ObjectProperty, ObjectType, Typ}; use windmill_parser_ts::{ parse_deno_signature, parse_expr_for_imports, parse_relative_imports, - remove_pinned_import_specifiers, + parse_runtime_relative_imports, remove_pinned_import_specifiers, }; /// The server parses defaults natively, where a non-JSON literal cannot be evaluated @@ -944,6 +944,19 @@ export const label = "pkg@1.2.3"; assert_eq!(result, vec!["f/folder/helper"]); } + #[test] + fn test_runtime_relative_imports_skip_type_only() { + let code = r#" + import type { Shape } from "./types"; + import { helper } from "./helper"; + export async function main(s: Shape) { return helper(s); } + "#; + let result = parse_runtime_relative_imports(code, "f/folder/script").unwrap(); + assert_eq!(result, vec!["f/folder/helper"]); + let all = parse_relative_imports(code, "f/folder/script").unwrap(); + assert_eq!(all, vec!["f/folder/helper", "f/folder/types"]); + } + #[test] fn test_relative_imports_double_dot() { let code = r#" diff --git a/backend/parsers/windmill-parser-wac/Cargo.toml b/backend/parsers/windmill-parser-wac/Cargo.toml index 21ee286db9..5dccb0aa0a 100644 --- a/backend/parsers/windmill-parser-wac/Cargo.toml +++ b/backend/parsers/windmill-parser-wac/Cargo.toml @@ -7,6 +7,9 @@ authors.workspace = true [lib] name = "windmill_parser_wac" path = "./src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] ruff_python_parser.workspace = true diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index 9b266a21ee..f89fa1d49a 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.837.0" +version = "1.841.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.837.0" +version = "1.841.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.837.0" +version = "1.841.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.837.0" +version = "1.841.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 3de0a1353e..d6c0389840 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.837.0" +version = "1.841.0" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/parsers/windmill-parser-yaml/Cargo.toml b/backend/parsers/windmill-parser-yaml/Cargo.toml index eb2f16fccc..5c3b3e2760 100644 --- a/backend/parsers/windmill-parser-yaml/Cargo.toml +++ b/backend/parsers/windmill-parser-yaml/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_parser_yaml" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] yaml-rust.workspace = true diff --git a/backend/parsers/windmill-parser/Cargo.toml b/backend/parsers/windmill-parser/Cargo.toml index 97b6c6da58..842a94d917 100644 --- a/backend/parsers/windmill-parser/Cargo.toml +++ b/backend/parsers/windmill-parser/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] serde = { version = "1.0", features = ["derive"] } diff --git a/backend/parsers/windmill-sql-datatype-parser-wasm/Cargo.toml b/backend/parsers/windmill-sql-datatype-parser-wasm/Cargo.toml index 7d66d56ade..e4d67e84a7 100644 --- a/backend/parsers/windmill-sql-datatype-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-sql-datatype-parser-wasm/Cargo.toml @@ -9,6 +9,8 @@ authors.workspace = true crate-type = ["cdylib"] name = "windmill_sql_datatype_parser_wasm" path = "./src/lib.rs" +# src/ has no unit tests: remove this line before adding one, or cargo test never runs it. +test = false [dev-dependencies] wasm-bindgen-test.workspace = true diff --git a/backend/src/main.rs b/backend/src/main.rs index fd953213a4..ef9961ba57 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -44,12 +44,13 @@ use windmill_common::{ CRITICAL_ALERTS_ON_TOKEN_EXPIRY_SETTING, CRITICAL_ALERT_MUTE_UI_SETTING, CRITICAL_ALERT_MUTE_ZOMBIE_JOB_RESTART_SETTING, CRITICAL_ERROR_CHANNELS_SETTING, CUSTOM_TAGS_SETTING, DEFAULT_TAGS_PER_WORKSPACE_SETTING, DEFAULT_TAGS_WORKSPACES_SETTING, - DEPENDENCY_JOB_TAG_SETTING, DISABLE_PASSWORD_LOGIN_SETTING, EMAIL_DOMAIN_SETTING, - ENV_SETTINGS, EXPOSE_DEBUG_METRICS_SETTING, EXPOSE_METRICS_SETTING, - EXTRA_PIP_INDEX_URL_SETTING, FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX_SETTING, - HTTP_ROUTE_DEFAULT_ALLOWED_ORIGINS_SETTING, HTTP_ROUTE_WORKSPACED_ROUTE_SETTING, - HUB_API_SECRET_SETTING, HUB_BASE_URL_SETTING, INDEXER_SETTING, - INSTANCE_EVENTS_WEBHOOK_SETTING, INSTANCE_PYTHON_VERSION_SETTING, + DEPENDENCY_JOB_TAG_SETTING, DEV_WORKSPACE_ISOLATION_SETTING, + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING, DEV_WORKSPACE_TAG_SUFFIX_SETTING, + DISABLE_PASSWORD_LOGIN_SETTING, EMAIL_DOMAIN_SETTING, ENV_SETTINGS, + EXPOSE_DEBUG_METRICS_SETTING, EXPOSE_METRICS_SETTING, EXTRA_PIP_INDEX_URL_SETTING, + FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX_SETTING, HTTP_ROUTE_DEFAULT_ALLOWED_ORIGINS_SETTING, + HTTP_ROUTE_WORKSPACED_ROUTE_SETTING, HUB_API_SECRET_SETTING, HUB_BASE_URL_SETTING, + INDEXER_SETTING, INSTANCE_EVENTS_WEBHOOK_SETTING, INSTANCE_PYTHON_VERSION_SETTING, JOB_DEFAULT_TIMEOUT_SECS_SETTING, JOB_ISOLATION_SETTING, JWT_SECRET_SETTING, KEEP_JOB_DIR_SETTING, LICENSE_KEY_SETTING, MAVEN_REPOS_SETTING, MAVEN_SETTINGS_XML_SETTING, MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING, MONITOR_LOGS_ON_OBJECT_STORE_SETTING, @@ -129,7 +130,9 @@ use windmill_worker::{ use crate::monitor::{ initial_load, load_concurrency_key_max_queued, load_dependency_job_tag, - load_disable_password_login, load_fork_workspace_tag_append_fork_suffix, load_keep_job_dir, + load_dev_workspace_isolation, load_dev_workspace_isolation_skip_non_dev_forks, + load_dev_workspace_tag_suffix, load_disable_password_login, + load_fork_workspace_tag_append_fork_suffix, load_keep_job_dir, load_mcp_disable_token_query_param, load_metrics_debug_enabled, load_preview_tags_override, load_require_preexisting_user, load_retention_period_overrides, load_tag_per_workspace_enabled, load_tag_per_workspace_workspaces, load_workspace_fairness_duration_secs, @@ -683,6 +686,29 @@ async fn windmill_main() -> anyhow::Result<()> { _ => {} } + // Before `num_workers`: it reads `WORKER_GROUP`, which an agent authenticating with a + // workload identity token only learns from the server. + let agent_setup = if mode == Mode::Agent { + let agent_config = match AgentConfig::from_env() { + Ok(config) => config, + Err(e) => { + eprintln!("{e}"); + std::process::exit(1); + } + }; + let suffix = resolve_worker_suffix(&hostname, 1)?; + if let Err(e) = agent_config.resolve_workload_identity(&suffix).await { + eprintln!( + "Agent worker could not authenticate with its workload identity token, check \ + AGENT_IDENTITY_TOKEN_FILE and BASE_INTERNAL_URL (the reason is in the server log): {e:#}" + ); + std::process::exit(1); + } + Some((agent_config, suffix)) + } else { + None + }; + #[allow(unused_mut)] let mut num_workers = if mode == Mode::Server || mode == Mode::Indexer || mode == Mode::MCP { 0 @@ -735,19 +761,11 @@ async fn windmill_main() -> anyhow::Result<()> { .and_then(|x| x.parse().ok()) .unwrap_or(IpAddr::from(default_bind_addr)); - let (conn, first_suffix, agent_config) = if mode == Mode::Agent { - let agent_config = match AgentConfig::from_env() { - Ok(config) => config, - Err(e) => { - tracing::error!("{e}"); - std::process::exit(1); - } - }; + let (conn, first_suffix, agent_config) = if let Some((agent_config, suffix)) = agent_setup { tracing::info!( "Creating http client for cluster using base internal url {}", agent_config.base_internal_url ); - let suffix = resolve_worker_suffix(&hostname, 1)?; ( Connection::Http(agent_config.build_http_client(&suffix)), Some(suffix), @@ -846,6 +864,8 @@ async fn windmill_main() -> anyhow::Result<()> { let worker_mode = num_workers > 0; if worker_mode { + windmill_common::worker::warn_secret_shaped_whitelist_envs(); + #[cfg(any(target_os = "linux"))] if let Err(e) = disable_oom_group() { tracing::warn!( @@ -991,7 +1011,7 @@ Windmill Community Edition {GIT_VERSION} tracing::error!("Failed to reload license key: {err:#}"); if is_agent { tracing::error!( - "Agent worker cannot connect to server. Please check AGENT_TOKEN and BASE_INTERNAL_URL" + "Agent worker cannot connect to server. Please check AGENT_TOKEN (or AGENT_IDENTITY_TOKEN_FILE) and BASE_INTERNAL_URL" ); std::process::exit(1); } @@ -1052,12 +1072,8 @@ Windmill Community Edition {GIT_VERSION} // Before the first load: it can sign a token for instance object storage. #[cfg(all(feature = "enterprise", feature = "openidconnect", feature = "private"))] - windmill_common::oidc_ee::init_oidc_signing( - &conn, - server_mode, - killpill_rx.resubscribe(), - ) - .await?; + windmill_common::oidc_ee::init_oidc_signing(&conn, server_mode, killpill_rx.resubscribe()) + .await?; initial_load( &conn, @@ -1881,6 +1897,21 @@ async fn process_notify_event( tracing::error!("Error loading dependency job tag: {e:#}"); } } + DEV_WORKSPACE_ISOLATION_SETTING => { + if let Err(e) = load_dev_workspace_isolation(db).await { + tracing::error!("Error loading dev workspace isolation: {e:#}"); + } + } + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING => { + if let Err(e) = load_dev_workspace_isolation_skip_non_dev_forks(db).await { + tracing::error!("Error loading dev workspace isolation of forks: {e:#}"); + } + } + DEV_WORKSPACE_TAG_SUFFIX_SETTING => match load_dev_workspace_tag_suffix(db).await { + Ok(true) if worker_mode => reload_worker_config(db, tx.clone(), true).await, + Ok(_) => (), + Err(e) => tracing::error!("Error loading dev workspace tag suffix: {e:#}"), + }, WORKSPACE_FAIRNESS_ENABLED_SETTING => { if let Err(e) = load_workspace_fairness_enabled(db).await { tracing::error!("Error loading workspace fairness enabled: {e:#}"); diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index 4fae6f34ab..827c092529 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -60,17 +60,19 @@ use windmill_common::{ CRITICAL_ALERTS_ON_DB_OVERSIZE_SETTING, CRITICAL_ALERTS_ON_TOKEN_EXPIRY_SETTING, CRITICAL_ALERT_MUTE_UI_SETTING, CRITICAL_ALERT_MUTE_ZOMBIE_JOB_RESTART_SETTING, CRITICAL_ERROR_CHANNELS_SETTING, CUSTOM_TAGS_SETTING, DEFAULT_TAGS_PER_WORKSPACE_SETTING, - DEFAULT_TAGS_WORKSPACES_SETTING, DEPENDENCY_JOB_TAG_SETTING, DISABLE_PASSWORD_LOGIN, - DISABLE_PASSWORD_LOGIN_SETTING, EXPOSE_DEBUG_METRICS_SETTING, EXPOSE_METRICS_SETTING, - EXTRA_PIP_INDEX_URL_SETTING, FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX_SETTING, - HUB_API_SECRET_SETTING, HUB_BASE_URL_SETTING, INSTANCE_PYTHON_VERSION_SETTING, - JOB_DEFAULT_TIMEOUT_SECS_SETTING, JOB_ISOLATION_SETTING, JWT_SECRET_SETTING, - KEEP_JOB_DIR_SETTING, LICENSE_KEY_SETTING, MCP_DISABLE_TOKEN_QUERY_PARAM, - MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING, MONITOR_LOGS_ON_OBJECT_STORE_SETTING, NPMRC_SETTING, - NPM_CONFIG_REGISTRY_SETTING, NSJAIL_TMPFS_SIZE_MB_SETTING, NSJAIL_TMP_BACKING_SETTING, - NUGET_CONFIG_SETTING, OTEL_SETTING, OTEL_TRACES_RETENTION_SECS_SETTING, - OTEL_TRACING_PROXY_SETTING, PIP_INDEX_URL_SETTING, POWERSHELL_REPO_PAT_SETTING, - POWERSHELL_REPO_URL_SETTING, PREVIEW_TAGS_OVERRIDE_SETTING, REQUEST_SIZE_LIMIT_SETTING, + DEFAULT_TAGS_WORKSPACES_SETTING, DEPENDENCY_JOB_TAG_SETTING, + DEV_WORKSPACE_ISOLATION_SETTING, DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING, + DEV_WORKSPACE_TAG_SUFFIX_SETTING, DISABLE_PASSWORD_LOGIN, DISABLE_PASSWORD_LOGIN_SETTING, + EXPOSE_DEBUG_METRICS_SETTING, EXPOSE_METRICS_SETTING, EXTRA_PIP_INDEX_URL_SETTING, + FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX_SETTING, HUB_API_SECRET_SETTING, + HUB_BASE_URL_SETTING, INSTANCE_PYTHON_VERSION_SETTING, JOB_DEFAULT_TIMEOUT_SECS_SETTING, + JOB_ISOLATION_SETTING, JWT_SECRET_SETTING, KEEP_JOB_DIR_SETTING, LICENSE_KEY_SETTING, + MCP_DISABLE_TOKEN_QUERY_PARAM, MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING, + MONITOR_LOGS_ON_OBJECT_STORE_SETTING, NPMRC_SETTING, NPM_CONFIG_REGISTRY_SETTING, + NSJAIL_TMPFS_SIZE_MB_SETTING, NSJAIL_TMP_BACKING_SETTING, NUGET_CONFIG_SETTING, + OTEL_SETTING, OTEL_TRACES_RETENTION_SECS_SETTING, OTEL_TRACING_PROXY_SETTING, + PIP_INDEX_URL_SETTING, POWERSHELL_REPO_PAT_SETTING, POWERSHELL_REPO_URL_SETTING, + PREVIEW_TAGS_OVERRIDE_SETTING, REQUEST_SIZE_LIMIT_SETTING, REQUIRE_PREEXISTING_USER_FOR_OAUTH_SETTING, RETENTION_PERIOD_SECS_SETTING, SAML_METADATA_SETTING, SANDBOX_IMAGE_CACHE_MAX_MB_SETTING, SANDBOX_IMAGE_DEFAULT_REGISTRY_SETTING, SANDBOX_IMAGE_MAX_SIZE_MB_SETTING, @@ -89,15 +91,18 @@ use windmill_common::{ users::truncate_token, utils::{empty_as_none, now_from_db, report_critical_error, Mode, HUB_API_SECRET}, worker::{ - load_env_vars, load_init_bash_from_env, load_periodic_bash_script_from_env, - load_periodic_bash_script_interval_from_env, load_whitelist_env_vars_from_env, - load_worker_config, store_pull_query, store_suspended_pull_query, Connection, WorkerConfig, - CLOUD_HOSTED, CONCURRENCY_KEY_MAX_QUEUED, CONCURRENCY_KEY_MAX_QUEUED_DEFAULT, - DEFAULT_TAGS_PER_WORKSPACE, DEFAULT_TAGS_WORKSPACES, DEPENDENCY_JOB_TAG, - FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX, INDEXER_CONFIG, PREVIEW_TAGS_OVERRIDE, SMTP_CONFIG, - WINDMILL_DIR, WORKER_CONFIG, WORKER_GROUP, WORKSPACE_FAIRNESS_DURATION_SECS, - WORKSPACE_FAIRNESS_ENABLED, WORKSPACE_FAIRNESS_MAX_PERCENT, WORKSPACE_FAIRNESS_MIN_TOTAL, - WORKSPACE_MAX_QUEUED_JOBS, WORKSPACE_MAX_QUEUED_JOBS_DEFAULT, + is_valid_dev_workspace_tag_suffix, load_env_vars, load_init_bash_from_env, + load_periodic_bash_script_from_env, load_periodic_bash_script_interval_from_env, + load_whitelist_env_vars_from_env, load_worker_config, store_pull_query, + store_suspended_pull_query, Connection, WorkerConfig, CLOUD_HOSTED, + CONCURRENCY_KEY_MAX_QUEUED, CONCURRENCY_KEY_MAX_QUEUED_DEFAULT, + DEFAULT_DEV_WORKSPACE_TAG_SUFFIX, DEFAULT_TAGS_PER_WORKSPACE, DEFAULT_TAGS_WORKSPACES, + DEPENDENCY_JOB_TAG, DEV_WORKSPACE_ISOLATION, DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS, + DEV_WORKSPACE_TAG_SUFFIX, FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX, INDEXER_CONFIG, + PREVIEW_TAGS_OVERRIDE, SMTP_CONFIG, WINDMILL_DIR, WORKER_CONFIG, WORKER_GROUP, + WORKSPACE_FAIRNESS_DURATION_SECS, WORKSPACE_FAIRNESS_ENABLED, + WORKSPACE_FAIRNESS_MAX_PERCENT, WORKSPACE_FAIRNESS_MIN_TOTAL, WORKSPACE_MAX_QUEUED_JOBS, + WORKSPACE_MAX_QUEUED_JOBS_DEFAULT, }, KillpillSender, AUDIT_LOG_RETENTION_DAYS, BASE_URL, CRITICAL_ALERTS_ON_DB_OVERSIZE, CRITICAL_ALERTS_ON_TOKEN_EXPIRY, CRITICAL_ALERT_MUTE_UI_ENABLED, @@ -321,6 +326,18 @@ pub async fn initial_load( pass.setting(DEPENDENCY_JOB_TAG_SETTING, false, |v| async move { apply_dependency_job_tag(v) }); + // Ahead of the worker config reload below, which expands the tags with it. + pass.setting(DEV_WORKSPACE_TAG_SUFFIX_SETTING, false, |v| async move { + apply_dev_workspace_tag_suffix(v); + }); + pass.setting(DEV_WORKSPACE_ISOLATION_SETTING, false, |v| async move { + apply_dev_workspace_isolation(v) + }); + pass.setting( + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING, + false, + |v| async move { apply_dev_workspace_isolation_skip_non_dev_forks(v) }, + ); // Load per-workspace retention overrides before the first cleanup tick so a fresh server // never sweeps globally without honoring configured longer-retention workspaces. @@ -1127,6 +1144,53 @@ pub fn apply_fork_workspace_tag_append_fork_suffix(value: Option error::Result { + let v = load_value_from_global_settings(db, DEV_WORKSPACE_TAG_SUFFIX_SETTING).await?; + Ok(apply_dev_workspace_tag_suffix(v)) +} + +pub fn apply_dev_workspace_tag_suffix(value: Option) -> bool { + let suffix = match value { + Some(serde_json::Value::String(t)) if !t.trim().is_empty() => t.trim().to_string(), + _ => DEFAULT_DEV_WORKSPACE_TAG_SUFFIX.to_string(), + }; + if !is_valid_dev_workspace_tag_suffix(&suffix) { + tracing::error!("Ignoring invalid dev workspace tag suffix {suffix:?}"); + return false; + } + let prev = DEV_WORKSPACE_TAG_SUFFIX.swap(std::sync::Arc::new(suffix.clone())); + *prev != suffix +} + +pub async fn load_dev_workspace_isolation(db: &DB) -> error::Result<()> { + let v = load_value_from_global_settings(db, DEV_WORKSPACE_ISOLATION_SETTING).await?; + apply_dev_workspace_isolation(v); + Ok(()) +} + +pub fn apply_dev_workspace_isolation(value: Option) { + DEV_WORKSPACE_ISOLATION.store( + matches!(value, Some(serde_json::Value::Bool(true))), + Ordering::Relaxed, + ); +} + +pub async fn load_dev_workspace_isolation_skip_non_dev_forks(db: &DB) -> error::Result<()> { + let v = load_value_from_global_settings(db, DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING) + .await?; + apply_dev_workspace_isolation_skip_non_dev_forks(v); + Ok(()) +} + +pub fn apply_dev_workspace_isolation_skip_non_dev_forks(value: Option) { + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS.store( + matches!(value, Some(serde_json::Value::Bool(true))), + Ordering::Relaxed, + ); +} + pub async fn reload_critical_alert_mute_ui_setting(conn: &Connection) -> error::Result<()> { let v = load_value_from_global_settings_with_conn(conn, CRITICAL_ALERT_MUTE_UI_SETTING, true) .await?; diff --git a/backend/tests/dev_workspace_tag_suffix.rs b/backend/tests/dev_workspace_tag_suffix.rs new file mode 100644 index 0000000000..1a61bee8aa --- /dev/null +++ b/backend/tests/dev_workspace_tag_suffix.rs @@ -0,0 +1,208 @@ +//! Sets the process-wide `DEV_WORKSPACE_ISOLATION`, so it lives in its own test binary: any other +//! test pushing a job in the same process would land on a suffixed tag. + +use std::collections::HashMap; + +use sqlx::{Pool, Postgres}; +use windmill_common::{ + jobs::{JobPayload, RawCode}, + runnable_settings::{ConcurrencySettings, DebouncingSettings}, + scripts::{ScriptHash, ScriptLang}, + worker::{DEV_WORKSPACE_ISOLATION, DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS}, +}; +use windmill_queue::{PushArgs, PushIsolationLevel}; + +async fn pushed_tag( + db: &Pool, + workspace_id: &str, + payload: JobPayload, + tag: Option<&str>, +) -> String { + try_pushed_tag(db, workspace_id, payload, tag) + .await + .expect("push must succeed") +} + +async fn try_pushed_tag( + db: &Pool, + workspace_id: &str, + payload: JobPayload, + tag: Option<&str>, +) -> Result { + let args = HashMap::new(); + let (id, tx) = windmill_queue::push( + db, + PushIsolationLevel::IsolatedRoot(db.clone()), + workspace_id, + payload, + PushArgs::from(&args), + "test-user", + "test@windmill.dev", + "u/test-user".to_string(), + None, + None, + None, + None, + None, + None, + None, + None, + false, + false, + None, + true, + tag.map(str::to_string), + None, + None, + None, + None, + false, + None, + None, + None, + None, + ) + .await?; + tx.commit().await.unwrap(); + Ok(sqlx::query_scalar("SELECT tag FROM v2_job WHERE id = $1") + .bind(id) + .fetch_one(db) + .await + .unwrap()) +} + +fn preview() -> JobPayload { + JobPayload::Code(RawCode { + hash: None, + content: "echo hi".to_string(), + path: None, + language: ScriptLang::Bash, + lock: None, + concurrency_settings: ConcurrencySettings::default().into(), + debouncing_settings: DebouncingSettings::default(), + cache_ttl: None, + cache_ignore_s3_path: None, + dedicated_worker: None, + modules: None, + tag: None, + }) +} + +#[sqlx::test(fixtures("base"))] +async fn dev_workspace_and_fork_jobs_run_on_suffixed_tags(db: Pool) { + DEV_WORKSPACE_ISOLATION.store(true, std::sync::atomic::Ordering::Relaxed); + + // A dev workspace, a fork of it, a fork whose parent was deleted (`ON DELETE SET NULL`), and a + // fork of the root with a fork of its own. + sqlx::query( + "INSERT INTO workspace (id, name, owner, parent_workspace_id, is_dev_workspace) VALUES + ('staging', 'staging', 'test-user', 'test-workspace', true), + ('wm-fork-a', 'fork', 'test-user', 'staging', false), + ('wm-fork-orphan', 'orphan', 'test-user', NULL, false), + ('wm-fork-root', 'root fork', 'test-user', 'test-workspace', false), + ('wm-fork-root-2', 'root fork 2', 'test-user', 'wm-fork-root', false), + ('archived-dev', 'archived dev', 'test-user', 'test-workspace', false), + ('wm-fork-of-archived', 'fork of archived dev', 'test-user', 'archived-dev', false)", + ) + .execute(&db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO workspace_settings (workspace_id) VALUES + ('staging'), ('wm-fork-a'), ('wm-fork-orphan'), ('wm-fork-root'), ('wm-fork-root-2'), + ('archived-dev'), ('wm-fork-of-archived')", + ) + .execute(&db) + .await + .unwrap(); + + for (workspace, tag, expected) in [ + ("test-workspace", None, "bash"), + ("test-workspace", Some("gpu"), "gpu"), + ("staging", None, "bash-dev"), + ("staging", Some("gpu"), "gpu-dev"), + // A tag inherited from a dev job (a flow step, an agent's tool) is not suffixed twice. + ("staging", Some("gpu-dev"), "gpu-dev"), + ("wm-fork-a", None, "bash-dev"), + ("wm-fork-orphan", None, "bash-dev"), + ("wm-fork-root", None, "bash-dev"), + ] { + assert_eq!( + pushed_tag(&db, workspace, preview(), tag).await, + expected, + "{workspace} with tag {tag:?}" + ); + } + + // Only the forks whose lineage holds no dev workspace leave isolation. An orphaned fork's + // lineage is unknown, and so is that of a fork of an archived dev workspace (archiving clears + // `is_dev_workspace`), so both stay. + sqlx::query("UPDATE workspace SET deleted = true WHERE id = 'archived-dev'") + .execute(&db) + .await + .unwrap(); + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS.store(true, std::sync::atomic::Ordering::Relaxed); + for (workspace, expected) in [ + ("wm-fork-root", "bash"), + ("wm-fork-root-2", "bash"), + ("staging", "bash-dev"), + ("wm-fork-a", "bash-dev"), + ("wm-fork-orphan", "bash-dev"), + ("wm-fork-of-archived", "bash-dev"), + ] { + assert_eq!( + pushed_tag(&db, workspace, preview(), None).await, + expected, + "{workspace} with non-dev forks not isolated" + ); + } + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS.store(false, std::sync::atomic::Ordering::Relaxed); + + // A dedicated worker tag already names the workspace, and its worker is placed by hand. + let dedicated = JobPayload::ScriptHash { + hash: ScriptHash(123412), + path: "f/system/hello".to_string(), + cache_ttl: None, + cache_ignore_s3_path: None, + dedicated_worker: Some(true), + language: ScriptLang::Bun, + priority: None, + apply_preprocessor: false, + concurrency_settings: ConcurrencySettings::default(), + debouncing_settings: DebouncingSettings::default(), + labels: None, + job_token_scopes: None, + }; + assert_eq!( + pushed_tag(&db, "staging", dedicated, None).await, + "staging:f/system/hello" + ); + + // A hashed dedicated tag keeps only a prefix of its workspace id: a dev workspace sharing that + // prefix does not get to use another workspace's dedicated worker. + let root = "a".repeat(40); + let dev = format!("{root}-dev"); + sqlx::query( + "INSERT INTO workspace (id, name, owner, parent_workspace_id, is_dev_workspace) + VALUES ($1, 'root', 'test-user', NULL, false), ($2, 'dev', 'test-user', $1, true)", + ) + .bind(&root) + .bind(&dev) + .execute(&db) + .await + .unwrap(); + sqlx::query("INSERT INTO workspace_settings (workspace_id) VALUES ($1), ($2)") + .bind(&root) + .bind(&dev) + .execute(&db) + .await + .unwrap(); + let root_dedicated = + windmill_common::worker::dedicated_worker_tag(&root, "f/some/long/script/path"); + assert!( + try_pushed_tag(&db, &dev, preview(), Some(&root_dedicated)) + .await + .is_err(), + "{root_dedicated} must not stay unsuffixed, and suffixed it no longer fits a job tag" + ); +} diff --git a/backend/tests/error_handler.rs b/backend/tests/error_handler.rs deleted file mode 100644 index 2e10006d2f..0000000000 --- a/backend/tests/error_handler.rs +++ /dev/null @@ -1,480 +0,0 @@ -use sqlx::{Pool, Postgres}; - -use windmill_test_utils::*; - -/// Test that workspace error handler can be set and removed via database operations -#[cfg(feature = "deno_core")] -#[sqlx::test(fixtures("base"))] -async fn test_error_handler_settings(db: Pool) -> anyhow::Result<()> { - initialize_tracing().await; - - let _server = ApiServer::start(db.clone()).await?; - - // Initially error_handler should be NULL - let initial = sqlx::query_scalar!( - r#"SELECT error_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert!(initial.is_none()); - - // Set error handler with all options - sqlx::query!( - r#" - UPDATE workspace_settings - SET error_handler = '{"path": "script/f/test/error_handler", "extra_args": {"notify": true}, "muted_on_cancel": true, "muted_on_user_path": false}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - let after_set = sqlx::query_scalar!( - r#"SELECT error_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert_eq!(after_set, Some("script/f/test/error_handler".to_string())); - - // Verify extra_args - let extra_args = sqlx::query_scalar!( - r#"SELECT error_handler->'extra_args' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert!(extra_args.is_some()); - - // Verify muted_on_cancel - let muted_on_cancel = sqlx::query_scalar!( - r#"SELECT (error_handler->>'muted_on_cancel')::boolean FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert_eq!(muted_on_cancel, Some(true)); - - // Verify muted_on_user_path - let muted_on_user_path = sqlx::query_scalar!( - r#"SELECT (error_handler->>'muted_on_user_path')::boolean FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert_eq!(muted_on_user_path, Some(false)); - - // Remove error handler - sqlx::query!( - r#" - UPDATE workspace_settings - SET error_handler = NULL - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - let after_remove = sqlx::query_scalar!( - r#"SELECT error_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert!(after_remove.is_none()); - - Ok(()) -} - -/// Test that a failed job triggers the workspace error handler -#[cfg(all(feature = "deno_core", feature = "enterprise", feature = "private"))] -#[sqlx::test(fixtures("base"))] -async fn test_error_handler_triggered_on_failure(db: Pool) -> anyhow::Result<()> { - use windmill_common::jobs::JobPayload; - use windmill_common::runnable_settings::{ConcurrencySettings, DebouncingSettings}; - use windmill_common::scripts::{ScriptHash, ScriptLang}; - - initialize_tracing().await; - - let server = ApiServer::start(db.clone()).await?; - - // Create the error handler script - let error_handler_code = r#" -export async function main(path: string, email: string, job_id: string, is_flow: boolean, workspace_id: string, error: any) { - console.log("Error handler called for job:", job_id); - return { handled: true, original_path: path }; -} -"#; - - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', 1111111111, 'f/test/error_handler', $1, 'bun', 'script', 'test-user', '{}', 'Error handler script', 'Handles failed job completions', E'{}\n//bun.lock\n') - "#, - error_handler_code - ) - .execute(&db) - .await?; - - // Create a script that will fail - let failing_script_code = "export function main() { throw new Error('intentional failure'); }"; - let failing_script_hash: i64 = 2222222222; - - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', $1, 'f/test/failing_script', $2, 'bun', 'script', 'test-user', '{}', 'Failing test script', 'A script that always fails', E'{}\n//bun.lock\n') - "#, - failing_script_hash, - failing_script_code - ) - .execute(&db) - .await?; - - // Set up the error handler in workspace_settings - sqlx::query!( - r#" - UPDATE workspace_settings - SET error_handler = '{"path": "script/f/test/error_handler"}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - // Create the error_handler group - sqlx::query!( - r#" - INSERT INTO group_ (workspace_id, name, summary, extra_perms) - VALUES ('test-workspace', 'error_handler', 'The group the error handler acts on behalf of', '{"u/test-user": true}') - ON CONFLICT DO NOTHING - "# - ) - .execute(&db) - .await?; - - // Run the failing script - let completed_job = RunJob::from(JobPayload::ScriptHash { - hash: ScriptHash(failing_script_hash), - path: "f/test/failing_script".to_string(), - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - language: ScriptLang::Bun, - priority: None, - apply_preprocessor: false, - concurrency_settings: ConcurrencySettings::default(), - debouncing_settings: DebouncingSettings::default(), - labels: None, - job_token_scopes: None, - }) - .run_until_complete(&db, false, server.addr.port()) - .await; - - // Verify the job actually failed - assert!(!completed_job.success, "Job should have failed"); - - let main_job_id = completed_job.id; - - // Wait for the error handler job to be created - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; - - // Verify the error handler job was created - let error_handler_job = sqlx::query!( - r#" - SELECT - id, - runnable_path, - permissioned_as_email, - parent_job - FROM v2_job - WHERE workspace_id = 'test-workspace' - AND permissioned_as_email = 'error_handler@windmill.dev' - ORDER BY created_at DESC - LIMIT 1 - "# - ) - .fetch_optional(&db) - .await?; - - assert!( - error_handler_job.is_some(), - "Error handler job should have been created" - ); - - let handler_job = error_handler_job.unwrap(); - - assert_eq!( - handler_job.runnable_path.as_deref(), - Some("f/test/error_handler"), - "Error handler should run the configured script" - ); - assert_eq!( - handler_job.permissioned_as_email.as_str(), - "error_handler@windmill.dev", - "Error handler should run as error_handler user" - ); - assert_eq!( - handler_job.parent_job, - Some(main_job_id), - "Error handler should have the failed job as parent" - ); - - Ok(()) -} - -/// Test that error handler is NOT triggered when ws_error_handler_muted is set on the script -#[cfg(all(feature = "deno_core", feature = "enterprise", feature = "private"))] -#[sqlx::test(fixtures("base"))] -async fn test_error_handler_muted_on_script(db: Pool) -> anyhow::Result<()> { - use windmill_common::jobs::JobPayload; - use windmill_common::runnable_settings::{ConcurrencySettings, DebouncingSettings}; - use windmill_common::scripts::{ScriptHash, ScriptLang}; - - initialize_tracing().await; - - let server = ApiServer::start(db.clone()).await?; - - // Create the error handler script - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', 3333333333, 'f/test/error_handler', 'export function main() { return "handled"; }', 'bun', 'script', 'test-user', '{}', '', '', E'{}\n//bun.lock\n') - "#, - ) - .execute(&db) - .await?; - - // Create a failing script with ws_error_handler_muted = true - let failing_script_hash: i64 = 4444444444; - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock, ws_error_handler_muted) - VALUES ('test-workspace', $1, 'f/test/muted_failing_script', 'export function main() { throw new Error("fail"); }', 'bun', 'script', 'test-user', '{}', '', '', E'{}\n//bun.lock\n', true) - "#, - failing_script_hash, - ) - .execute(&db) - .await?; - - // Set up the error handler - sqlx::query!( - r#" - UPDATE workspace_settings - SET error_handler = '{"path": "script/f/test/error_handler"}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - sqlx::query!( - r#" - INSERT INTO group_ (workspace_id, name, summary, extra_perms) - VALUES ('test-workspace', 'error_handler', 'Error handler group', '{"u/test-user": true}') - ON CONFLICT DO NOTHING - "# - ) - .execute(&db) - .await?; - - // Run the muted failing script - let completed_job = RunJob::from(JobPayload::ScriptHash { - hash: ScriptHash(failing_script_hash), - path: "f/test/muted_failing_script".to_string(), - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - language: ScriptLang::Bun, - priority: None, - apply_preprocessor: false, - concurrency_settings: ConcurrencySettings::default(), - debouncing_settings: DebouncingSettings::default(), - labels: None, - job_token_scopes: None, - }) - .run_until_complete(&db, false, server.addr.port()) - .await; - - assert!(!completed_job.success, "Job should have failed"); - - // Wait and check that NO error handler job was created - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; - - let error_handler_job = sqlx::query_scalar!( - r#" - SELECT id - FROM v2_job - WHERE workspace_id = 'test-workspace' - AND permissioned_as_email = 'error_handler@windmill.dev' - "# - ) - .fetch_optional(&db) - .await?; - - assert!( - error_handler_job.is_none(), - "Error handler should NOT have been triggered for a muted script" - ); - - Ok(()) -} - -/// Test that error handler is NOT triggered on successful job completion -#[cfg(all(feature = "deno_core", feature = "enterprise", feature = "private"))] -#[sqlx::test(fixtures("base"))] -async fn test_error_handler_not_triggered_on_success(db: Pool) -> anyhow::Result<()> { - use windmill_common::jobs::JobPayload; - use windmill_common::runnable_settings::{ConcurrencySettings, DebouncingSettings}; - use windmill_common::scripts::{ScriptHash, ScriptLang}; - - initialize_tracing().await; - - let server = ApiServer::start(db.clone()).await?; - - // Create the error handler script - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', 5555555555, 'f/test/error_handler', 'export function main() { return "handled"; }', 'bun', 'script', 'test-user', '{}', '', '', E'{}\n//bun.lock\n') - "#, - ) - .execute(&db) - .await?; - - // Create a successful script - let success_script_hash: i64 = 6666666666; - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', $1, 'f/test/success_script', 'export function main() { return "ok"; }', 'bun', 'script', 'test-user', '{}', '', '', E'{}\n//bun.lock\n') - "#, - success_script_hash, - ) - .execute(&db) - .await?; - - // Set up the error handler - sqlx::query!( - r#" - UPDATE workspace_settings - SET error_handler = '{"path": "script/f/test/error_handler"}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - sqlx::query!( - r#" - INSERT INTO group_ (workspace_id, name, summary, extra_perms) - VALUES ('test-workspace', 'error_handler', 'Error handler group', '{"u/test-user": true}') - ON CONFLICT DO NOTHING - "# - ) - .execute(&db) - .await?; - - // Run the successful script - let completed_job = RunJob::from(JobPayload::ScriptHash { - hash: ScriptHash(success_script_hash), - path: "f/test/success_script".to_string(), - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - language: ScriptLang::Bun, - priority: None, - apply_preprocessor: false, - concurrency_settings: ConcurrencySettings::default(), - debouncing_settings: DebouncingSettings::default(), - labels: None, - job_token_scopes: None, - }) - .run_until_complete(&db, false, server.addr.port()) - .await; - - assert!(completed_job.success, "Job should have succeeded"); - - // Wait and check that NO error handler job was created - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; - - let error_handler_job = sqlx::query_scalar!( - r#" - SELECT id - FROM v2_job - WHERE workspace_id = 'test-workspace' - AND permissioned_as_email = 'error_handler@windmill.dev' - "# - ) - .fetch_optional(&db) - .await?; - - assert!( - error_handler_job.is_none(), - "Error handler should NOT have been triggered for a successful job" - ); - - Ok(()) -} - -/// A hub script run at the top level (a schedule, a trigger, the API) is a `script_hub` job, -/// and its failure must reach the workspace error handler like a workspace script's. -#[cfg(all(feature = "enterprise", feature = "private"))] -#[sqlx::test(fixtures("base"))] -async fn test_error_handler_triggered_on_hub_script_failure( - db: Pool, -) -> anyhow::Result<()> { - use windmill_common::jobs::JobPayload; - - initialize_tracing().await; - - let server = ApiServer::start(db.clone()).await?; - - let version = "990000002"; - let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR; - tokio::fs::create_dir_all(hub_dir).await?; - tokio::fs::write( - format!("{hub_dir}/{version}"), - r#"{"content":"exit 1","lockfile":null,"language":"bash","schema":{},"summary":null}"#, - ) - .await?; - - // The workspace handler settings are cached per workspace id across the tests of this - // binary, so this reuses the handler path every other test here configures. - sqlx::query( - "INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', 1111111112, 'f/test/error_handler', 'echo handled', 'bash', 'script', 'test-user', '{}', '', '', '')", - ) - .execute(&db) - .await?; - sqlx::query( - r#"UPDATE workspace_settings SET error_handler = '{"path": "script/f/test/error_handler"}'::jsonb - WHERE workspace_id = 'test-workspace'"#, - ) - .execute(&db) - .await?; - - let completed_job = RunJob::from(JobPayload::ScriptHub { - path: format!("hub/{version}/test/fail"), - apply_preprocessor: false, - }) - .run_until_complete(&db, false, server.addr.port()) - .await; - assert!(!completed_job.success, "Hub script should have failed"); - - let mut handler_parent = None; - for _ in 0..50 { - handler_parent = sqlx::query_scalar::<_, Option>( - "SELECT parent_job FROM v2_job - WHERE workspace_id = 'test-workspace' AND permissioned_as_email = 'error_handler@windmill.dev'", - ) - .fetch_optional(&db) - .await?; - if handler_parent.is_some() { - break; - } - tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; - } - assert_eq!( - handler_parent, - Some(Some(completed_job.id)), - "Workspace error handler should handle the failed hub script" - ); - - Ok(()) -} diff --git a/backend/tests/fixtures/workspace_dependencies.sql b/backend/tests/fixtures/workspace_dependencies.sql deleted file mode 100644 index 9491f62e7c..0000000000 --- a/backend/tests/fixtures/workspace_dependencies.sql +++ /dev/null @@ -1,33 +0,0 @@ --- NOTE: Applied after workspace_dependencies_leafs.sql --- Python script that uses relative imports -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -from f.leafs.python import main as python_leaf - -def main(): - return {"python_import": python_leaf()}', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/python_importer', 500005, 'python3', ''); - --- TypeScript script that uses relative imports -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -import { main as tsLeaf } from "./leafs/ts"; - -export async function main() { - return { ts_import: await tsLeaf() }; -}', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/ts_importer', 500006, 'nativets', ''); - --- Dependency map entries -INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path, importer_node_id) VALUES ('test-workspace', 'f/python_importer', 'script', 'f/leafs/python', ''); -INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path, importer_node_id) VALUES ('test-workspace', 'f/ts_importer', 'script', 'f/leafs/ts', ''); diff --git a/backend/tests/fixtures/workspace_dependencies_leafs.sql b/backend/tests/fixtures/workspace_dependencies_leafs.sql deleted file mode 100644 index 3896cb4b00..0000000000 --- a/backend/tests/fixtures/workspace_dependencies_leafs.sql +++ /dev/null @@ -1,54 +0,0 @@ --- Basic leaf scripts in different languages -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -export async function main() { - return "TypeScript leaf"; -}', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/leafs/ts', 500001, 'nativets', ''); - -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -package main - -import "fmt" - -func main() { - fmt.Println("Go leaf") -}', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/leafs/go', 500002, 'go', ''); - -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -def main(): - return "Python leaf"', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/leafs/python', 500003, 'python3', ''); - -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/leafs/php', 500004, 'php', ''); - diff --git a/backend/tests/folder_default_permissioned_as.rs b/backend/tests/folder_default_permissioned_as.rs index 238d7cdb32..94d1d2fad5 100644 --- a/backend/tests/folder_default_permissioned_as.rs +++ b/backend/tests/folder_default_permissioned_as.rs @@ -680,6 +680,17 @@ async fn test_folder_default_permissioned_as(db: Pool) -> anyhow::Resu // 8. Stale rule — rule resolves to a user that does not exist // ======================================================================== + let resp = authed( + client().post(format!("{base}/scripts/create")), + "SECRET_TOKEN", + ) + .json(&new_script("f/prodfolder/stale/existing")) + .send() + .await?; + let status = resp.status(); + let existing_hash = resp.text().await?; + assert_eq!(status, 201, "script before the stale rule: {existing_hash}"); + let resp = authed( client().post(format!("{base}/folders/update/prodfolder")), "SECRET_TOKEN", @@ -719,6 +730,33 @@ async fn test_folder_default_permissioned_as(db: Pool) -> anyhow::Resu "error should identify the stale user: {body}" ); + // The default applies only to a first deploy, so it cannot fail a redeploy... + let mut redeploy = new_script("f/prodfolder/stale/existing"); + redeploy["content"] = json!("export async function main() { return 43; }"); + redeploy["parent_hash"] = json!(existing_hash); + let resp = authed( + client().post(format!("{base}/scripts/create")), + "SECRET_TOKEN", + ) + .json(&redeploy) + .send() + .await?; + assert_eq!( + resp.status(), + 201, + "stale rule must not block a redeploy: {}", + resp.text().await? + ); + // ...while a first deploy it would apply to still reports it. + let resp = authed( + client().post(format!("{base}/scripts/create")), + "SECRET_TOKEN", + ) + .json(&new_script("f/prodfolder/stale/new_script")) + .send() + .await?; + assert_eq!(resp.status(), 400, "stale rule should refuse a new script"); + // Non-matching paths in the same folder still work fine. let resp = authed( client().post(format!("{base}/schedules/create")), diff --git a/backend/tests/instance_config.rs b/backend/tests/instance_config.rs index 24937a3ce5..18a7466637 100644 --- a/backend/tests/instance_config.rs +++ b/backend/tests/instance_config.rs @@ -1533,6 +1533,32 @@ async fn declarative_sync_rejects_an_unusable_instance_banner(db: Pool ); } +#[sqlx::test(fixtures("base"))] +async fn declarative_sync_rejects_an_unusable_dev_workspace_tag_suffix(db: Pool) { + clear_settings_and_configs(&db).await; + let before = count_global_settings(&db).await; + + let mut desired = BTreeMap::new(); + desired.insert( + "dev_workspace_tag_suffix".to_string(), + serde_json::json!("-dev' OR '1'='1"), + ); + + let err = windmill_common::instance_config::sync_global_settings_declarative( + &db, + &BTreeMap::new(), + &desired, + &(), + ) + .await + .expect_err("a suffix the workers would ignore must fail the sync"); + assert!( + err.to_string().contains("dev_workspace_tag_suffix"), + "the error should name the offending setting, got: {err}" + ); + assert_eq!(count_global_settings(&db).await, before); +} + #[sqlx::test(fixtures("base"))] async fn declarative_sync_rejects_a_malformed_max_token_expiration(db: Pool) { clear_settings_and_configs(&db).await; diff --git a/backend/tests/protection_rules.rs b/backend/tests/protection_rules.rs index 6714b24801..bb9ef29fa2 100644 --- a/backend/tests/protection_rules.rs +++ b/backend/tests/protection_rules.rs @@ -686,3 +686,118 @@ async fn test_protection_rule_rename(db: Pool) -> anyhow::Result<()> { Ok(()) } + +/// `RequireIsolatedForks` refuses a non-bypassing forker any data shared with the workspace, on +/// both fork entry points, and lets an admin through. +#[sqlx::test(fixtures("base"))] +async fn test_require_isolated_forks(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + // Not `test-workspace`: PROTECTION_RULES_CACHE is process-wide and keyed by workspace id, so + // the other tests here, running concurrently on their own databases, would overwrite its rules. + invalidate_protection_rules_cache("iso-ws"); + // `dt2` is a clone governed from `gov`, but its database is this workspace's; `dt3` points + // into `gov`'s database. + let pg = r#"{"resource_type": "postgresql", "resource_path": "u/test-user/pg"}"#; + let gov = r#"{"workspace_id": "gov", "datatable": "src"}"#; + sqlx::raw_sql( + "INSERT INTO workspace (id, name, owner) VALUES + ('gov', 'gov', 'test-user'), ('iso-ws', 'iso-ws', 'test-user'); + INSERT INTO workspace_settings (workspace_id) VALUES ('gov'), ('iso-ws'); + INSERT INTO workspace_key (workspace_id, kind, key) VALUES ('iso-ws', 'cloud', 'iso-key'); + INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES + ('iso-ws', 'all', 'All users', '{}'); + INSERT INTO usr (workspace_id, email, username, is_admin, role) VALUES + ('iso-ws', 'test@windmill.dev', 'test-user', true, 'Admin'), + ('iso-ws', 'test2@windmill.dev', 'test-user-2', false, 'User')", + ) + .execute(&db) + .await?; + for (w_id, datatables) in [ + ("gov", format!(r#"{{"src": {{"database": {pg}}}}}"#)), + ( + "iso-ws", + format!( + r#"{{"dt1": {{"database": {pg}}}, "dt2": {{"database": {pg}, "governed_by": {gov}}}, + "dt3": {{"reference": {gov}}}}}"# + ), + ), + ] { + sqlx::query( + "UPDATE workspace_settings SET datatable = jsonb_build_object('datatables', $2::jsonb) \ + WHERE workspace_id = $1", + ) + .bind(w_id) + .bind(datatables) + .execute(&db) + .await?; + } + + let server = ApiServer::start(db.clone()).await?; + let base = format!("http://localhost:{}/api/w/iso-ws", server.addr.port()); + let resp = authed( + client().post(format!("{base}/workspaces/protection_rules")), + "SECRET_TOKEN", + ) + .json(&json!({ + "name": "isolate", + "rules": ["RequireIsolatedForks"], + "bypass_users": [], + "bypass_groups": [] + })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let cloned = + json!([{"name": "dt1", "new_dbname": "wm_fork_iso__dt1", "fork_behavior": "schema_only"}]); + for (route, body, shared) in [ + ( + "create_fork", + json!({"shared_storages": ["_default_"], "forked_datatables": cloned}), + "storage", + ), + ( + "create_workspace_fork_branch", + json!({"shared_ducklakes": ["main"], "forked_datatables": cloned}), + "ducklake", + ), + ( + "create_fork", + json!({"forked_datatables": cloned}), + "data table `dt2`", + ), + ] { + let mut body = body; + body["id"] = json!("wm-fork-iso"); + body["name"] = json!("iso"); + let resp = authed( + client().post(format!("{base}/workspaces/{route}")), + "SECRET_TOKEN_2", + ) + .json(&body) + .send() + .await?; + let status = resp.status(); + let text = resp.text().await?; + assert!( + status == 403 && text.contains(shared) && !text.contains("dt3"), + "{route} sharing {shared} should be refused: {status} {text}" + ); + } + + // An admin bypasses the rule: what stops this request is the unknown storage name. + let resp = authed( + client().post(format!("{base}/workspaces/create_fork")), + "SECRET_TOKEN", + ) + .json(&json!({"id": "wm-fork-iso", "name": "iso", "shared_storages": ["_default_"]})) + .send() + .await?; + let text = resp.text().await?; + assert!( + !text.contains("isolate"), + "admin should bypass the rule: {text}" + ); + + Ok(()) +} diff --git a/backend/tests/success_handler.rs b/backend/tests/success_handler.rs deleted file mode 100644 index 14df1a4c25..0000000000 --- a/backend/tests/success_handler.rs +++ /dev/null @@ -1,293 +0,0 @@ -use sqlx::{Pool, Postgres}; - -use windmill_test_utils::*; - -/// Both job-running tests seed `f/test/success_handler` with a different hash, each in its own -/// database, while the deployed-script caches are process-global and keyed by workspace and -/// path. With them on, one test resolves the handler to the other's hash and the handler push -/// 404s whenever that hash's info is not cached yet. -#[cfg(all(feature = "enterprise", feature = "private"))] -fn disable_deployed_script_cache() { - windmill_common::DEPLOYED_SCRIPT_CACHE_DISABLED - .store(true, std::sync::atomic::Ordering::Relaxed); -} - -/// The handler job is pushed after the job it handles is reported complete. -#[cfg(all(feature = "enterprise", feature = "private"))] -async fn wait_for_success_handler_job( - db: &Pool, -) -> anyhow::Result, Option)>> { - for _ in 0..100 { - let job = sqlx::query_as::<_, (Option, Option)>( - "SELECT runnable_path, parent_job FROM v2_job - WHERE workspace_id = 'test-workspace' AND permissioned_as_email = 'success_handler@windmill.dev'", - ) - .fetch_optional(db) - .await?; - if job.is_some() { - return Ok(job); - } - tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; - } - Ok(None) -} - -/// Test that the workspace success handler cache works correctly with 60s TTL -#[cfg(feature = "deno_core")] -#[sqlx::test(fixtures("base"))] -async fn test_success_handler_cache(db: Pool) -> anyhow::Result<()> { - initialize_tracing().await; - - // First, create a success handler script - let _server = ApiServer::start(db.clone()).await?; - - // Set up a success handler in workspace_settings using new JSONB column - sqlx::query!( - r#" - UPDATE workspace_settings - SET success_handler = '{"path": "script/f/test/success_handler", "extra_args": {"key": "value"}}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - // Verify the success handler was set - let result = sqlx::query_scalar!( - r#"SELECT success_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - - assert_eq!(result, Some("script/f/test/success_handler".to_string())); - - // Verify extra args were set - let extra_args = sqlx::query_scalar!( - r#"SELECT success_handler->'extra_args' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - - assert!(extra_args.is_some()); - - Ok(()) -} - -/// Test that success handler can be set and removed via database operations -#[cfg(feature = "deno_core")] -#[sqlx::test(fixtures("base"))] -async fn test_success_handler_settings(db: Pool) -> anyhow::Result<()> { - initialize_tracing().await; - - let _server = ApiServer::start(db.clone()).await?; - - // Initially success_handler should be NULL - let initial = sqlx::query_scalar!( - r#"SELECT success_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert!(initial.is_none()); - - // Set success handler - sqlx::query!( - r#" - UPDATE workspace_settings - SET success_handler = '{"path": "flow/f/test/success_flow"}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - let after_set = sqlx::query_scalar!( - r#"SELECT success_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert_eq!(after_set, Some("flow/f/test/success_flow".to_string())); - - // Remove success handler - sqlx::query!( - r#" - UPDATE workspace_settings - SET success_handler = NULL - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - let after_remove = sqlx::query_scalar!( - r#"SELECT success_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert!(after_remove.is_none()); - - Ok(()) -} - -/// Test that a successful job completion triggers the success handler -#[cfg(all(feature = "deno_core", feature = "enterprise", feature = "private"))] -#[sqlx::test(fixtures("base"))] -async fn test_success_handler_triggered_on_success(db: Pool) -> anyhow::Result<()> { - use serde_json::json; - use windmill_common::jobs::JobPayload; - use windmill_common::runnable_settings::{ConcurrencySettings, DebouncingSettings}; - use windmill_common::scripts::{ScriptHash, ScriptLang}; - - initialize_tracing().await; - disable_deployed_script_cache(); - - let server = ApiServer::start(db.clone()).await?; - - // Create a simple success handler script - // Note: lock must be non-null for script to be considered "deployed" - let success_handler_code = r#" -export async function main(path: string, email: string, job_id: string, is_flow: boolean, workspace_id: string, result: any) { - console.log("Success handler called for job:", job_id); - return { handled: true, original_path: path }; -} -"#; - - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', 1234567890, 'f/test/success_handler', $1, 'bun', 'script', 'test-user', '{}', 'Success handler script', 'Handles successful job completions', E'{}\n//bun.lock\n') - "#, - success_handler_code - ) - .execute(&db) - .await?; - - // Create a simple test script that we'll run (needs to be JobKind::Script, not Preview) - // Note: lock must be non-null for script to be considered "deployed" - let test_script_code = "export function main() { return 'success'; }"; - let test_script_hash: i64 = 9876543210; - - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', $1, 'f/test/simple_script', $2, 'bun', 'script', 'test-user', '{}', 'Simple test script', 'A simple test script', E'{}\n//bun.lock\n') - "#, - test_script_hash, - test_script_code - ) - .execute(&db) - .await?; - - // Set up the success handler in workspace_settings - sqlx::query!( - r#" - UPDATE workspace_settings - SET success_handler = '{"path": "script/f/test/success_handler"}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - // Create the success_handler group - sqlx::query!( - r#" - INSERT INTO group_ (workspace_id, name, summary, extra_perms) - VALUES ('test-workspace', 'success_handler', 'The group the success handler acts on behalf of', '{"u/test-user": true}') - ON CONFLICT DO NOTHING - "# - ) - .execute(&db) - .await?; - - // Run a script using ScriptHash (produces JobKind::Script, not Preview) - let completed_job = RunJob::from(JobPayload::ScriptHash { - hash: ScriptHash(test_script_hash), - path: "f/test/simple_script".to_string(), - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - language: ScriptLang::Bun, - priority: None, - apply_preprocessor: false, - concurrency_settings: ConcurrencySettings::default(), - debouncing_settings: DebouncingSettings::default(), - labels: None, - job_token_scopes: None, - }) - .run_until_complete(&db, false, server.addr.port()) - .await; - - let result = completed_job.json_result().unwrap(); - assert_eq!(result, json!("success")); - - let main_job_id = completed_job.id; - - let handler_job = wait_for_success_handler_job(&db).await?; - assert_eq!( - handler_job, - Some(( - Some("f/test/success_handler".to_string()), - Some(main_job_id) - )), - "Success handler should run the configured script with the main job as parent" - ); - // Note: root_job may be None when it equals parent_job (optimization in push function) - - Ok(()) -} - -/// A hub script run at the top level (a schedule, a trigger, the API) is a `script_hub` job, -/// and its success must reach the workspace success handler like a workspace script's. -#[cfg(all(feature = "enterprise", feature = "private"))] -#[sqlx::test(fixtures("base"))] -async fn test_success_handler_triggered_on_hub_script_success( - db: Pool, -) -> anyhow::Result<()> { - use windmill_common::jobs::JobPayload; - - initialize_tracing().await; - disable_deployed_script_cache(); - - let server = ApiServer::start(db.clone()).await?; - - let version = "990000003"; - let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR; - tokio::fs::create_dir_all(hub_dir).await?; - tokio::fs::write( - format!("{hub_dir}/{version}"), - r#"{"content":"echo ok","lockfile":null,"language":"bash","schema":{},"summary":null}"#, - ) - .await?; - - // The workspace handler settings are cached per workspace id across the tests of this - // binary, so this reuses the handler path every other test here configures. - sqlx::query( - "INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', 1234567891, 'f/test/success_handler', 'echo handled', 'bash', 'script', 'test-user', '{}', '', '', '')", - ) - .execute(&db) - .await?; - sqlx::query( - r#"UPDATE workspace_settings SET success_handler = '{"path": "script/f/test/success_handler"}'::jsonb - WHERE workspace_id = 'test-workspace'"#, - ) - .execute(&db) - .await?; - - let completed_job = RunJob::from(JobPayload::ScriptHub { - path: format!("hub/{version}/test/ok"), - apply_preprocessor: false, - }) - .run_until_complete(&db, false, server.addr.port()) - .await; - assert!(completed_job.success, "Hub script should have succeeded"); - - let handler_job = wait_for_success_handler_job(&db).await?; - assert_eq!( - handler_job.map(|(_, parent)| parent), - Some(Some(completed_job.id)), - "Workspace success handler should handle the successful hub script" - ); - - Ok(()) -} diff --git a/backend/tests/v2_job_delete_orphans.rs b/backend/tests/v2_job_delete_orphans.rs index fa621fb2a2..a11494baa7 100644 --- a/backend/tests/v2_job_delete_orphans.rs +++ b/backend/tests/v2_job_delete_orphans.rs @@ -528,6 +528,16 @@ async fn test_jobs_export_delete_is_workspace_scoped(db: Pool) -> anyh let other_job = Uuid::new_v4(); insert_job(&db, "ws-other", other_job).await?; seed_side_rows(&db, "ws-other", other_job).await?; + // A queued flow's per-job tables, which carry no workspace_id of their own. + for sql in [ + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for) VALUES ($1, 'ws-other', now())", + "INSERT INTO v2_job_runtime (id) VALUES ($1)", + "INSERT INTO v2_job_status (id) VALUES ($1)", + "INSERT INTO resume_job (id, job, flow) VALUES (gen_random_uuid(), $1, $1)", + "INSERT INTO concurrency_key (key, job_id) VALUES ('k', $1)", + ] { + sqlx::query(sql).bind(other_job).execute(&db).await?; + } // A test-workspace admin calls the purge endpoint with the FOREIGN job id. let server = ApiServer::start(db.clone()).await?; @@ -552,5 +562,20 @@ async fn test_jobs_export_delete_is_workspace_scoped(db: Pool) -> anyh (1, 1, 1, 1), "jobs_export purge crossed workspaces: dispatch_event={de} flow_conversation_message={fcm} zombie_job_counter={zombie} v2_job={job}" ); + for table_col in [ + "v2_job_queue WHERE id", + "v2_job_runtime WHERE id", + "v2_job_status WHERE id", + "resume_job WHERE job", + "concurrency_key WHERE job_id", + ] { + let n = count( + &db, + &format!("SELECT count(*) FROM {table_col} = $1"), + other_job, + ) + .await?; + assert_eq!(n, 1, "jobs_export purge crossed workspaces: {table_col}"); + } Ok(()) } diff --git a/backend/tests/worker.rs b/backend/tests/worker.rs index c47ea6d1ae..553106e6fe 100644 --- a/backend/tests/worker.rs +++ b/backend/tests/worker.rs @@ -2123,7 +2123,6 @@ async fn test_postgresql_single_worker_session_isolation(db: Pool) -> #[serial(pg_cache)] async fn test_postgresql_100_jobs_cached(db: Pool) -> anyhow::Result<()> { use std::sync::atomic::Ordering; - use windmill_common::worker::Connection; use windmill_worker::pg_executor::{clear_pg_cache, CACHE_HITS}; initialize_tracing().await; @@ -2176,27 +2175,7 @@ async fn test_postgresql_100_jobs_cached(db: Pool) -> anyhow::Result<( ids.push(make_pg_job(content).push(&db).await); } - // Run ONE worker for all 100 jobs. - let listener = listen_for_completed_jobs(&db).await; - let id_set = ids - .iter() - .copied() - .collect::>(); - in_test_worker( - Connection::Sql(db.clone()), - async { - use futures::StreamExt; - let mut remaining = id_set; - let mut listener = listener; - while !remaining.is_empty() { - if let Some(id) = listener.next().await { - remaining.remove(&id); - } - } - }, - port, - ) - .await; + run_on_one_worker(&db, port, &ids).await; // Verify all 100 jobs succeeded. for (i, id) in ids.iter().enumerate() { @@ -2259,6 +2238,26 @@ async fn test_postgresql_arg_type_combinations(db: Pool) -> anyhow::Re let db_arg = json!({"host": "localhost", "port": 5432, "dbname": "windmill", "user": "postgres", "password": "changeme"}); + let make_pg_job = |content: String| { + RunJob::from(JobPayload::Code(RawCode { + hash: None, + content, + path: None, + lock: None, + language: ScriptLang::Postgresql, + cache_ttl: None, + cache_ignore_s3_path: None, + dedicated_worker: None, + concurrency_settings: windmill_common::runnable_settings::ConcurrencySettings::default( + ) + .into(), + debouncing_settings: windmill_common::runnable_settings::DebouncingSettings::default(), + modules: None, + tag: None, + })) + .arg("database", db_arg.clone()) + }; + // Build a fresh schema for this test so we don't trip over prior runs. let setup = r#" DROP SCHEMA IF EXISTS wm_pg_arg_combo_test CASCADE; @@ -2289,26 +2288,7 @@ CREATE TABLE wm_pg_arg_combo_test.allcols ( CREATE TYPE wm_pg_arg_combo_test.color AS ENUM ('red','green','blue'); CREATE TABLE wm_pg_arg_combo_test.enumtbl (c wm_pg_arg_combo_test.color); "#; - RunJob::from(JobPayload::Code(RawCode { - hash: None, - content: setup.to_owned(), - path: None, - lock: None, - language: ScriptLang::Postgresql, - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - concurrency_settings: windmill_common::runnable_settings::ConcurrencySettings::default() - .into(), - debouncing_settings: windmill_common::runnable_settings::DebouncingSettings::default(), - modules: None, - tag: None, - })) - .arg("database", db_arg.clone()) - .run_until_complete(&db, false, port) - .await - .json_result() - .unwrap(); + let setup_id = make_pg_job(setup.to_owned()).push(&db).await; // Each case: (name, content, args, expected_result) let cases: Vec<(&str, String, serde_json::Value, serde_json::Value)> = vec![ @@ -2742,29 +2722,22 @@ SELECT 'price: $5' AS lbl, $5::int + $50::int AS sum"# ), ]; - for (name, content, args, expected) in cases { - let mut job = RunJob::from(JobPayload::Code(RawCode { - hash: None, - content, - path: None, - lock: None, - language: ScriptLang::Postgresql, - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - concurrency_settings: windmill_common::runnable_settings::ConcurrencySettings::default( - ) - .into(), - debouncing_settings: windmill_common::runnable_settings::DebouncingSettings::default(), - modules: None, - tag: None, - })) - .arg("database", db_arg.clone()); + let mut ids = vec![setup_id]; + for (_, content, args, _) in &cases { + let mut job = make_pg_job(content.clone()); for (k, v) in args.as_object().unwrap() { job = job.arg(k, v.clone()); } - let result = job - .run_until_complete(&db, false, port) + ids.push(job.push(&db).await); + } + run_on_one_worker(&db, port, &ids).await; + + completed_job(setup_id, &db) + .await + .json_result() + .expect("setup: no json result"); + for ((name, _, _, expected), id) in cases.into_iter().zip(&ids[1..]) { + let result = completed_job(*id, &db) .await .json_result() .unwrap_or_else(|| panic!("case '{name}': no json result")); @@ -2774,6 +2747,32 @@ SELECT 'price: $5' AS lbl, $5::int + $50::int AS sum"# Ok(()) } +/// Runs the already pushed `ids` on a single worker and returns once all completed. One worker +/// takes them one at a time in push order, so a setup job pushed first runs before the rest, +/// and they all share the process-wide PG connection cache as consecutive jobs would. +async fn run_on_one_worker(db: &Pool, port: u16, ids: &[Uuid]) { + use futures::StreamExt; + use windmill_common::worker::Connection; + + let mut listener = listen_for_completed_jobs(db).await; + let mut remaining = ids + .iter() + .copied() + .collect::>(); + in_test_worker( + Connection::Sql(db.clone()), + async { + while !remaining.is_empty() { + if let Some(id) = listener.next().await { + remaining.remove(&id); + } + } + }, + port, + ) + .await; +} + /// Pooler-safety regression test for #8988: when every arg has a resolvable /// otyp (the common SDK case), the dispatch must use unnamed prepared /// statements (`query_typed_raw`) and *must not* leak named statements @@ -3010,11 +3009,7 @@ CREATE SCHEMA wm_pg_cached_test; CREATE TYPE wm_pg_cached_test.color AS ENUM ('red', 'green', 'blue'); CREATE DOMAIN wm_pg_cached_test.short_name AS TEXT CHECK (length(VALUE) BETWEEN 1 AND 10); "#; - make_pg_job(setup.to_owned()) - .run_until_complete(&db, false, port) - .await - .json_result() - .unwrap(); + let setup_id = make_pg_job(setup.to_owned()).push(&db).await; // Run a long alternating sequence of enum + domain queries on the same // cached connection. Each query goes through the prepare-fallback path @@ -3022,21 +3017,36 @@ CREATE DOMAIN wm_pg_cached_test.short_name AS TEXT CHECK (length(VALUE) BETWEEN // tokio_postgres' typeinfo cache to resolve the Oids server-side. Pre-fix // this would fail intermittently with `prepared statement "sN" does not // exist` after the first cached-conn reuse. + let mut pairs = Vec::with_capacity(10); for i in 0..10 { - let r = make_pg_job("-- $1 arg1\nSELECT $1::wm_pg_cached_test.color AS c".to_owned()) + let enum_id = make_pg_job("-- $1 arg1\nSELECT $1::wm_pg_cached_test.color AS c".to_owned()) .arg("arg1", json!(if i % 2 == 0 { "red" } else { "blue" })) - .run_until_complete(&db, false, port) + .push(&db) .await; + let domain_id = + make_pg_job("-- $1 arg1\nSELECT $1::wm_pg_cached_test.short_name AS s".to_owned()) + .arg("arg1", json!(format!("v{i}"))) + .push(&db) + .await; + pairs.push((enum_id, domain_id)); + } + let mut ids = vec![setup_id]; + ids.extend(pairs.iter().flat_map(|(e, d)| [*e, *d])); + run_on_one_worker(&db, port, &ids).await; + + completed_job(setup_id, &db) + .await + .json_result() + .expect("setup: no json result"); + for (i, (enum_id, domain_id)) in pairs.into_iter().enumerate() { + let r = completed_job(enum_id, &db).await; assert!( r.success, "iter {i} enum query failed (was the DISCARD ALL bug); result: {:?}", r.result ); - let r = make_pg_job("-- $1 arg1\nSELECT $1::wm_pg_cached_test.short_name AS s".to_owned()) - .arg("arg1", json!(format!("v{i}"))) - .run_until_complete(&db, false, port) - .await; + let r = completed_job(domain_id, &db).await; assert!( r.success, "iter {i} domain query failed (was the DISCARD ALL bug); result: {:?}", @@ -5852,42 +5862,6 @@ async fn test_flow_schedule_handlers(db: Pool) -> anyhow::Result<()> { Ok(()) } -#[sqlx::test(fixtures("base", "relative_bun"))] -async fn test_relative_imports_bun(db: Pool) -> anyhow::Result<()> { - let content = r#" -import { main as test1 } from "/f/system/same_folder_script.ts"; -import { main as test2 } from "./same_folder_script.ts"; -import { main as test3 } from "/f/system_relative/different_folder_script.ts"; -import { main as test4 } from "../system_relative/different_folder_script.ts"; - -export async function main() { - return [test1(), test2(), test3(), test4()]; -} -"# - .to_string(); - - run_deployed_relative_imports(&db, content.clone(), ScriptLang::Bun).await?; - run_preview_relative_imports(&db, content, ScriptLang::Bun).await?; - Ok(()) -} - -#[cfg(feature = "deno_core")] -#[sqlx::test(fixtures("base", "relative_bun"))] -async fn test_nested_imports_bun(db: Pool) -> anyhow::Result<()> { - let content = r#" -import { main as test } from "/f/system_relative/nested_script.ts"; - -export async function main() { - return test(); -} -"# - .to_string(); - - run_deployed_relative_imports(&db, content.clone(), ScriptLang::Bun).await?; - run_preview_relative_imports(&db, content, ScriptLang::Bun).await?; - Ok(()) -} - #[sqlx::test(fixtures("base", "relative_deno"))] async fn test_relative_imports_deno(db: Pool) -> anyhow::Result<()> { let content = r#" diff --git a/backend/tests/workspace_dependencies.rs b/backend/tests/workspace_dependencies.rs index 773a4fd965..8136416190 100644 --- a/backend/tests/workspace_dependencies.rs +++ b/backend/tests/workspace_dependencies.rs @@ -1,23 +1,10 @@ mod workspace_dependencies { use sqlx::{Pool, Postgres}; - use tokio_stream::StreamExt; use windmill_common::scripts::ScriptLang; use windmill_dep_map::workspace_dependencies::NewWorkspaceDependencies; - use windmill_test_utils::in_test_worker; - use windmill_test_utils::init_client; - use windmill_test_utils::listen_for_completed_jobs; - mod deps { - pub const REQUIREMENTS_IN: &'static str = "tiny==0.1.3"; - // pub const GO_MOD: &'static str = r##" - // module example.com/project - // go 1.20 - - // require github.com/gin-gonic/gin v1.8.1 - // "##; - - pub const PACKAGE_JSON: &'static str = r##" + const PACKAGE_JSON: &'static str = r##" { "name": "example-project", "version": "1.0.0", @@ -27,101 +14,13 @@ mod workspace_dependencies { } "##; - pub const COMPOSER_JSON: &'static str = r##" - { - "name": "example/project", - "require": { - "monolog/monolog": "^2.3" - } - } - "##; - } - - #[cfg(feature = "python")] - #[sqlx::test(fixtures("base", "workspace_dependencies_leafs"))] - #[ignore] - async fn basic_manual_named(db: Pool) -> anyhow::Result<()> { - let ((_client, port, _s), db, mut completed) = ( - init_client(db.clone()).await, - &db, - listen_for_completed_jobs(&db).await, - ); - - for (idx, (l, c)) in [ - (ScriptLang::Python3, deps::REQUIREMENTS_IN), - (ScriptLang::Bun, deps::PACKAGE_JSON), - (ScriptLang::Php, deps::COMPOSER_JSON), - // (ScriptLang::Go, deps::GO_MOD), - ] - .iter() - .enumerate() - { - let id = NewWorkspaceDependencies { - workspace_id: "test-workspace".into(), - language: *l, - content: (*c).into(), - name: Some("test".to_owned()), - description: None, - } - .create(("".to_owned(), "".to_owned(), "".to_owned()), db.clone()) - .await - .unwrap(); - - assert_eq!(idx + 1, id as usize); - } - - // Wait for 4 jobs. - // Creating those dependencies will trigger redeployment of all scripts in workspace_dependencies_leafs.sql - in_test_worker( - db, - async { - completed.next().await; - completed.next().await; - completed.next().await; - // completed.next().await; - }, - port, - ) - .await; - - // Verify all scripts have correct locks - // let mut langs = vec![]; - // for r in sqlx::query!( - // r#"SELECT language AS "language: ScriptLang",lock FROM script WHERE archived = false"# - // ) - // .fetch_all(db) - // .await - // .unwrap() - // { - // match r.language { - // ScriptLang::Python3 => assert_eq!("", &r.lock.unwrap()), - // ScriptLang::Go => todo!(), - // ScriptLang::Bun => todo!(), - // ScriptLang::Bunnative => todo!(), - // ScriptLang::Php => todo!(), - // _ => panic!("Unsupported language"), - // } - - // langs.push(r.language); - // } - - // langs.sort(); - // // Just tiny additional verification for peace of mind. - // assert_eq!(langs.as_slice(), &[]); - - Ok(()) - } - #[sqlx::test(fixtures("base", "hub_sync_blacklist"))] async fn hub_sync_blacklist_from_workspace_deps(db: Pool) -> anyhow::Result<()> { - let ((_client, port, _s), db, mut completed) = ( - init_client(db.clone()).await, - &db, - listen_for_completed_jobs(&db).await, - ); + // The first unnamed workspace dependencies wait out the existence cache before + // redeploying their dependents. Read once per process, and this binary has no other test. + std::env::set_var("EXISTS_CACHE_TIMEOUT_MS", "0"); + let db = &db; - // Verify built-in fixtures exist - // Check that hub_sync script exists and is a Bun script let hub_sync_lang = sqlx::query_scalar!( r#"SELECT language AS "language: ScriptLang" FROM script WHERE path = 'u/admin/hub_sync'"# ) @@ -134,51 +33,55 @@ mod workspace_dependencies { "Expected hub_sync to be a Bun script" ); - // Create unnamed (default) workspace dependencies for Bun - let _id = NewWorkspaceDependencies { + // Unnamed (default) workspace dependencies for Bun + NewWorkspaceDependencies { workspace_id: "admins".into(), language: ScriptLang::Bun, - content: deps::PACKAGE_JSON.into(), - name: None, // No name = default workspace dependencies + content: PACKAGE_JSON.into(), + name: None, description: None, } .create(("".to_owned(), "".to_owned(), "".to_owned()), db.clone()) .await .unwrap(); - // Wait for exactly 1 job (only u/admin/simple_bun, not hub_sync) - let job_id = in_test_worker(db, async { completed.next().await }, port) - .await - .expect("Expected one job to complete"); - - // Query the job's runnable_path - let runnable_path = - sqlx::query_scalar!("SELECT runnable_path FROM v2_job WHERE id = $1", job_id) - .fetch_one(db) - .await - .unwrap(); - + // The dependency map decides which runnables are redeployed, and is rebuilt before + // `create` returns. + let importers: Vec = sqlx::query_scalar( + "SELECT importer_path FROM dependency_map + WHERE workspace_id = 'admins' AND imported_path = 'dependencies/package.json' + ORDER BY importer_path", + ) + .fetch_all(db) + .await?; assert_eq!( - runnable_path, - Some("u/admin/simple_bun".to_string()), - "Expected job runnable_path to be 'u/admin/simple_bun' (hub_sync should be blacklisted)" + importers, + vec!["u/admin/simple_bun".to_string()], + "hub_sync must not be recorded as importing the default workspace dependencies" ); - // Assert total job count is 1 - let job_count = sqlx::query_scalar!("SELECT COUNT(*) FROM v2_job") - .fetch_one(db) - .await - .unwrap(); - - assert_eq!(job_count, Some(1), "Expected exactly one job total"); - - // Assert v2_job_queue is empty - let queue_count = sqlx::query_scalar!("SELECT COUNT(*) FROM v2_job_queue") - .fetch_one(db) - .await - .unwrap(); - - assert_eq!(queue_count, Some(0), "Expected job queue to be empty"); + // The redeploy is pushed in the background as a debounced dependency job; it never needs + // to run for what is asserted here. + let mut jobs: Vec<(Option, String)> = vec![]; + for _ in 0..200 { + jobs = sqlx::query_as( + "SELECT runnable_path, kind::text FROM v2_job WHERE workspace_id = 'admins'", + ) + .fetch_all(db) + .await?; + if !jobs.is_empty() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + assert_eq!( + jobs, + vec![( + Some("u/admin/simple_bun".to_string()), + "dependencies".to_string() + )], + "Expected exactly one dependency job, for u/admin/simple_bun (hub_sync should be blacklisted)" + ); Ok(()) } diff --git a/backend/tests/workspace_handlers.rs b/backend/tests/workspace_handlers.rs new file mode 100644 index 0000000000..0ad1e044bd --- /dev/null +++ b/backend/tests/workspace_handlers.rs @@ -0,0 +1,422 @@ +#![cfg(all(feature = "enterprise", feature = "private"))] + +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +const ERROR_HANDLER_EMAIL: &str = "error_handler@windmill.dev"; +const SUCCESS_HANDLER_EMAIL: &str = "success_handler@windmill.dev"; + +/// Every test seeds `f/test/error_handler` or `f/test/success_handler` with a different hash, +/// each in its own database, while the deployed-script caches are process-global and keyed by +/// workspace and path. With them on, one test resolves the handler to another's hash and the +/// handler push 404s whenever that hash's info is not cached yet. +fn disable_deployed_script_cache() { + windmill_common::DEPLOYED_SCRIPT_CACHE_DISABLED + .store(true, std::sync::atomic::Ordering::Relaxed); +} + +/// Polls so the assertion does not depend on the handler being pushed before +/// `run_until_complete` returns, which only holds while the worker drains its completions on exit. +async fn wait_for_handler_job( + db: &Pool, + handler_email: &str, +) -> anyhow::Result, Option)>> { + for _ in 0..100 { + let job = sqlx::query_as::<_, (Option, Option)>( + "SELECT runnable_path, parent_job FROM v2_job + WHERE workspace_id = 'test-workspace' AND permissioned_as_email = $1", + ) + .bind(handler_email) + .fetch_optional(db) + .await?; + if job.is_some() { + return Ok(job); + } + tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; + } + Ok(None) +} + +#[cfg(feature = "deno_core")] +async fn insert_bun_script( + db: &Pool, + hash: i64, + path: &str, + content: &str, + ws_error_handler_muted: bool, +) -> anyhow::Result<()> { + // The lock must be non-null for the script to count as deployed. + sqlx::query( + r#"INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock, ws_error_handler_muted) + VALUES ('test-workspace', $1, $2, $3, 'bun', 'script', 'test-user', '{}', '', '', E'{}\n//bun.lock\n', $4)"#, + ) + .bind(hash) + .bind(path) + .bind(content) + .bind(ws_error_handler_muted) + .execute(db) + .await?; + Ok(()) +} + +/// Configures `f/test/error_handler` and `f/test/success_handler` as the workspace handlers. +/// Both settings are cached per workspace id across the tests of this binary, and any test's +/// top-level job can fill either cache, so every test configures both, with the same paths. +async fn configure_workspace_handlers(db: &Pool) -> anyhow::Result<()> { + sqlx::query( + r#"UPDATE workspace_settings + SET error_handler = '{"path": "script/f/test/error_handler"}'::jsonb, + success_handler = '{"path": "script/f/test/success_handler"}'::jsonb + WHERE workspace_id = 'test-workspace'"#, + ) + .execute(db) + .await?; + sqlx::query( + r#"INSERT INTO group_ (workspace_id, name, summary, extra_perms) + VALUES ('test-workspace', 'error_handler', '', '{"u/test-user": true}'), + ('test-workspace', 'success_handler', '', '{"u/test-user": true}') + ON CONFLICT DO NOTHING"#, + ) + .execute(db) + .await?; + Ok(()) +} + +/// Runs a deployed script by hash, which makes a `script` job rather than a preview. +#[cfg(feature = "deno_core")] +async fn run_script_hash(db: &Pool, port: u16, hash: i64, path: &str) -> CompletedJob { + use windmill_common::jobs::JobPayload; + use windmill_common::runnable_settings::{ConcurrencySettings, DebouncingSettings}; + use windmill_common::scripts::{ScriptHash, ScriptLang}; + + RunJob::from(JobPayload::ScriptHash { + hash: ScriptHash(hash), + path: path.to_string(), + cache_ttl: None, + cache_ignore_s3_path: None, + dedicated_worker: None, + language: ScriptLang::Bun, + priority: None, + apply_preprocessor: false, + concurrency_settings: ConcurrencySettings::default(), + debouncing_settings: DebouncingSettings::default(), + labels: None, + job_token_scopes: None, + }) + .run_until_complete(db, false, port) + .await +} + +/// A job's handler, if any, is pushed before the worker that ran it exits, so once a control +/// job has been handled, every handler job that the jobs run before it would produce exists. +#[cfg(feature = "deno_core")] +async fn assert_only_handled( + db: &Pool, + control_job: uuid::Uuid, + message: &str, +) -> anyhow::Result<()> { + assert!( + wait_for_handler_job(db, ERROR_HANDLER_EMAIL) + .await? + .is_some(), + "Error handler should have handled the control failure" + ); + let handled = sqlx::query_scalar::<_, Option>( + "SELECT parent_job FROM v2_job + WHERE workspace_id = 'test-workspace' AND permissioned_as_email = $1", + ) + .bind(ERROR_HANDLER_EMAIL) + .fetch_all(db) + .await?; + assert_eq!(handled, vec![Some(control_job)], "{message}"); + Ok(()) +} + +/// Test that a failed job triggers the workspace error handler +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base"))] +async fn test_error_handler_triggered_on_failure(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + + insert_bun_script( + &db, + 1111111111, + "f/test/error_handler", + r#" +export async function main(path: string, email: string, job_id: string, is_flow: boolean, workspace_id: string, error: any) { + console.log("Error handler called for job:", job_id); + return { handled: true, original_path: path }; +} +"#, + false, + ) + .await?; + insert_bun_script( + &db, + 2222222222, + "f/test/failing_script", + "export function main() { throw new Error('intentional failure'); }", + false, + ) + .await?; + configure_workspace_handlers(&db).await?; + + let completed_job = + run_script_hash(&db, server.addr.port(), 2222222222, "f/test/failing_script").await; + assert!(!completed_job.success, "Job should have failed"); + + assert_eq!( + wait_for_handler_job(&db, ERROR_HANDLER_EMAIL).await?, + Some(( + Some("f/test/error_handler".to_string()), + Some(completed_job.id) + )), + "Error handler should run the configured script with the failed job as parent" + ); + + Ok(()) +} + +/// Test that error handler is NOT triggered when ws_error_handler_muted is set on the script +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base"))] +async fn test_error_handler_muted_on_script(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + insert_bun_script( + &db, + 3333333333, + "f/test/error_handler", + r#"export function main() { return "handled"; }"#, + false, + ) + .await?; + let failing = r#"export function main() { throw new Error("fail"); }"#; + insert_bun_script( + &db, + 4444444444, + "f/test/muted_failing_script", + failing, + true, + ) + .await?; + insert_bun_script(&db, 4444444445, "f/test/failing_script", failing, false).await?; + configure_workspace_handlers(&db).await?; + + let muted_job = run_script_hash(&db, port, 4444444444, "f/test/muted_failing_script").await; + assert!(!muted_job.success, "Job should have failed"); + + let control_job = run_script_hash(&db, port, 4444444445, "f/test/failing_script").await; + assert!(!control_job.success, "Job should have failed"); + + assert_only_handled( + &db, + control_job.id, + "Error handler should NOT have been triggered for a muted script", + ) + .await +} + +/// Test that error handler is NOT triggered on successful job completion +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base"))] +async fn test_error_handler_not_triggered_on_success(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + insert_bun_script( + &db, + 5555555555, + "f/test/error_handler", + r#"export function main() { return "handled"; }"#, + false, + ) + .await?; + insert_bun_script( + &db, + 6666666666, + "f/test/success_script", + r#"export function main() { return "ok"; }"#, + false, + ) + .await?; + insert_bun_script( + &db, + 6666666667, + "f/test/failing_script", + r#"export function main() { throw new Error("fail"); }"#, + false, + ) + .await?; + configure_workspace_handlers(&db).await?; + + let success_job = run_script_hash(&db, port, 6666666666, "f/test/success_script").await; + assert!(success_job.success, "Job should have succeeded"); + + let control_job = run_script_hash(&db, port, 6666666667, "f/test/failing_script").await; + assert!(!control_job.success, "Job should have failed"); + + assert_only_handled( + &db, + control_job.id, + "Error handler should NOT have been triggered for a successful job", + ) + .await +} + +/// A hub script run at the top level (a schedule, a trigger, the API) is a `script_hub` job, +/// and its failure must reach the workspace error handler like a workspace script's. +#[sqlx::test(fixtures("base"))] +async fn test_error_handler_triggered_on_hub_script_failure( + db: Pool, +) -> anyhow::Result<()> { + use windmill_common::jobs::JobPayload; + + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + + let version = "990000002"; + let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR; + tokio::fs::create_dir_all(hub_dir).await?; + tokio::fs::write( + format!("{hub_dir}/{version}"), + r#"{"content":"exit 1","lockfile":null,"language":"bash","schema":{},"summary":null}"#, + ) + .await?; + + sqlx::query( + "INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) + VALUES ('test-workspace', 1111111112, 'f/test/error_handler', 'echo handled', 'bash', 'script', 'test-user', '{}', '', '', '')", + ) + .execute(&db) + .await?; + configure_workspace_handlers(&db).await?; + + let completed_job = RunJob::from(JobPayload::ScriptHub { + path: format!("hub/{version}/test/fail"), + apply_preprocessor: false, + }) + .run_until_complete(&db, false, server.addr.port()) + .await; + assert!(!completed_job.success, "Hub script should have failed"); + + let handler_job = wait_for_handler_job(&db, ERROR_HANDLER_EMAIL).await?; + assert_eq!( + handler_job.map(|(_, parent)| parent), + Some(Some(completed_job.id)), + "Workspace error handler should handle the failed hub script" + ); + + Ok(()) +} + +/// Test that a successful job completion triggers the success handler +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base"))] +async fn test_success_handler_triggered_on_success(db: Pool) -> anyhow::Result<()> { + use serde_json::json; + + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + + insert_bun_script( + &db, + 1234567890, + "f/test/success_handler", + r#" +export async function main(path: string, email: string, job_id: string, is_flow: boolean, workspace_id: string, result: any) { + console.log("Success handler called for job:", job_id); + return { handled: true, original_path: path }; +} +"#, + false, + ) + .await?; + insert_bun_script( + &db, + 9876543210, + "f/test/simple_script", + "export function main() { return 'success'; }", + false, + ) + .await?; + configure_workspace_handlers(&db).await?; + + let completed_job = + run_script_hash(&db, server.addr.port(), 9876543210, "f/test/simple_script").await; + assert_eq!(completed_job.json_result().unwrap(), json!("success")); + + assert_eq!( + wait_for_handler_job(&db, SUCCESS_HANDLER_EMAIL).await?, + Some(( + Some("f/test/success_handler".to_string()), + Some(completed_job.id) + )), + "Success handler should run the configured script with the main job as parent" + ); + + Ok(()) +} + +/// A hub script run at the top level (a schedule, a trigger, the API) is a `script_hub` job, +/// and its success must reach the workspace success handler like a workspace script's. +#[sqlx::test(fixtures("base"))] +async fn test_success_handler_triggered_on_hub_script_success( + db: Pool, +) -> anyhow::Result<()> { + use windmill_common::jobs::JobPayload; + + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + + let version = "990000003"; + let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR; + tokio::fs::create_dir_all(hub_dir).await?; + tokio::fs::write( + format!("{hub_dir}/{version}"), + r#"{"content":"echo ok","lockfile":null,"language":"bash","schema":{},"summary":null}"#, + ) + .await?; + + sqlx::query( + "INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) + VALUES ('test-workspace', 1234567891, 'f/test/success_handler', 'echo handled', 'bash', 'script', 'test-user', '{}', '', '', '')", + ) + .execute(&db) + .await?; + configure_workspace_handlers(&db).await?; + + let completed_job = RunJob::from(JobPayload::ScriptHub { + path: format!("hub/{version}/test/ok"), + apply_preprocessor: false, + }) + .run_until_complete(&db, false, server.addr.port()) + .await; + assert!(completed_job.success, "Hub script should have succeeded"); + + let handler_job = wait_for_handler_job(&db, SUCCESS_HANDLER_EMAIL).await?; + assert_eq!( + handler_job.map(|(_, parent)| parent), + Some(Some(completed_job.id)), + "Workspace success handler should handle the successful hub script" + ); + + Ok(()) +} diff --git a/backend/windmill-ai/Cargo.toml b/backend/windmill-ai/Cargo.toml index 44c4ac83c7..38f62fa16f 100644 --- a/backend/windmill-ai/Cargo.toml +++ b/backend/windmill-ai/Cargo.toml @@ -12,6 +12,8 @@ mcp = ["dep:windmill-mcp"] [lib] name = "windmill_ai" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-common = { workspace = true, default-features = false } diff --git a/backend/windmill-ai/src/ai_providers.rs b/backend/windmill-ai/src/ai_providers.rs index 3b3af833d6..311c8d3eb7 100644 --- a/backend/windmill-ai/src/ai_providers.rs +++ b/backend/windmill-ai/src/ai_providers.rs @@ -5,6 +5,9 @@ use serde::{Deserialize, Deserializer, Serialize}; use windmill_common::db::DB; use windmill_common::error::{Error, Result}; +use windmill_common::ssrf::{PrivateHostAllowance, SsrfValidationError, ValidatedTarget}; + +const ALLOW_PRIVATE_AI_BASE_URLS_ENV: &str = "ALLOW_PRIVATE_AI_BASE_URLS"; /// Deserializes an Option where empty strings become None. /// Use with `#[serde(default, deserialize_with = "empty_string_as_none")]` @@ -20,10 +23,10 @@ where lazy_static::lazy_static! { static ref OPENAI_AZURE_BASE_PATH: Option = std::env::var("OPENAI_AZURE_BASE_PATH").ok(); - pub static ref ALLOW_PRIVATE_AI_BASE_URLS: bool = std::env::var("ALLOW_PRIVATE_AI_BASE_URLS") - .ok() - .map(|v| v == "true" || v == "1") - .unwrap_or(false); + /// Covers every AI base URL, whoever supplied it: the workspace or instance AI config, a + /// resource a member picked, or an inline resource value sent to the proxy. + pub static ref ALLOW_PRIVATE_AI_BASE_URLS: PrivateHostAllowance = + PrivateHostAllowance::from_env(ALLOW_PRIVATE_AI_BASE_URLS_ENV); /// Drops the cache breakpoints from agent-step requests on every Anthropic platform, /// not just the one that motivates it: a Google Cloud project can have explicit prompt /// caching turned off (by request to Cloud support), and Vertex then rejects any request @@ -131,6 +134,23 @@ pub enum AIProvider { Cloudflare, } +/// Check an AI endpoint URL against the SSRF rules, allowing the private hosts +/// `ALLOW_PRIVATE_AI_BASE_URLS` names. Callers that connect next pin the returned target. +pub async fn validate_ai_url(url: &str) -> Result { + windmill_common::ssrf::validate_url_for_ssrf_allowing(url, &ALLOW_PRIVATE_AI_BASE_URLS) + .await + .map_err(|e| match e { + // Only a private target is fixed by the env var; for a malformed URL or bad + // scheme the hint would send users the wrong way (issue #9171). + e @ SsrfValidationError::Private { .. } => Error::BadRequest(format!( + "{e}. To use a private/internal AI endpoint, add its host (host, host:port or \ + CIDR range) to the comma-separated {ALLOW_PRIVATE_AI_BASE_URLS_ENV} environment \ + variable, or set it to true to allow every private host" + )), + e => Error::from(e), + }) +} + /// The Workers AI models URL of a Cloudflare account. The id goes into the path, so it is held to /// the characters an account id has rather than trusted to stay inside its segment. pub fn cloudflare_workers_ai_base_url(account_id: Option<&str>) -> Result { @@ -161,22 +181,7 @@ impl AIProvider { /// Get the base URL for the AI provider pub async fn get_base_url(&self, resource_base_url: Option, db: &DB) -> Result { if let Some(base_url) = resource_base_url { - if !*ALLOW_PRIVATE_AI_BASE_URLS { - use windmill_common::ssrf::SsrfValidationError; - windmill_common::ssrf::validate_url_for_ssrf(&base_url) - .await - .map_err(|e| match e { - // The env-var hint is only actionable when the URL is - // well-formed but blocked for targeting a private - // address. For a malformed URL or bad scheme, surface - // the real error so users fix the URL (issue #9171). - e @ SsrfValidationError::Private { .. } => Error::BadRequest(format!( - "{e}. If you need to use private/internal AI endpoints, \ - set the ALLOW_PRIVATE_AI_BASE_URLS=true environment variable" - )), - e => Error::from(e), - })?; - } + validate_ai_url(&base_url).await?; return Ok(base_url); } diff --git a/backend/windmill-ai/src/proxy.rs b/backend/windmill-ai/src/proxy.rs index 887cab0f3e..ca6ee1b59b 100644 --- a/backend/windmill-ai/src/proxy.rs +++ b/backend/windmill-ai/src/proxy.rs @@ -19,6 +19,25 @@ pub struct ProxyBuildArgs<'a> { pub credentials: &'a ProviderCredentials, } +/// Refuses a client-supplied proxy path that could resolve outside the provider's base +/// path once appended to it. URL parsing treats `\` as `/`, drops tabs and newlines, trims +/// spaces and ends the path at `?` or `#`, so `.\t./`, `..\`, `.. ` and `..?x` climb a +/// segment like `../`. The path arrives decoded once, so any `%` left is a second encoding +/// (`%2e`, `%2f`) that the URL parser or a gateway in front of the provider may decode again. +pub fn validate_proxy_path(path: &str) -> Result<()> { + let invalid = || Error::BadRequest(format!("Invalid AI proxy path: {path}")); + if path + .chars() + .any(|c| matches!(c, '\\' | ' ' | '?' | '#' | '%') || c.is_control()) + || path + .split('/') + .any(|segment| segment == "." || segment == "..") + { + return Err(invalid()); + } + Ok(()) +} + /// Provider-specific request produced by proxy request builders. #[derive(Clone, Debug)] pub struct ProxyRequest { @@ -271,6 +290,39 @@ mod tests { } } + #[test] + fn proxy_path_refuses_dot_segments() { + for path in [ + "chat/completions", + "v1/messages", + "models", + "openai/deployments/gpt-4.1/chat/completions", + "a..b/c", + ] { + assert!(validate_proxy_path(path).is_ok(), "{path}"); + } + for path in [ + "../key/info", + "..", + "models/../../key/info", + "./x", + "%2e%2e/key/info", + "%2E./key/info", + ".%2E/key/info", + "..\\key/info", + ".\t./key/info", + "..\n/key/info", + ".. ", + "..?x=1", + "..#f", + "%2e%2e?x", + "..%2fkey/info", + "%2e%2e%2fkey", + ] { + assert!(validate_proxy_path(path).is_err(), "{path:?}"); + } + } + #[test] fn builds_openai_compatible_proxy_request() { let credentials = credentials(AIProvider::OpenRouter, "https://openrouter.ai/api/v1/"); diff --git a/backend/windmill-ai/src/utils.rs b/backend/windmill-ai/src/utils.rs index 328d2e0458..de7efda183 100644 --- a/backend/windmill-ai/src/utils.rs +++ b/backend/windmill-ai/src/utils.rs @@ -88,30 +88,17 @@ pub fn ai_http_client_builder() -> reqwest::ClientBuilder { /// after the check (DNS-rebinding TOCTOU). /// /// Returns the shared pooled [`AI_HTTP_CLIENT`] unchanged when there is nothing -/// to pin — an IP-literal host, or a deployment that opted into private AI -/// endpoints via `ALLOW_PRIVATE_AI_BASE_URLS`. The same opt-out and error hint -/// as `AIProvider::get_base_url` apply, so this is consistent with the +/// to pin — an IP-literal host, or a host `ALLOW_PRIVATE_AI_BASE_URLS` allows +/// by name or wholesale. The same allowlist and error hint as +/// `AIProvider::get_base_url` apply, so this is consistent with the /// credential-time validation while additionally closing the connect-time window. pub async fn pinned_ai_client_for( url: &str, ) -> windmill_common::error::Result> { use std::borrow::Cow; - use windmill_common::error::{to_anyhow, Error}; - use windmill_common::ssrf::SsrfValidationError; + use windmill_common::error::to_anyhow; - if *crate::ai_providers::ALLOW_PRIVATE_AI_BASE_URLS { - return Ok(Cow::Borrowed(&AI_HTTP_CLIENT)); - } - - let target = windmill_common::ssrf::validate_url_for_ssrf(url) - .await - .map_err(|e| match e { - e @ SsrfValidationError::Private { .. } => Error::BadRequest(format!( - "{e}. If you need to use private/internal AI endpoints, \ - set the ALLOW_PRIVATE_AI_BASE_URLS=true environment variable" - )), - e => Error::from(e), - })?; + let target = crate::ai_providers::validate_ai_url(url).await?; if target.pinned_addrs().is_empty() { return Ok(Cow::Borrowed(&AI_HTTP_CLIENT)); diff --git a/backend/windmill-alerting/Cargo.toml b/backend/windmill-alerting/Cargo.toml index 6f7352426e..a1c46edbb9 100644 --- a/backend/windmill-alerting/Cargo.toml +++ b/backend/windmill-alerting/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_alerting" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-common = { workspace = true, default-features = false } diff --git a/backend/windmill-api-agent-workers/Cargo.toml b/backend/windmill-api-agent-workers/Cargo.toml index feabde8b12..4b3a202003 100644 --- a/backend/windmill-api-agent-workers/Cargo.toml +++ b/backend/windmill-api-agent-workers/Cargo.toml @@ -7,17 +7,20 @@ edition.workspace = true [lib] name = "windmill_api_agent_workers" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] enterprise = ["windmill-common/enterprise", "windmill-queue/enterprise"] -private = ["windmill-common/private", "windmill-queue/private"] +private = ["windmill-common/private", "windmill-queue/private", "windmill-audit/private"] python = ["dep:windmill-parser-py-imports"] benchmark = ["windmill-queue/benchmark"] [dependencies] windmill-api-auth.workspace = true windmill-common = { workspace = true, default-features = false } +windmill-audit.workspace = true windmill-queue.workspace = true windmill-worker.workspace = true axum.workspace = true diff --git a/backend/windmill-api-assets/Cargo.toml b/backend/windmill-api-assets/Cargo.toml index 62bc3d9c8d..5b43e3f2a5 100644 --- a/backend/windmill-api-assets/Cargo.toml +++ b/backend/windmill-api-assets/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_assets" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] private = ["windmill-common/private"] diff --git a/backend/windmill-api-auth/Cargo.toml b/backend/windmill-api-auth/Cargo.toml index 515a51cab7..1461e95237 100644 --- a/backend/windmill-api-auth/Cargo.toml +++ b/backend/windmill-api-auth/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_auth" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index 720111e89d..6bc9a930a4 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -6,6 +6,7 @@ use axum::{ }; use chrono::TimeZone; use http::{request::Parts, StatusCode}; +use itertools::Itertools; use quick_cache::sync::Cache; use serde::{Deserialize, Serialize}; use sqlx::FromRow; @@ -1022,6 +1023,49 @@ where } } +/// Adds the suffixed form of each tag of an `if_jobs:filter_tags:` scope: in a dev workspace a +/// job allowed on `gpu` is queued on `gpu-dev`, and the token must still reach the jobs it starts. +fn expand_filter_tags_with_dev_suffix(scopes: &mut [String], suffix: &str) { + for scope in scopes.iter_mut() { + if let Some(tags) = scope.strip_prefix("if_jobs:filter_tags:") { + let expanded = tags + .split(',') + .flat_map(|t| { + let suffixed = windmill_common::worker::with_dev_workspace_suffix(t, suffix); + [t.to_string(), suffixed] + }) + .unique() + .join(","); + *scope = format!("if_jobs:filter_tags:{expanded}"); + } + } +} + +/// Only while isolation is on and for a workspace whose jobs get the suffix then: otherwise the +/// suffixed tags are other tags the token was not given. +async fn expand_filter_tags_for_dev_workspace( + db: &DB, + workspace_id: &str, + scopes: Option<&mut Vec>, +) { + let Some(scopes) = scopes else { return }; + if !windmill_common::worker::DEV_WORKSPACE_ISOLATION.load(std::sync::atomic::Ordering::Relaxed) + || !scopes.iter().any(|s| s.starts_with("if_jobs:filter_tags:")) + { + return; + } + let (is_dev, in_dev_lineage) = windmill_common::workspaces::dev_lineage(db, workspace_id) + .await + .unwrap_or(( + workspace_id.starts_with(windmill_common::workspaces::WM_FORK_PREFIX), + true, + )); + if windmill_common::worker::is_isolated_workspace(is_dev, in_dev_lineage) { + let suffix = windmill_common::worker::DEV_WORKSPACE_TAG_SUFFIX.load(); + expand_filter_tags_with_dev_suffix(scopes, &suffix); + } +} + pub fn transform_old_scope_to_new_scope(scopes: Option<&mut Vec>) { if let Some(scopes) = scopes { for scope in scopes.iter_mut() { @@ -1110,10 +1154,10 @@ pub async fn resolve_opt_job_authed( }; if is_no_auth() { - return Ok(( - OptJobAuthed { authed: no_auth_admin_authed(), job_id: None }, - parts, - )); + let authed = no_auth_admin_authed(); + // Handlers taking `Extension` read this insert, as on the token path. + parts.extensions.insert(authed.clone()); + return Ok((OptJobAuthed { authed, job_id: None }, parts)); } // Safe only while what the route checks below read is fixed before the first @@ -1172,6 +1216,14 @@ pub async fn resolve_opt_job_authed( let authed = &mut opt_job_authed.authed; if authed.scopes.is_some() && !own_job_runtime_route { transform_old_scope_to_new_scope(authed.scopes.as_mut()); + if let Some(w_id) = workspace_id.as_deref() { + expand_filter_tags_for_dev_workspace( + &cache.db, + w_id, + authed.scopes.as_mut(), + ) + .await; + } if let Err(err) = crate::scopes::check_scopes_for_route( authed.scopes.as_deref(), @@ -1359,6 +1411,19 @@ pub async fn list_tokens_internal( mod tests { use super::*; + #[test] + fn filter_tags_reach_their_dev_workspace_form() { + let mut scopes = vec![ + "jobs:read".to_string(), + "if_jobs:filter_tags:gpu,bash-dev".to_string(), + ]; + expand_filter_tags_with_dev_suffix(&mut scopes, "-dev"); + assert_eq!( + scopes, + vec!["jobs:read", "if_jobs:filter_tags:gpu,gpu-dev,bash-dev"] + ); + } + /// Dropping the `AUTH_CACHE` entry between the two resolutions is what makes a memo /// hit observable: only a working memo can answer the second one. #[tokio::test] diff --git a/backend/windmill-api-client/Cargo.toml b/backend/windmill-api-client/Cargo.toml index 5d7ea274d9..ac326f9215 100644 --- a/backend/windmill-api-client/Cargo.toml +++ b/backend/windmill-api-client/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_client" path = "./src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] diff --git a/backend/windmill-api-configs/Cargo.toml b/backend/windmill-api-configs/Cargo.toml index a24e0b9540..f8c1c48dab 100644 --- a/backend/windmill-api-configs/Cargo.toml +++ b/backend/windmill-api-configs/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_configs" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-configs/src/lib.rs b/backend/windmill-api-configs/src/lib.rs index f1f4792e71..890a561679 100644 --- a/backend/windmill-api-configs/src/lib.rs +++ b/backend/windmill-api-configs/src/lib.rs @@ -273,18 +273,22 @@ async fn update_config( } let mut tx = db.begin().await?; - let was_paused = if name.starts_with("worker__") { + let previous = if name.starts_with("worker__") { sqlx::query_scalar!( - "SELECT COALESCE(config->'paused' = 'true'::jsonb, false) FROM config WHERE name = $1 FOR UPDATE", + "SELECT config FROM config WHERE name = $1 FOR UPDATE", &name ) .fetch_optional(&mut *tx) .await? .flatten() - .unwrap_or(false) } else { - false + None }; + let is_set = |c: Option<&serde_json::Value>, k: &str| { + c.and_then(|c| c.get(k)).and_then(|v| v.as_bool()) == Some(true) + }; + let was_paused = is_set(previous.as_ref(), "paused"); + let was_serving_dev = is_set(previous.as_ref(), "serves_dev_workspaces"); sqlx::query!( "INSERT INTO config (name, config) VALUES ($1, $2) ON CONFLICT (name) DO UPDATE SET config = EXCLUDED.config", &name, @@ -306,7 +310,7 @@ async fn update_config( tx.commit().await?; if name.starts_with("worker__") { - let paused = config.get("paused").and_then(|v| v.as_bool()) == Some(true); + let paused = is_set(Some(&config), "paused"); if paused != was_paused { windmill_common::feature_usage::log_feature_usage( "worker_group", @@ -314,6 +318,14 @@ async fn update_config( if paused { "pause" } else { "resume" }, ); } + let serving_dev = is_set(Some(&config), "serves_dev_workspaces"); + if serving_dev != was_serving_dev { + windmill_common::feature_usage::log_feature_usage( + "worker_group", + "dev_workspaces_toggle", + if serving_dev { "serve" } else { "stop" }, + ); + } } Ok(format!("Updated config {name}")) } diff --git a/backend/windmill-api-debug/Cargo.toml b/backend/windmill-api-debug/Cargo.toml index c262ac3d32..8e3ce3daf0 100644 --- a/backend/windmill-api-debug/Cargo.toml +++ b/backend/windmill-api-debug/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_debug" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-embeddings/Cargo.toml b/backend/windmill-api-embeddings/Cargo.toml index ff7c3435aa..411dc0efb0 100644 --- a/backend/windmill-api-embeddings/Cargo.toml +++ b/backend/windmill-api-embeddings/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_embeddings" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-flow-conversations/Cargo.toml b/backend/windmill-api-flow-conversations/Cargo.toml index dfb927e92e..d9e0c743ee 100644 --- a/backend/windmill-api-flow-conversations/Cargo.toml +++ b/backend/windmill-api-flow-conversations/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_flow_conversations" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-api-auth.workspace = true diff --git a/backend/windmill-api-flows/Cargo.toml b/backend/windmill-api-flows/Cargo.toml index 3fc2c7b572..c0bb7ae5e2 100644 --- a/backend/windmill-api-flows/Cargo.toml +++ b/backend/windmill-api-flows/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_flows" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-flows/src/flows.rs b/backend/windmill-api-flows/src/flows.rs index eab73bc015..fe4d8c37d4 100644 --- a/backend/windmill-api-flows/src/flows.rs +++ b/backend/windmill-api-flows/src/flows.rs @@ -805,6 +805,21 @@ async fn create_flow( nf.preserve_on_behalf_of = Some(true); } } + // Before `tx` opens, as every `db` read here must be: `user_db` wraps the same pool, so + // taking a second connection while holding `tx` lets concurrent deploys starve it. + let resolved_on_behalf_of = windmill_common::resolve_on_behalf_of( + nf.on_behalf_of_email.as_deref(), + nf.on_behalf_of.as_deref(), + nf.preserve_on_behalf_of.unwrap_or(false), + &authed, + &w_id, + &db, + ) + .await?; + // Written beside the principal only while a worker that still reads it may be live. + let legacy_on_behalf_of_email = + windmill_common::legacy_on_behalf_of_email(resolved_on_behalf_of.as_deref(), &w_id, &db) + .await?; let mut tx = user_db.clone().begin(&authed).await?; @@ -830,19 +845,6 @@ async fn create_flow( if restricts_steps { windmill_common::feature_usage::log_feature_usage("job_token_scopes", "deploy", "step:set"); } - let resolved_on_behalf_of = windmill_common::resolve_on_behalf_of( - nf.on_behalf_of_email.as_deref(), - nf.on_behalf_of.as_deref(), - nf.preserve_on_behalf_of.unwrap_or(false), - &authed, - &w_id, - &db, - ) - .await?; - // Written beside the principal only while a worker that still reads it may be live. - let legacy_on_behalf_of_email = - windmill_common::legacy_on_behalf_of_email(resolved_on_behalf_of.as_deref(), &w_id, &db) - .await?; sqlx::query!( r#"INSERT INTO flow ( workspace_id, path, summary, description, @@ -1389,6 +1391,20 @@ async fn update_flow( validate_flow(&nf, &authed, &db, &user_db, &w_id).await?; let authed = maybe_refresh_folders(&flow_path, &w_id, authed, &db).await; + // Before `tx` opens, for the reason given in `create_flow`. + let resolved_on_behalf_of = windmill_common::resolve_on_behalf_of( + nf.on_behalf_of_email.as_deref(), + nf.on_behalf_of.as_deref(), + nf.preserve_on_behalf_of.unwrap_or(false), + &authed, + &w_id, + &db, + ) + .await?; + // Written beside the principal only while a worker that still reads it may be live. + let legacy_on_behalf_of_email = + windmill_common::legacy_on_behalf_of_email(resolved_on_behalf_of.as_deref(), &w_id, &db) + .await?; let mut tx = user_db.clone().begin(&authed).await?; check_schedule_conflict(&mut tx, &w_id, flow_path).await?; @@ -1426,19 +1442,6 @@ async fn update_flow( if restricts_steps { windmill_common::feature_usage::log_feature_usage("job_token_scopes", "deploy", "step:set"); } - let resolved_on_behalf_of = windmill_common::resolve_on_behalf_of( - nf.on_behalf_of_email.as_deref(), - nf.on_behalf_of.as_deref(), - nf.preserve_on_behalf_of.unwrap_or(false), - &authed, - &w_id, - &db, - ) - .await?; - // Written beside the principal only while a worker that still reads it may be live. - let legacy_on_behalf_of_email = - windmill_common::legacy_on_behalf_of_email(resolved_on_behalf_of.as_deref(), &w_id, &db) - .await?; sqlx::query!( " diff --git a/backend/windmill-api-groups/Cargo.toml b/backend/windmill-api-groups/Cargo.toml index 35443008f0..3887f3b03e 100644 --- a/backend/windmill-api-groups/Cargo.toml +++ b/backend/windmill-api-groups/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_groups" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-groups/src/groups.rs b/backend/windmill-api-groups/src/groups.rs index d9550d2f5b..860e486a75 100644 --- a/backend/windmill-api-groups/src/groups.rs +++ b/backend/windmill-api-groups/src/groups.rs @@ -238,6 +238,13 @@ async fn create_group( Json(ng): Json, ) -> Result { crate::check_demo_workspace_restriction(&authed, &w_id, "Group creation")?; + // Admins stay allowed: `wmill sync push` recreates exported groups through this endpoint. + if !authed.is_admin && windmill_common::RESERVED_GROUP_NAMES.contains(&ng.name.as_str()) { + return Err(Error::BadRequest(format!( + "Group name {} is reserved by Windmill; only an admin can create it", + ng.name + ))); + } let mut tx = user_db.begin(&authed).await?; check_name_conflict(&mut tx, &w_id, &ng.name).await?; diff --git a/backend/windmill-api-inputs/Cargo.toml b/backend/windmill-api-inputs/Cargo.toml index 30d3f0d9f5..f5fbe3b0ea 100644 --- a/backend/windmill-api-inputs/Cargo.toml +++ b/backend/windmill-api-inputs/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_inputs" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-api-auth.workspace = true diff --git a/backend/windmill-api-integration-tests/Cargo.toml b/backend/windmill-api-integration-tests/Cargo.toml index 69dbaeaaa2..8302b5b252 100644 --- a/backend/windmill-api-integration-tests/Cargo.toml +++ b/backend/windmill-api-integration-tests/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_integration_tests" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-api-integration-tests/tests/fork_secret_replication_azure.rs b/backend/windmill-api-integration-tests/tests/fork_secret_replication_azure.rs index 19682de70a..855b45e2ca 100644 --- a/backend/windmill-api-integration-tests/tests/fork_secret_replication_azure.rs +++ b/backend/windmill-api-integration-tests/tests/fork_secret_replication_azure.rs @@ -14,14 +14,16 @@ //! (lowkey-vault), which the `AzureKeyVaultBackend` talks to via its //! static-token / self-signed-cert emulator mode. //! -//! Run it: +//! The test is `#[ignore]`d, so a plain `cargo test` skips it without creating +//! a database. Run it with `--ignored` (`AZURE_KV_URL` overrides the default +//! https://localhost:8443): //! ```bash //! podman run -d --name lowkey -p 8443:8443 \ //! -e LOWKEY_ARGS="--LOWKEY_VAULT_NAMES=default" \ //! docker.io/nagyesta/lowkey-vault:7.3.0 //! -//! RUN_AZURE_KV_TESTS=1 cargo test -p windmill-api-integration-tests \ -//! --features private,enterprise --test fork_secret_replication_azure -- --nocapture +//! cargo test -p windmill-api-integration-tests \ +//! --features private,enterprise --test fork_secret_replication_azure -- --ignored --nocapture //! ``` #[cfg(all(feature = "private", feature = "enterprise"))] @@ -55,11 +57,8 @@ mod azure_fork { } #[sqlx::test(migrations = "../migrations", fixtures("base"))] + #[ignore = "requires a lowkey-vault Azure Key Vault emulator at AZURE_KV_URL"] async fn migrated_secret_is_replicated_on_fork(db: Pool) -> anyhow::Result<()> { - if std::env::var("RUN_AZURE_KV_TESTS").as_deref() != Ok("1") { - eprintln!("skipping: set RUN_AZURE_KV_TESTS=1 and start lowkey-vault to run"); - return Ok(()); - } initialize_tracing().await; // The Azure KV emulator persists across runs; derive unique names per run diff --git a/backend/windmill-api-integration-tests/tests/groups.rs b/backend/windmill-api-integration-tests/tests/groups.rs index 9928d1c060..20e866cc37 100644 --- a/backend/windmill-api-integration-tests/tests/groups.rs +++ b/backend/windmill-api-integration-tests/tests/groups.rs @@ -1116,3 +1116,38 @@ async fn test_instance_group_member_that_is_not_an_email_is_skipped( Ok(()) } + +/// A non-admin who creates a reserved group first becomes its member and inherits every grant +/// Windmill later gives it. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_reserved_group_names_admin_only(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!( + "http://localhost:{}/api/w/test-workspace/groups", + server.addr.port() + ); + + for name in windmill_common::RESERVED_GROUP_NAMES { + let resp = client() + .post(format!("{base}/create")) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .json(&json!({ "name": name })) + .send() + .await?; + assert_eq!(resp.status(), 400, "non-admin creating {name}"); + assert!(resp.text().await?.contains("reserved")); + + let resp = authed(client().post(format!("{base}/create"))) + .json(&json!({ "name": name })) + .send() + .await?; + assert_eq!( + resp.status(), + 200, + "admin creating {name}: {}", + resp.text().await? + ); + } + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/jobs_unauthed.rs b/backend/windmill-api-integration-tests/tests/jobs_unauthed.rs index fa8b6cb66f..5cb7d0dfb5 100644 --- a/backend/windmill-api-integration-tests/tests/jobs_unauthed.rs +++ b/backend/windmill-api-integration-tests/tests/jobs_unauthed.rs @@ -236,14 +236,17 @@ async fn test_jobs_unauthed_complex_reachability(db: Pool) -> anyhow:: "GET /get_log_file", ); - let resp = authed(client().post(format!("{base}/queue/cancel_persistent/u/test-user/fake"))) + // Unauthenticated, so the handler refuses before cancelling, which sleeps for seconds. + let resp = client() + .post(format!("{base}/queue/cancel_persistent/u/test-user/fake")) .json(&serde_json::json!({"reason": "test"})) .send() .await?; - assert_route_reachable( - resp.status().as_u16(), - &resp.text().await?, - "POST /queue/cancel_persistent", + let status = resp.status().as_u16(); + let body = resp.text().await?; + assert!( + status == 400 && body.contains("Cancelling persistent script require"), + "POST /queue/cancel_persistent did not reach its handler: {status} {body}" ); Ok(()) diff --git a/backend/windmill-api-integration-tests/tests/mcp_preprocessor_headers.rs b/backend/windmill-api-integration-tests/tests/mcp_preprocessor_headers.rs index 25942e845c..7ae631b5dc 100644 --- a/backend/windmill-api-integration-tests/tests/mcp_preprocessor_headers.rs +++ b/backend/windmill-api-integration-tests/tests/mcp_preprocessor_headers.rs @@ -127,7 +127,7 @@ async fn test_mcp_preprocessor_receives_the_callers_headers( .and_then(|list| { list.iter() .filter_map(|t| t["name"].as_str()) - .find(|n| n.contains("mcp__hdr__probe")) + .find(|n| *n == "mcp_hdr_probe") }) .ok_or_else(|| anyhow::anyhow!("the deployed script was not listed as a tool: {tools}"))? .to_string(); diff --git a/backend/windmill-api-integration-tests/tests/nested_dev_workspace.rs b/backend/windmill-api-integration-tests/tests/nested_dev_workspace.rs index a9549b91a8..fb92236ae1 100644 --- a/backend/windmill-api-integration-tests/tests/nested_dev_workspace.rs +++ b/backend/windmill-api-integration-tests/tests/nested_dev_workspace.rs @@ -432,13 +432,35 @@ async fn test_archive_takes_the_pairing_lock_for_a_standalone_workspace( .execute(&mut *held) .await?; - let finished = - tokio::time::timeout(std::time::Duration::from_secs(5), archive(port, "h-cand")).await; - assert!( - finished.is_err(), - "archive of a standalone workspace completed while its pairing lock was held: {finished:?}" - ); + let archiving = tokio::spawn(async move { archive(port, "h-cand").await }); + + let mut parked = false; + for _ in 0..400 { + let waiting: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock' \ + AND wait_event = 'advisory' AND datname = current_database() \ + AND query LIKE '%dev_workspace_pairing%' AND pid <> pg_backend_pid()", + ) + .fetch_one(&db) + .await?; + if waiting > 0 { + parked = true; + break; + } + assert!( + !archiving.is_finished(), + "archive of a standalone workspace completed while its pairing lock was held: {:?}", + archiving.await + ); + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + assert!(parked, "archive never waited on the pairing lock"); held.rollback().await?; + let (status, body) = archiving.await?; + assert!( + status.is_success(), + "archive after the lock was released returned {status}: {body}" + ); Ok(()) } diff --git a/backend/windmill-api-jobs/Cargo.toml b/backend/windmill-api-jobs/Cargo.toml index dad6469947..ca4153ac44 100644 --- a/backend/windmill-api-jobs/Cargo.toml +++ b/backend/windmill-api-jobs/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_jobs" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-jobs/src/jobs_export.rs b/backend/windmill-api-jobs/src/jobs_export.rs index b2b69367bc..c426497cf0 100644 --- a/backend/windmill-api-jobs/src/jobs_export.rs +++ b/backend/windmill-api-jobs/src/jobs_export.rs @@ -434,6 +434,7 @@ pub async fn import_completed_jobs( pub async fn import_queued_jobs( authed: ApiAuthed, + Extension(db): Extension, Extension(user_db): Extension, Path(w_id): Path, Json(jobs): Json>, @@ -468,7 +469,9 @@ pub async fn import_queued_jobs( let mut tx = user_db.begin(&authed).await?; - for job in jobs { + for mut job in jobs { + // A fork's admin is whoever created it, so an imported tag is as untrusted as a pushed one. + job.tag = windmill_queue::tags::apply_dev_workspace_suffix(job.tag, &w_id, &db).await?; sqlx::query!( r#" INSERT INTO v2_job ( @@ -622,6 +625,21 @@ pub async fn delete_jobs( let mut tx = user_db.begin(&authed).await?; + // job_ids are request-supplied, and resume_job, v2_job_runtime, v2_job_status, + // concurrency_key and zombie_job_counter have no workspace_id: keep only this workspace's + // jobs, or a workspace admin could erase another workspace's rows by passing its job ids. + // (Side-table list kept in sync with windmill_common::jobs::delete_jobs.) + let job_ids = sqlx::query_scalar!( + "SELECT id FROM v2_job WHERE workspace_id = $1 AND id = ANY($2)", + &w_id, + &job_ids + ) + .fetch_all(&mut *tx) + .await?; + if job_ids.is_empty() { + return Ok("No jobs to delete".to_string()); + } + let logs_deleted = sqlx::query!( "DELETE FROM job_logs WHERE workspace_id = $1 AND job_id = ANY($2)", &w_id, @@ -690,14 +708,8 @@ pub async fn delete_jobs( .await? .rows_affected(); - // job_ids are request-supplied, so scope every side-table delete to the workspace exactly - // like the v2_job delete below — otherwise a workspace admin could erase another - // workspace's side rows by passing foreign job ids. zombie_job_counter and - // flow_conversation_message have no workspace_id, so scope them via v2_job / their conversation. - // (Side-table list kept in sync with windmill_common::jobs::delete_jobs.) let zombie_deleted = sqlx::query!( - "DELETE FROM zombie_job_counter WHERE job_id IN (SELECT id FROM v2_job WHERE workspace_id = $1 AND id = ANY($2))", - &w_id, + "DELETE FROM zombie_job_counter WHERE job_id = ANY($1)", &job_ids ) .execute(&mut *tx) diff --git a/backend/windmill-api-npm-proxy/Cargo.toml b/backend/windmill-api-npm-proxy/Cargo.toml index d6e123abe3..e5d326e660 100644 --- a/backend/windmill-api-npm-proxy/Cargo.toml +++ b/backend/windmill-api-npm-proxy/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_npm_proxy" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-openapi/Cargo.toml b/backend/windmill-api-openapi/Cargo.toml index 24a6f2aed8..97d11f1f0d 100644 --- a/backend/windmill-api-openapi/Cargo.toml +++ b/backend/windmill-api-openapi/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_openapi" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-api-auth.workspace = true diff --git a/backend/windmill-api-schedule/Cargo.toml b/backend/windmill-api-schedule/Cargo.toml index 5017985820..f7a612c628 100644 --- a/backend/windmill-api-schedule/Cargo.toml +++ b/backend/windmill-api-schedule/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_schedule" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-api-scripts/Cargo.toml b/backend/windmill-api-scripts/Cargo.toml index 72353c6f1b..73bbfd49bb 100644 --- a/backend/windmill-api-scripts/Cargo.toml +++ b/backend/windmill-api-scripts/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_scripts" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-scripts/src/scripts.rs b/backend/windmill-api-scripts/src/scripts.rs index 4f4c962759..4bbe372254 100644 --- a/backend/windmill-api-scripts/src/scripts.rs +++ b/backend/windmill-api-scripts/src/scripts.rs @@ -900,7 +900,7 @@ async fn is_noop_deploy_against_parent( parent: &Script, resolved_on_behalf_of: Option<&str>, resolved_job_token_scopes: Option<&[String]>, - db: &DB, + tx: &mut Transaction<'_, Postgres>, ) -> Result { if parent.archived || parent.deleted { return Ok(false); @@ -1056,12 +1056,13 @@ async fn is_noop_deploy_against_parent( return Ok(false); } + let parent_settings = windmill_common::runnable_settings::from_handle( + parent.runnable_settings.runnable_settings_handle, + &mut **tx, + ) + .await?; let (parent_debouncing, parent_concurrency) = - windmill_common::runnable_settings::prefetch_cached_from_handle( - parent.runnable_settings.runnable_settings_handle, - db, - ) - .await?; + windmill_common::runnable_settings::prefetch_cached_tx(&parent_settings, tx).await?; if concurrency_settings != &parent_concurrency { return Ok(false); } @@ -1130,6 +1131,69 @@ fn lock_hash_entry(path: &str, lock: &str) -> [(String, i64); 1] { [(path.to_string(), hash_script(lock))] } +/// The principal a deploy would store, and the address written beside it only while a worker +/// that still reads that address may be live. +async fn resolve_deploy_identity( + on_behalf_of_email: Option<&str>, + on_behalf_of: Option<&str>, + preserve: bool, + authed: &ApiAuthed, + w_id: &str, + db: &DB, +) -> Result<(Option, Option)> { + let resolved = windmill_common::resolve_on_behalf_of( + on_behalf_of_email, + on_behalf_of, + preserve, + authed, + w_id, + db, + ) + .await?; + let legacy_email = + windmill_common::legacy_on_behalf_of_email(resolved.as_deref(), w_id, db).await?; + Ok((resolved, legacy_email)) +} + +/// Lineage reads must see versions the caller cannot, yet run on the deploy's own connection, +/// after the row locks that make them sound: lifting RLS for them is what stands in for asking +/// the pool, which while `tx` is held is a hold-and-wait. Every lift must be undone before `tx` +/// is handed on, or the rest of the deploy writes unscoped. +async fn set_lineage_reads_unscoped( + tx: &mut Transaction<'_, Postgres>, + authed: &ApiAuthed, + unscoped: bool, +) -> Result<()> { + // An admin's transaction already runs as `windmill_admin`. + if !authed.is_admin { + let role = if unscoped { + "SET LOCAL ROLE windmill_admin" + } else { + "SET LOCAL ROLE windmill_user" + }; + sqlx::query(role).execute(&mut **tx).await?; + } + Ok(()) +} + +/// The folder's default identity for `path` and what deploying under it would store. +async fn resolve_folder_default_identity( + authed: &ApiAuthed, + w_id: &str, + path: &str, + db: &DB, +) -> Result, Option))>> { + let Some((email, permissioned_as)) = + windmill_common::folders::resolve_folder_default_on_behalf_of(db, w_id, path).await? + else { + return Ok(None); + }; + let identity = + resolve_deploy_identity(Some(&email), Some(&permissioned_as), true, authed, w_id, db) + .await?; + Ok(Some((email, permissioned_as, identity))) +} + /// The `dbt://` relation both halves of a deploy have to agree on: a whole /// `//`, under a warehouse this workspace configures. /// @@ -1341,38 +1405,24 @@ async fn create_script_internal<'c>( let skip_draft_deletion = ns.skip_draft_deletion.unwrap_or(false); let authed = maybe_refresh_folders(&ns.path, &w_id, authed, &db).await; - let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?; - - // Apply folder default_permissioned_as the first time a script is deployed - // at this path. Check inside the transaction to avoid TOCTOU with concurrent deploys. + // Everything read from `db` happens before `tx` opens: `user_db` wraps the same pool, so a + // deploy taking a second connection while holding `tx` lets N concurrent deploys hold the + // whole pool between them and each wait out the acquire timeout for one more. let explicit_preserve = (ns.on_behalf_of_email.is_some() || ns.on_behalf_of.is_some()) && ns.preserve_on_behalf_of.unwrap_or(false) && windmill_common::can_preserve_on_behalf_of(&authed); - if !explicit_preserve && windmill_common::can_preserve_on_behalf_of(&authed) { - let path_already_exists = sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM script WHERE path = $1 AND workspace_id = $2)", - &ns.path, - &w_id - ) - .fetch_one(&mut *tx) - .await? - .unwrap_or(false); - if !path_already_exists { - if let Some((default_email, default_permissioned_as)) = - windmill_common::folders::resolve_folder_default_on_behalf_of(&db, &w_id, &ns.path) - .await? - { - ns.on_behalf_of_email = Some(default_email); - ns.on_behalf_of = Some(default_permissioned_as); - ns.preserve_on_behalf_of = Some(true); - } - } - } - let authed_principal = windmill_common::users::username_to_permissioned_as(&authed.username); + // Held rather than raised: a rule naming a principal that no longer exists fails here, and + // must fail only a first deploy, which is all the default applies to. + let folder_default = + if !explicit_preserve && windmill_common::can_preserve_on_behalf_of(&authed) { + resolve_folder_default_identity(&authed, &w_id, &ns.path, &db).await + } else { + Ok(None) + }; // Resolved here rather than at the INSERT so the no-op check below compares the identity // that would actually be stored: the parent row holds only the principal, while a // preserving push may name that same principal by address alone. - let resolved_on_behalf_of = windmill_common::resolve_on_behalf_of( + let requested_identity = resolve_deploy_identity( ns.on_behalf_of_email.as_deref(), ns.on_behalf_of.as_deref(), ns.preserve_on_behalf_of.unwrap_or(false), @@ -1381,10 +1431,46 @@ async fn create_script_internal<'c>( &db, ) .await?; - // Written beside the principal only while a worker that still reads it may be live. - let legacy_on_behalf_of_email = - windmill_common::legacy_on_behalf_of_email(resolved_on_behalf_of.as_deref(), &w_id, &db) - .await?; + // Not on `tx`: these inserts are cached as written, which a rolled-back deploy would undo. + let runnable_settings_handle = windmill_common::runnable_settings::insert_rs( + RunnableSettings { + debouncing_settings: ns.debouncing_settings.insert_cached(&db).await?, + concurrency_settings: ns.concurrency_settings.insert_cached(&db).await?, + retry_settings: None, + }, + &db, + ) + .await?; + + let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?; + + // Apply folder default_permissioned_as the first time a script is deployed + // at this path. Check inside the transaction to avoid TOCTOU with concurrent deploys. + let path_already_exists = match folder_default { + Ok(None) => true, + _ => sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM script WHERE path = $1 AND workspace_id = $2)", + &ns.path, + &w_id + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false), + }; + let (resolved_on_behalf_of, legacy_on_behalf_of_email) = if path_already_exists { + requested_identity + } else { + match folder_default? { + Some((default_email, default_permissioned_as, identity)) => { + ns.on_behalf_of_email = Some(default_email); + ns.on_behalf_of = Some(default_permissioned_as); + ns.preserve_on_behalf_of = Some(true); + identity + } + None => requested_identity, + } + }; + let authed_principal = windmill_common::users::username_to_permissioned_as(&authed.username); // When auto_parent is set, serialize concurrent creates for the same (workspace, path) // so the clashing_script query always sees the latest committed head. if ns.auto_parent.unwrap_or(false) { @@ -1467,66 +1553,70 @@ async fn create_script_internal<'c>( // nothing being live there, so a parentless deploy onto a live path still meets the // path conflict the match below raises. let mut parent_adopted_from_retired_path = false; - if ns.parent_hash.is_none() && clashing_script.is_none() { - // Locked, not merely read: a competing deploy chaining onto this same candidate - // takes `FOR UPDATE` on it before inserting, so holding the row is what serializes - // the two. Probe first and the child still uncommitted reads as absent. - let candidate = sqlx::query_scalar::<_, i64>( + // Locked, not merely read: a competing deploy chaining onto this same candidate + // takes `FOR UPDATE` on it before inserting, so holding the row is what serializes + // the two. Probe first and the child still uncommitted reads as absent. + let adoption_candidate = if ns.parent_hash.is_none() && clashing_script.is_none() { + sqlx::query_scalar::<_, i64>( "SELECT hash FROM script WHERE path = $1 AND workspace_id = $2 \ ORDER BY created_at DESC LIMIT 1 FOR UPDATE", ) .bind(&ns.path) .bind(&w_id) .fetch_optional(&mut *tx) - .await?; + .await? + } else { + None + }; + set_lineage_reads_unscoped(&mut tx, &authed, true).await?; + if let Some(hash) = adoption_candidate { // Adoptable only if nothing already descends from it: a rename leaves its source // path holding a version whose child lives at the destination, and a second child // forks a lineage the guard below requires to be linear. Nothing adoptable means a // fresh lineage, which has no parent to vary its hash and can still collide. - ns.parent_hash = match candidate { - Some(hash) => sqlx::query_scalar!( - "SELECT 1 FROM script WHERE parent_hashes[1] = $1 AND workspace_id = $2", - hash, - &w_id - ) - .fetch_optional(&db) - .await? - .is_none() - .then_some(ScriptHash(hash)), - None => None, - }; + ns.parent_hash = sqlx::query_scalar!( + "SELECT 1 FROM script WHERE parent_hashes[1] = $1 AND workspace_id = $2", + hash, + &w_id + ) + .fetch_optional(&mut *tx) + .await? + .is_none() + .then_some(ScriptHash(hash)); parent_adopted_from_retired_path = ns.parent_hash.is_some(); } // Absent keeps the previous version's value, read once the parent is settled (a rename // adopts its source head above), so a client unaware of the setting cannot drop a // restriction by redeploying or renaming. - let resolved_job_token_scopes: Option> = match (&ns.job_token_scopes, &ns.parent_hash) { - (Some(Some(scopes)), _) => { - windmill_common::min_version::MIN_VERSION_SUPPORTS_JOB_TOKEN_SCOPES - .assert() - .await?; - Some(windmill_common::scopes::validate_job_token_scopes(scopes)?) - } - (Some(None), _) => None, - (None, Some(parent_hash)) => sqlx::query_scalar!( - "SELECT job_token_scopes FROM script WHERE hash = $1 AND workspace_id = $2", - parent_hash.0, - &w_id - ) - .fetch_optional(&db) - .await? - .flatten(), - (None, None) => sqlx::query_scalar!( - "SELECT job_token_scopes FROM script WHERE path = $1 AND workspace_id = $2 \ + let resolved_job_token_scopes: Option> = + match (&ns.job_token_scopes, &ns.parent_hash) { + (Some(Some(scopes)), _) => { + windmill_common::min_version::MIN_VERSION_SUPPORTS_JOB_TOKEN_SCOPES + .assert() + .await?; + Some(windmill_common::scopes::validate_job_token_scopes(scopes)?) + } + (Some(None), _) => None, + (None, Some(parent_hash)) => sqlx::query_scalar!( + "SELECT job_token_scopes FROM script WHERE hash = $1 AND workspace_id = $2", + parent_hash.0, + &w_id + ) + .fetch_optional(&mut *tx) + .await? + .flatten(), + (None, None) => sqlx::query_scalar!( + "SELECT job_token_scopes FROM script WHERE path = $1 AND workspace_id = $2 \ AND deleted = false ORDER BY created_at DESC LIMIT 1", - &ns.path, - &w_id - ) - .fetch_optional(&db) - .await? - .flatten(), - }; + &ns.path, + &w_id + ) + .fetch_optional(&mut *tx) + .await? + .flatten(), + }; + set_lineage_reads_unscoped(&mut tx, &authed, false).await?; ns.job_token_scopes = Some(resolved_job_token_scopes.clone()); // Before hashing, so the hash and the no-op check see the schema that gets stored. @@ -1610,14 +1700,16 @@ async fn create_script_internal<'c>( // Unscoped, and sound only under the lock above: linearity is a property of the // lineage, not of what this caller may read. A child can sit where they cannot // see it — a folder they renamed it into, or grants an adopting deploy reset — - // and asked through `tx` it reads as absent, letting the fork through. + // and asked through a scoped `tx` it reads as absent, letting the fork through. + set_lineage_reads_unscoped(&mut tx, &authed, true).await?; let clashing_hash_o = sqlx::query_scalar!( "SELECT hash FROM script WHERE parent_hashes[1] = $1 AND workspace_id = $2", p_hash.0, &w_id ) - .fetch_optional(&db) + .fetch_optional(&mut *tx) .await?; + set_lineage_reads_unscoped(&mut tx, &authed, false).await?; if let Some(clashing_hash) = clashing_hash_o { // Named only when the caller could already read it. The probe above has to be @@ -1662,7 +1754,7 @@ async fn create_script_internal<'c>( &ps, resolved_on_behalf_of.as_deref(), resolved_job_token_scopes.as_deref(), - &db, + &mut tx, ) .await? { @@ -2207,16 +2299,6 @@ async fn create_script_internal<'c>( auto_kind }; - let runnable_settings_handle = windmill_common::runnable_settings::insert_rs( - RunnableSettings { - debouncing_settings: ns.debouncing_settings.insert_cached(&db).await?, - concurrency_settings: ns.concurrency_settings.insert_cached(&db).await?, - retry_settings: None, - }, - &db, - ) - .await?; - let ( guarded_concurrent_limit, guarded_concurrency_time_window_s, diff --git a/backend/windmill-api-settings/Cargo.toml b/backend/windmill-api-settings/Cargo.toml index 034a24edf1..816a2223ac 100644 --- a/backend/windmill-api-settings/Cargo.toml +++ b/backend/windmill-api-settings/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_settings" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-settings/src/lib.rs b/backend/windmill-api-settings/src/lib.rs index f9ba1ff86f..96c1be32c9 100644 --- a/backend/windmill-api-settings/src/lib.rs +++ b/backend/windmill-api-settings/src/lib.rs @@ -916,6 +916,7 @@ pub async fn set_global_setting_internal( run_setting_pre_write_hook(db, &key, &value).await?; + let turns_on = value.as_bool() == Some(true); match value { serde_json::Value::Null => { if instance_config::PROTECTED_SETTINGS.contains(&key.as_str()) { @@ -949,6 +950,21 @@ pub async fn set_global_setting_internal( } }; + if key == windmill_common::global_settings::DEV_WORKSPACE_ISOLATION_SETTING { + windmill_common::feature_usage::log_feature_usage( + "dev_workspace_isolation", + "toggle", + if turns_on { "on" } else { "off" }, + ); + } + if key == windmill_common::global_settings::DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING { + windmill_common::feature_usage::log_feature_usage( + "dev_workspace_isolation", + "skip_non_dev_forks_toggle", + if turns_on { "on" } else { "off" }, + ); + } + if should_bump_instance_ai_revision { bump_instance_ai_config_revision(); } @@ -975,6 +991,14 @@ async fn run_setting_pre_write_hook( value: &serde_json::Value, ) -> error::Result<()> { match key { + windmill_common::global_settings::DEV_WORKSPACE_TAG_SUFFIX_SETTING => match value { + serde_json::Value::Null => {} + serde_json::Value::String(s) if s.trim().is_empty() => {} + suffix => windmill_common::global_settings::validate_dev_workspace_tag_suffix(suffix) + .map_err(|e| { + error::Error::BadRequest(format!("The dev workspace tag suffix {e}")) + })?, + }, // The instance AI config is written as an untyped blob through this generic // endpoint, so it never passes the typed check the workspace handler applies. // Rates that reach a cost total unbounded would make it negative or infinite. @@ -1254,6 +1278,13 @@ async fn run_setting_pre_write_hook( v => windmill_common::global_settings::validate_accent_color(v) .map_err(|e| error::Error::BadRequest(format!("{ACCENT_COLOR_SETTING}: {e}")))?, }, + windmill_common::global_settings::AGENT_WORKLOAD_IDENTITY_ISSUERS_SETTING => { + if !value.is_null() { + let key = windmill_common::global_settings::AGENT_WORKLOAD_IDENTITY_ISSUERS_SETTING; + windmill_common::agent_workload_identity::validate_issuers_value(value) + .map_err(|e| error::Error::BadRequest(format!("{key}: {e}")))?; + } + } _ => {} } Ok(()) diff --git a/backend/windmill-api-sse/Cargo.toml b/backend/windmill-api-sse/Cargo.toml index b8127c3d36..d70f760163 100644 --- a/backend/windmill-api-sse/Cargo.toml +++ b/backend/windmill-api-sse/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_sse" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-api-users/Cargo.toml b/backend/windmill-api-users/Cargo.toml index 13ab8143d8..cfd683434c 100644 --- a/backend/windmill-api-users/Cargo.toml +++ b/backend/windmill-api-users/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_users" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-workers/Cargo.toml b/backend/windmill-api-workers/Cargo.toml index 8e54d84e77..fd87b8f4be 100644 --- a/backend/windmill-api-workers/Cargo.toml +++ b/backend/windmill-api-workers/Cargo.toml @@ -7,10 +7,14 @@ edition.workspace = true [lib] name = "windmill_api_workers" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-api-auth.workspace = true windmill-common = { workspace = true, default-features = false } +windmill-queue.workspace = true axum.workspace = true chrono.workspace = true serde.workspace = true diff --git a/backend/windmill-api-workers/src/lib.rs b/backend/windmill-api-workers/src/lib.rs index 8ebee2a967..2e224beb06 100644 --- a/backend/windmill-api-workers/src/lib.rs +++ b/backend/windmill-api-workers/src/lib.rs @@ -21,7 +21,11 @@ use windmill_common::{ jobs::{HIDE_WORKERS_FOR_NON_ADMINS, TAGS_ARE_SENSITIVE}, queue_metrics::{read_queue_metrics_series, QueueMetricsSeries}, utils::{paginate, Pagination}, - worker::{ALL_TAGS, CUSTOM_TAGS_PER_WORKSPACE, DEFAULT_TAGS, DEFAULT_TAGS_PER_WORKSPACE}, + worker::{ + ALL_TAGS, CUSTOM_TAGS_PER_WORKSPACE, DEFAULT_TAGS, DEFAULT_TAGS_PER_WORKSPACE, + DEV_WORKSPACE_ISOLATION, DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS, + DEV_WORKSPACE_TAG_SUFFIX, + }, workspaces::workspace_with_fork_ancestors, DB, }; @@ -37,6 +41,7 @@ pub fn global_service() -> Router { "/is_default_tags_per_workspace", get(get_default_tags_per_workspace), ) + .route("/dev_workspace_isolation", get(get_dev_workspace_isolation)) .route("/get_default_tags", get(get_default_tags)) .route("/queue_metrics", get(get_queue_metrics)) .route("/queue_metrics_series", get(get_queue_metrics_series)) @@ -186,7 +191,18 @@ async fn exists_workers_with_tags( let chain = workspace_with_fork_ancestors(&db, workspace).await?; let custom_tags = CUSTOM_TAGS_PER_WORKSPACE.load(); let allowed_tags = custom_tags.to_string_vec(Some(&chain)); - tags.retain(|t| allowed_tags.contains(t)); + // A dev workspace's jobs run on the suffixed form of the tags it may use. + let dev_suffix = windmill_queue::tags::dev_workspace_suffix_for(workspace, &db) + .await + .ok() + .flatten(); + tags.retain(|t| { + allowed_tags.contains(t) + || dev_suffix.as_deref().is_some_and(|s| { + t.strip_suffix(s) + .is_some_and(|b| allowed_tags.iter().any(|a| a == b)) + }) + }); } else { // No workspace provided and not superadmin - return empty return Ok(Json(std::collections::HashMap::new())); @@ -259,6 +275,22 @@ async fn get_default_tags_per_workspace() -> JsonResult { )) } +#[derive(Serialize)] +struct DevWorkspaceIsolation { + enabled: bool, + suffix: String, + skip_non_dev_forks: bool, +} + +async fn get_dev_workspace_isolation() -> JsonResult { + Ok(Json(DevWorkspaceIsolation { + enabled: DEV_WORKSPACE_ISOLATION.load(std::sync::atomic::Ordering::Relaxed), + suffix: DEV_WORKSPACE_TAG_SUFFIX.load().to_string(), + skip_non_dev_forks: DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS + .load(std::sync::atomic::Ordering::Relaxed), + })) +} + async fn get_default_tags() -> JsonResult> { Ok(Json(DEFAULT_TAGS.clone())) } diff --git a/backend/windmill-api-workspaces/Cargo.toml b/backend/windmill-api-workspaces/Cargo.toml index 9f05a26f28..646536a9ec 100644 --- a/backend/windmill-api-workspaces/Cargo.toml +++ b/backend/windmill-api-workspaces/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_workspaces" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index aa0dc764ec..eb00c4106d 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -515,6 +515,11 @@ struct CreateWorkspaceFork { /// fork namespace + read-defer. #[serde(default)] shared_ducklakes: Vec, + /// Workspace storages the fork reads and writes at the parent's keys (`_default_` for the + /// primary one). Every other storage is isolated: the fork writes under its own prefix + /// and reads through to the parent's objects. + #[serde(default)] + shared_storages: Vec, /// Create the fork as a persistent dev workspace: the id is not required to carry the /// `wm-fork-` prefix, and at most one dev workspace may exist per parent. #[serde(default)] @@ -2131,6 +2136,38 @@ async fn edit_dbt_warehouses( Ok("Updated the workspace's dbt warehouses".to_string()) } +/// A fork's isolated storage is purged at deletion from the storage recorded at creation: under +/// another location, its objects would outlive the fork untracked, and a same-id fork would +/// read them. +async fn reject_isolated_storage_repoint( + tx: &mut Transaction<'_, Postgres>, + w_id: &str, + new_lfs: &serde_json::Value, +) -> Result<()> { + let rows = sqlx::query!( + "SELECT storage, storage_ref FROM fork_storage_namespace WHERE workspace_id = $1", + w_id + ) + .fetch_all(&mut **tx) + .await?; + for row in rows { + let new_ref = windmill_common::fork_storage::lfs_entry(new_lfs, &row.storage) + .and_then(windmill_common::workspaces::lfs_entry_storage_ref); + if new_ref.is_some_and(|r| r != row.storage_ref) { + let name = if row.storage.is_empty() { + windmill_types::s3::DEFAULT_STORAGE + } else { + row.storage.as_str() + }; + return Err(Error::BadRequest(format!( + "storage `{name}` is isolated from the parent in this fork, so where it points \ + cannot be changed" + ))); + } + } + Ok(()) +} + async fn edit_large_file_storage_config( authed: ApiAuthed, Extension(db): Extension, @@ -2168,6 +2205,15 @@ async fn edit_large_file_storage_config( windmill_types::s3::DEFAULT_STORAGE ))); } + if lfs_config + .secondary_storage + .contains_key(windmill_types::s3::BUCKET_ADDRESSED_SEGMENT) + { + return Err(Error::BadRequest(format!( + "`{}` is reserved by the S3 proxy and cannot name a secondary storage", + windmill_types::s3::BUCKET_ADDRESSED_SEGMENT + ))); + } if !windmill_common::workspaces::filesystem_storage_allowed() { let named = std::iter::once(("primary storage", &lfs_config.large_file_storage)).chain( @@ -2189,6 +2235,7 @@ async fn edit_large_file_storage_config( let serialized_lfs_config = serde_json::to_value::(lfs_config) .map_err(|err| Error::internal_err(err.to_string()))?; + reject_isolated_storage_repoint(&mut tx, &w_id, &serialized_lfs_config).await?; // A workspace whose AI session backups fell back to the instance store leaves it // here: the generation moves on, so nothing it left in any instance store is read @@ -2285,6 +2332,9 @@ struct DataTableListItem { /// at its parent. Its permissions apply here, and only its admins may edit them. #[serde(skip_serializing_if = "Option::is_none")] governing_workspace_id: Option, + /// The workspace owning the database this entry points at, when it is not this workspace. + #[serde(skip_serializing_if = "Option::is_none")] + database_workspace_id: Option, /// Whether the governing entry is under roles. permissioned: bool, } @@ -2314,6 +2364,8 @@ async fn list_datatables( resource_path: database.resource_path.clone(), governing_workspace_id: (governing.governing_workspace_id() != w_id) .then(|| governing.governing_workspace_id().to_string()), + database_workspace_id: (governing.workspace_id != w_id) + .then(|| governing.workspace_id.clone()), permissioned: governing.datatable.permissions.is_some(), }); } @@ -8850,6 +8902,7 @@ async fn create_workspace_fork_branch( { return Err(Error::PermissionDenied(msg)); } + enforce_isolated_forks(&db, &authed, &w_id, &nw).await?; // Two-phase create for git-synced workspaces: this endpoint only creates the git branch(es) and // validates up front; it does NOT create the workspace row. The caller follows up with @@ -9562,6 +9615,25 @@ async fn create_workspace_fork( i.msg ); } + // Unlike a dropped lake's files, a deleted fork's objects are live to a same-id fork: it + // reads its own prefix first. + let leftover_storages = crate::workspaces_extra::prepare_fork_storage_purges( + &db, + &nw.id, + Some(&parent_workspace_id), + ) + .await?; + let storage_issues = + crate::workspaces_extra::purge_fork_storages_unless_live(&db, &nw.id, leftover_storages) + .await?; + if !storage_issues.is_empty() { + return Err(Error::BadRequest(format!( + "a previously deleted workspace with id '{}' left objects in its fork prefix that \ + could not be deleted: {}; retry once the storage is reachable again", + nw.id, + storage_issues.join("; ") + ))); + } #[cfg(not(feature = "enterprise"))] _check_nb_of_workspaces(&db).await?; @@ -9581,6 +9653,7 @@ async fn create_workspace_fork( { return Err(Error::PermissionDenied(msg)); } + enforce_isolated_forks(&db, &authed, &parent_workspace_id, &nw).await?; if nw.is_dev_workspace { ensure_dev_parent_can_host_dev(&db, &parent_workspace_id).await?; @@ -9955,6 +10028,185 @@ fn copy_requests( .collect() } +/// Under `RequireIsolatedForks` on `parent`, refuse a fork that would leave any of its data +/// shared: a shared storage or lake, or a data table not cloned (`Keep original` points the fork +/// at the parent's database). +async fn enforce_isolated_forks( + db: &DB, + authed: &ApiAuthed, + parent: &str, + nw: &CreateWorkspaceFork, +) -> Result<()> { + let Some(msg) = isolation_required(db, authed, parent).await? else { + return Ok(()); + }; + let mut shared: Vec = nw + .shared_storages + .iter() + .map(|s| format!("storage `{s}`")) + .chain( + nw.shared_ducklakes + .iter() + .map(|l| format!("ducklake `{l}`")), + ) + .collect(); + shared.extend( + kept_parent_datatables(db, parent, &nw.forked_datatables) + .await? + .into_iter() + .map(|name| format!("data table `{name}`")), + ); + refuse_shared(msg, shared) +} + +/// The rule's message when `RequireIsolatedForks` on `parent` binds `authed`. +async fn isolation_required(db: &DB, authed: &ApiAuthed, parent: &str) -> Result> { + match check_user_against_rule( + parent, + &ProtectionRuleKind::RequireIsolatedForks, + AuditAuthorable::username(authed), + &authed.groups, + authed.is_admin, + db, + ) + .await? + { + RuleCheckResult::Blocked(msg) => Ok(Some(msg)), + RuleCheckResult::Allowed => Ok(None), + } +} + +/// `parent`'s own data tables that `forked` leaves as pointers at its database. An entry whose +/// database another workspace owns is not `parent`'s data, so the rule does not cover it. +async fn kept_parent_datatables( + db: &DB, + parent: &str, + forked: &[ForkedDatatableInfo], +) -> Result> { + Ok( + windmill_common::workspaces::resolve_workspace_governing_datatables(db, parent) + .await? + .into_iter() + .filter(|(_, governing)| governing.workspace_id == parent) + .filter(|(name, _)| { + !forked.iter().any(|d| { + &d.name == name + && matches!( + d.fork_behavior, + Some( + DataTableForkBehavior::SchemaOnly + | DataTableForkBehavior::SchemaAndData + ) + ) + }) + }) + .map(|(name, _)| name) + .collect(), + ) +} + +fn refuse_shared(msg: String, shared: Vec) -> Result<()> { + if shared.is_empty() { + return Ok(()); + } + Err(Error::PermissionDenied(format!( + "{msg}. Shared in this request: {}. Only a bypasser of the rule can fork while one of \ + them cannot be isolated", + shared.join(", ") + ))) +} + +/// Record every storage of the fork's cloned settings as isolated, except `shared` ones. +/// Isolation is a per-fork-creation choice, never inherited: a fork of a shared fork is +/// isolated unless it asks otherwise. +async fn isolate_fork_storages( + tx: &mut Transaction<'_, Postgres>, + fork_id: &str, + shared: &[String], + shared_ducklakes: &[String], +) -> Result<()> { + use windmill_common::fork_storage::{lfs_entry, registry_storage_name}; + + let settings = sqlx::query!( + "SELECT large_file_storage, ducklake FROM workspace_settings WHERE workspace_id = $1", + fork_id + ) + .fetch_optional(&mut **tx) + .await?; + let (lfs, ducklake) = settings + .map(|s| (s.large_file_storage, s.ducklake)) + .unwrap_or_default(); + let lfs = lfs.filter(|v| v.get("type").is_some()); + + // A shared lake keeps the parent's data path: its files must land at the parent's keys, or + // the parent's catalog would point at objects in the fork's prefix, purged with the fork. + if lfs.is_some() { + for lake in shared_ducklakes { + let lake_storage = ducklake + .as_ref() + .and_then(|d| { + d.get("ducklakes")? + .get(lake)? + .get("storage")? + .get("storage") + }) + .and_then(|s| s.as_str()); + let storage = registry_storage_name(lake_storage); + if !shared + .iter() + .any(|s| registry_storage_name(Some(s)) == storage) + { + return Err(Error::BadRequest(format!( + "ducklake `{lake}` is shared with the parent, so the storage holding its \ + data (`{}`) must be shared too", + lake_storage.unwrap_or(windmill_types::s3::DEFAULT_STORAGE) + ))); + } + } + } + let mut storages: Vec<&str> = vec![]; + if let Some(lfs) = &lfs { + storages.push(""); + if let Some(secondary) = lfs.get("secondary_storage").and_then(|s| s.as_object()) { + storages.extend(secondary.keys().map(String::as_str)); + } + } + for name in shared { + if !storages.contains(®istry_storage_name(Some(name))) { + return Err(Error::BadRequest(format!( + "cannot share storage `{name}` with the parent: no such storage in the workspace \ + settings" + ))); + } + } + let Some(lfs) = &lfs else { + return Ok(()); + }; + for storage in storages { + if shared + .iter() + .any(|s| registry_storage_name(Some(s)) == storage) + { + continue; + } + let Some(storage_ref) = + lfs_entry(lfs, storage).and_then(windmill_common::workspaces::lfs_entry_storage_ref) + else { + continue; + }; + sqlx::query!( + "INSERT INTO fork_storage_namespace (workspace_id, storage, storage_ref) + VALUES ($1, $2, $3)", + fork_id, + storage, + storage_ref + ) + .execute(&mut **tx) + .await?; + } + Ok(()) +} + /// Write the fork, with its data tables pointed at `copies`. async fn write_workspace_fork( db: DB, @@ -9977,6 +10229,17 @@ async fn write_workspace_fork( // Also before the external cluster's lifecycle lock, which finalizing an external copy takes: // fork cleanup takes the two in this order. windmill_common::workspaces::lock_fork_datatables(&mut tx, &parent_workspace_id).await?; + // Data table edits take the lock above: one committed since the creation check would reach + // this fork as a pointer at the parent's database. + if let Some(msg) = isolation_required(&db, &authed, &parent_workspace_id).await? { + let kept = kept_parent_datatables(&db, &parent_workspace_id, &nw.forked_datatables).await?; + refuse_shared( + msg, + kept.into_iter() + .map(|name| format!("data table `{name}`")) + .collect(), + )?; + } if nw.is_dev_workspace { // The checks above ran outside a transaction, so the parent's eligibility and the chain's @@ -10220,6 +10483,14 @@ async fn write_workspace_fork( } } + isolate_fork_storages( + &mut tx, + &forked_id, + &nw.shared_storages, + &nw.shared_ducklakes, + ) + .await?; + // Lock the parent ("prod") so edits are funneled through this dev workspace. let locked_prod = nw.is_dev_workspace && (nw.lock_prod_deploy || nw.lock_prod_forking); if locked_prod { @@ -10267,6 +10538,9 @@ async fn write_workspace_fork( .await?; } tx.commit().await?; + // Same for a mapping cached before the isolation rows were visible: identity, writing the + // root's keys. + windmill_common::fork_storage::invalidate_fork_storage_keys_cache(&forked_id); // A pre-creation lookup could have cached an EMPTY ancestor chain for this id, which // would bypass ducklake fork isolation for the TTL. The same lookup could have cached the id @@ -10983,20 +11257,10 @@ async fn archive_workspace( if let Some(prod) = dev_lock_parent { windmill_common::workspaces::invalidate_protection_rules_cache(&prod); - // The teardown above cleared `is_dev_workspace`, which is what let this workspace keep its - // own id for tag routing; it and every fork resolving through it now land on an ancestor. - // Only a dev workspace reaches here, so archiving anything else needs no sweep. - windmill_queue::tags::invalidate_fork_parent_cache(&w_id); - for id in windmill_common::workspaces::list_fork_descendants(&db, &w_id) - .await - .unwrap_or_default() - { - windmill_queue::tags::invalidate_fork_parent_cache(&id); - } - if let Err(e) = windmill_queue::tags::notify_fork_lineage_reset(&db).await { - tracing::warn!("failed to broadcast fork lineage change: {e:#}"); - } } + // The tag lineage reads `deleted` (an archived ancestor counts as dev lineage), and a dev + // workspace's teardown above also cleared `is_dev_workspace`. + reset_tag_lineage(&db, &w_id).await; Ok(format!( "Archived workspace {}, disabled {} schedules, canceled {} jobs and deleted {} tokens", @@ -11097,10 +11361,26 @@ async fn unarchive_workspace( ) .await?; tx.commit().await?; + reset_tag_lineage(&db, &w_id).await; Ok(format!("Unarchived workspace {}", &w_id)) } +/// Drops the tag lineage cached for `w_id` and every fork resolving through it, here and on every +/// replica, after a change to a field the lineage reads. +async fn reset_tag_lineage(db: &DB, w_id: &str) { + windmill_queue::tags::invalidate_fork_parent_cache(w_id); + for id in windmill_common::workspaces::list_fork_descendants(db, w_id) + .await + .unwrap_or_default() + { + windmill_queue::tags::invalidate_fork_parent_cache(&id); + } + if let Err(e) = windmill_queue::tags::notify_fork_lineage_reset(db).await { + tracing::warn!("failed to broadcast fork lineage change: {e:#}"); + } +} + /// Whether the instance is configured to suppress the email notifications sent /// when a user is invited or added to a workspace. Defaults to false (emails on). async fn workspace_invite_emails_disabled(db: &DB) -> Result { diff --git a/backend/windmill-api-workspaces/src/workspaces_extra.rs b/backend/windmill-api-workspaces/src/workspaces_extra.rs index 67d31f8a77..e02d7c8c3e 100644 --- a/backend/windmill-api-workspaces/src/workspaces_extra.rs +++ b/backend/windmill-api-workspaces/src/workspaces_extra.rs @@ -54,6 +54,23 @@ pub(crate) async fn change_workspace_id( require_admin(authed.is_admin, &authed.username)?; } + // An isolating fork's objects live under a prefix derived from its id: under a new id it + // would see none of them, and descendants would lose them from their read-through. + let isolates_storage = sqlx::query_scalar!( + "SELECT EXISTS (SELECT 1 FROM fork_storage_namespace WHERE workspace_id = $1)", + &old_id + ) + .fetch_one(&db) + .await? + .unwrap_or(false); + if isolates_storage { + return Err(Error::BadRequest( + "This workspace isolates its object storage from its parent under a prefix derived \ + from its id, so its id cannot be changed" + .to_string(), + )); + } + let mut tx = db.begin().await?; // The settings copy below carries every data table entry to the new id, which fork cleanup of @@ -868,11 +885,21 @@ pub(crate) async fn change_workspace_id( "Re-pushing jobs for {} enabled schedules", enabled_schedule_paths.len() ); - for schedule_path in &enabled_schedule_paths { - if let Some(schedule) = get_schedule_opt(&mut *tx, &rw.new_id, schedule_path).await? { - tx = push_scheduled_job(&db, tx, &schedule, None, None).await?; + windmill_queue::tags::carry_lineage_over_rename(&old_id, &rw.new_id, &db).await?; + let new_id = &rw.new_id; + let repushed = async { + for schedule_path in &enabled_schedule_paths { + if let Some(schedule) = get_schedule_opt(&mut *tx, new_id, schedule_path).await? { + tx = push_scheduled_job(&db, tx, &schedule, None, None).await?; + } } + Ok::<_, Error>(tx) } + .await; + if repushed.is_err() { + windmill_queue::tags::invalidate_fork_parent_cache(new_id); + } + let mut tx = repushed?; // After every workspace_settings write above: fork cleanup locks a settings row before the // registry, so taking the registry first here would deadlock with it. @@ -1099,6 +1126,34 @@ pub(crate) async fn delete_workspace( tracing::warn!("deleting workspace {w_id}: preparing ducklake cleanup: {e:#}"); vec![] }); + // A child fork reads through to this fork's prefix, or to the one this fork shares, and a + // child sharing the storage writes into it: deleting this link would destroy the child's + // data, or leave its chain without the isolating fork, writing the root's own keys. Under the + // lock forking this workspace takes, so no child can commit between the check and the delete. + windmill_common::workspaces::lock_fork_datatables(&mut tx, &w_id).await?; + let chain = windmill_common::workspaces::workspace_with_fork_ancestors(&db, &w_id).await?; + let isolating_with_children = sqlx::query_scalar!( + "SELECT EXISTS (SELECT 1 FROM fork_storage_namespace WHERE workspace_id = ANY($1)) + AND EXISTS (SELECT 1 FROM workspace WHERE parent_workspace_id = $2)", + &chain, + &w_id + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false); + if isolating_with_children { + return Err(Error::BadRequest(format!( + "the forks of {w_id} reach its fork chain's isolated object storage through it: \ + delete them first" + ))); + } + // Nothing can reach a deleted fork's prefix once it is gone, so it is always purged. + let fork_storage_purges = prepare_fork_storage_purges(&db, &w_id, None) + .await + .unwrap_or_else(|e| { + tracing::warn!("deleting workspace {w_id}: preparing storage purge: {e:#}"); + vec![] + }); sqlx::query!("DELETE FROM ai_agent_memory WHERE workspace_id = $1", &w_id) .execute(&mut *tx) @@ -1369,6 +1424,14 @@ pub(crate) async fn delete_workspace( e.msg ); } + match purge_fork_storages_unless_live(&db, &w_id, fork_storage_purges).await { + Ok(errors) => { + for e in errors { + tracing::warn!("deleted workspace {w_id}: storage purge: {e}"); + } + } + Err(e) => tracing::warn!("deleted workspace {w_id}: storage purge: {e:#}"), + } if let Some(parent) = dev_lock_parent { windmill_common::workspaces::invalidate_protection_rules_cache(&parent); @@ -2298,6 +2361,114 @@ async fn delete_fork_ducklake_data( )) } +/// A storage a fork isolated, resolved while its `$res:` still exists. +pub(crate) struct PreparedForkStoragePurge { + storage: String, + store: std::result::Result<(windmill_types::s3::LargeFileStorage, serde_json::Value), String>, +} + +/// Read-only: one entry per `fork_storage_namespace` row of `w_id`. `res_fallback_w_id` as in +/// [`prepare_fork_ducklake_cleanups`]. +pub(crate) async fn prepare_fork_storage_purges( + db: &DB, + w_id: &str, + res_fallback_w_id: Option<&str>, +) -> Result> { + let rows = sqlx::query!( + "SELECT storage, storage_ref FROM fork_storage_namespace WHERE workspace_id = $1", + w_id + ) + .fetch_all(db) + .await?; + let mut prepared = Vec::with_capacity(rows.len()); + for row in rows { + let storage = Some(row.storage.as_str()).filter(|s| !s.is_empty()); + let store = resolve_fork_storage(db, w_id, res_fallback_w_id, storage, &row.storage_ref) + .await + .map_err(|e| e.to_string()); + prepared.push(PreparedForkStoragePurge { storage: row.storage, store }); + } + Ok(prepared) +} + +/// [`purge_fork_storages`] under the lock same-id fork creation takes, unless a workspace with +/// that id exists again: the rows are then the new fork's, and its creation already purged the +/// ones it found. +pub(crate) async fn purge_fork_storages_unless_live( + db: &DB, + w_id: &str, + prepared: Vec, +) -> Result> { + // The lock only orders a purge against a same-id fork write; with nothing to purge, waiting + // on it would only hold fork creation's answer behind such a write. + if prepared.is_empty() { + return Ok(vec![]); + } + let mut lock = db.begin().await?; + sqlx::query("SELECT pg_advisory_xact_lock(hashtext('fork:' || $1))") + .bind(w_id) + .execute(&mut *lock) + .await?; + let live = sqlx::query_scalar!( + "SELECT EXISTS (SELECT 1 FROM workspace WHERE id = $1)", + w_id + ) + .fetch_one(&mut *lock) + .await? + .unwrap_or(false); + let errors = if live { + vec![] + } else { + purge_fork_storages(db, w_id, prepared).await + }; + lock.commit().await?; + Ok(errors) +} + +/// Delete everything under the fork's `__wm_forks//` in each prepared storage, then its +/// registry row. Returns one message per storage that could not be purged; its row survives. +async fn purge_fork_storages( + db: &DB, + w_id: &str, + prepared: Vec, +) -> Vec { + let area = format!( + "{}/{}", + windmill_common::workspaces::FORK_DUCKLAKE_DATA_DIR, + windmill_common::workspaces::fork_data_dir_segment(w_id) + ); + let mut errors = vec![]; + for p in prepared { + let name = if p.storage.is_empty() { + "default storage" + } else { + p.storage.as_str() + }; + let purged = match p.store { + Ok((lfs, value)) => delete_fork_ducklake_data(lfs, value, &area) + .await + .map_err(|e| e.to_string()), + Err(e) => Err(e), + }; + if let Err(e) = purged { + errors.push(format!("{name}: {e}")); + continue; + } + if let Err(e) = sqlx::query!( + "DELETE FROM fork_storage_namespace WHERE workspace_id = $1 AND storage = $2", + w_id, + p.storage + ) + .execute(db) + .await + { + errors.push(format!("{name}: removing registry row: {e}")); + } + } + windmill_common::fork_storage::invalidate_fork_storage_keys_cache(w_id); + errors +} + /// Destroying an ATTACHED dev workspace (or its data environments) must be a prod-admin /// action, not just the dev's own owner (dev ownership can diverge from prod's) — mirrors /// detach_dev_workspace. Shared by `delete_workspace` and `drop_forked_ducklake_namespaces` diff --git a/backend/windmill-api/Cargo.toml b/backend/windmill-api/Cargo.toml index b3aea64f72..583d139cf5 100644 --- a/backend/windmill-api/Cargo.toml +++ b/backend/windmill-api/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 943d05dc11..64534d0afc 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.837.0 + version: 1.841.0 title: Windmill API contact: @@ -5640,6 +5640,9 @@ paths: type: string governing_workspace_id: type: string + database_workspace_id: + type: string + description: The workspace owning the database this entry points at, when it is not this workspace. permissioned: type: boolean @@ -11413,6 +11416,34 @@ paths: schema: type: boolean + /workers/dev_workspace_isolation: + get: + summary: get whether the jobs of dev workspaces and forks run on their own worker groups + operationId: getDevWorkspaceIsolation + tags: + - worker + responses: + "200": + description: dev workspace isolation + content: + application/json: + schema: + type: object + properties: + enabled: + type: boolean + description: whether new jobs of dev workspaces and forks are queued on suffixed tags + suffix: + type: string + description: the suffix of those tags, which worker groups serving dev workspaces listen with + skip_non_dev_forks: + type: boolean + description: whether forks of a workspace that is not a dev workspace, nor under one, run on their parent's workers instead + required: + - enabled + - suffix + - skip_non_dev_forks + /w/{workspace}/workspace_dependencies/create: post: summary: create workspace dependencies @@ -25220,6 +25251,31 @@ paths: schema: $ref: "#/components/schemas/S3Resource" + /w/{workspace}/job_helpers/v2/s3_proxy_bucket: + get: + summary: Returns the bucket S3 clients name to reach a workspace storage + through the S3 proxy, or null when that storage is not S3 + operationId: s3ProxyBucket + tags: + - helpers + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: storage + in: query + schema: + type: string + responses: + "200": + description: The storage's bucket + content: + application/json: + schema: + type: object + properties: + bucket: + type: string + nullable: true + /w/{workspace}/job_helpers/test_connection: get: summary: Test connection to the workspace object storage @@ -36625,6 +36681,11 @@ components: items: type: string description: "Lake names the fork SHARES with the parent (reads and writes the parent's lake directly). Every lake not listed gets the default isolated fork namespace with read-defer to the parent." + shared_storages: + type: array + items: + type: string + description: "Workspace storages the fork SHARES with the parent (`_default_` for the primary one): it reads and writes the parent's objects directly. Every storage not listed is isolated: the fork writes under its own prefix and reads through to the parent's objects." is_dev_workspace: type: boolean description: "Create the fork as a persistent dev workspace (id not required to carry the wm-fork- prefix; at most one per parent)" @@ -39126,6 +39187,7 @@ components: - RestrictAnonymousAppDeployment - RestrictPublicRunSharing - RestrictGuestAppDeployment + - RequireIsolatedForks RuleBypasserGroups: type: array description: Groups that can bypass this ruleset diff --git a/backend/windmill-api/src/ai.rs b/backend/windmill-api/src/ai.rs index fc7a20c57f..8de5e16c11 100644 --- a/backend/windmill-api/src/ai.rs +++ b/backend/windmill-api/src/ai.rs @@ -37,8 +37,8 @@ use windmill_ai::providers::{ }, }; use windmill_ai::proxy::{ - fim::maybe_transform_fim_request, proxy_execution_mode, ProxyBuildArgs, ProxyExecutionMode, - ProxyRequest, + fim::maybe_transform_fim_request, proxy_execution_mode, validate_proxy_path, ProxyBuildArgs, + ProxyExecutionMode, ProxyRequest, }; use windmill_ai::retry::send_with_retries; use windmill_audit::{audit_oss::audit_log, ActionKind}; @@ -166,27 +166,14 @@ fn ai_http_client_builder() -> reqwest::ClientBuilder { /// after the check (DNS-rebinding TOCTOU). /// /// Returns the shared pooled [`HTTP_CLIENT`] unchanged when there is nothing to -/// pin — an IP-literal host, or a deployment that opted into private AI -/// endpoints via `ALLOW_PRIVATE_AI_BASE_URLS`. The same opt-out and error hint -/// as `get_base_url` apply, so the guard here is consistent with save-time +/// pin — an IP-literal host, or a host `ALLOW_PRIVATE_AI_BASE_URLS` allows +/// by name or wholesale. The same allowlist and error hint as `get_base_url` +/// apply, so the guard here is consistent with save-time /// validation while additionally closing the connect-time window. async fn pinned_ai_client_for(url: &str) -> Result> { use std::borrow::Cow; - use windmill_common::ssrf::SsrfValidationError; - if *windmill_ai::ai_providers::ALLOW_PRIVATE_AI_BASE_URLS { - return Ok(Cow::Borrowed(&HTTP_CLIENT)); - } - - let target = windmill_common::ssrf::validate_url_for_ssrf(url) - .await - .map_err(|e| match e { - e @ SsrfValidationError::Private { .. } => Error::BadRequest(format!( - "{e}. If you need to use private/internal AI endpoints, \ - set the ALLOW_PRIVATE_AI_BASE_URLS=true environment variable" - )), - e => Error::from(e), - })?; + let target = windmill_ai::ai_providers::validate_ai_url(url).await?; if target.pinned_addrs().is_empty() { return Ok(Cow::Borrowed(&HTTP_CLIENT)); @@ -1103,6 +1090,7 @@ async fn global_proxy( headers: HeaderMap, body: Bytes, ) -> impl IntoResponse { + validate_proxy_path(&ai_path)?; let provider = headers .get("X-Provider") .map(|v| v.to_str().unwrap_or("").to_string()); @@ -1221,6 +1209,7 @@ async fn proxy( headers: HeaderMap, mut body: Bytes, ) -> impl IntoResponse { + validate_proxy_path(&ai_path)?; let provider = headers .get("X-Provider") .map(|v| v.to_str().unwrap_or("").to_string()); diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 8343b4595d..944535dd84 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -5317,10 +5317,14 @@ async fn upload_s3_file_from_app( let user_db = UserDB::new(db.clone()); - let (s3_resource_opt, file_key, on_behalf_of_email, permissioned_as, username) = if policy - .as_ref() - .is_some_and(|p| p.s3_inputs.is_some()) - { + let ( + s3_resource_opt, + file_key, + on_behalf_of_email, + permissioned_as, + username, + is_workspace_storage, + ) = if policy.as_ref().is_some_and(|p| p.s3_inputs.is_some()) { let policy = policy.unwrap(); let s3_inputs = policy.s3_inputs.as_ref().unwrap(); @@ -5389,6 +5393,7 @@ async fn upload_s3_file_from_app( email, permissioned_as, username, + false, ) } else { return Err(Error::BadRequest( @@ -5417,6 +5422,7 @@ async fn upload_s3_file_from_app( email, permissioned_as, username, + false, ) } } else { @@ -5434,7 +5440,14 @@ async fn upload_s3_file_from_app( None, ) .await?; - (s3_resource_opt, file_key, email, permissioned_as, username) + ( + s3_resource_opt, + file_key, + email, + permissioned_as, + username, + true, + ) } } else { return Err(Error::BadRequest( @@ -5468,7 +5481,14 @@ async fn upload_s3_file_from_app( ) .await?; - (s3_resource_opt, file_key, email, permissioned_as, username) + ( + s3_resource_opt, + file_key, + email, + permissioned_as, + username, + true, + ) } } else { // backward compatibility (no policy) @@ -5500,6 +5520,7 @@ async fn upload_s3_file_from_app( on_behalf_of_email, permissioned_as, username, + false, ) } else { let db_with_opt_authed = DbWithOptAuthed::from_authed(&authed, db.clone(), None); @@ -5519,6 +5540,7 @@ async fn upload_s3_file_from_app( on_behalf_of_email, permissioned_as, username, + true, ) } } else { @@ -5529,7 +5551,19 @@ async fn upload_s3_file_from_app( let s3_resource = s3_resource_opt.ok_or(Error::internal_err( "No files storage resource defined at the workspace level".to_string(), ))?; - let s3_client = windmill_object_store::build_object_store_client(&s3_resource).await?; + // The quota sizes an overwrite by the fork's own copy: a fork's write never replaces the + // ancestor's object its reads fall through to. + type Client = std::sync::Arc; + let (s3_client, _quota_client): (Client, Client) = if is_workspace_storage { + let store = + windmill_object_store::fork_store::workspace_fork_store(&db, &w_id, None, &s3_resource) + .await?; + let own_only = store.own_only(); + (store, own_only) + } else { + let client = windmill_object_store::build_object_store_client(&s3_resource).await?; + (client.clone(), client) + }; let options = Attributes::from_iter(vec![ ( @@ -5562,7 +5596,8 @@ async fn upload_s3_file_from_app( .get(http::header::CONTENT_LENGTH) .and_then(|h| h.to_str().ok()) .and_then(|s| s.parse::().ok()); - let budget = ce_upload_budget(&db, &w_id, &s3_client, &file_key, content_length).await?; + let budget = + ce_upload_budget(&db, &w_id, &_quota_client, &file_key, content_length).await?; (Some(budget.max_size), budget.existing_size) } else { (None, 0) @@ -5644,6 +5679,7 @@ async fn delete_s3_file_from_app( ) .await?; + let is_workspace_storage = s3_resource_path.is_none(); let s3_resource = if let Some(s3_resource_path) = s3_resource_path { let db_with_opt_authed = DbWithOptAuthed::from_authed(&on_behalf_authed, db.clone(), Some(user_db.clone())); @@ -5672,7 +5708,12 @@ async fn delete_s3_file_from_app( ))? }; - let s3_client = windmill_object_store::build_object_store_client(&s3_resource).await?; + let s3_client = if is_workspace_storage { + windmill_object_store::fork_store::workspace_object_store(&db, &w_id, None, &s3_resource) + .await? + } else { + windmill_object_store::build_object_store_client(&s3_resource).await? + }; s3_client.delete(&path).await.map_err(|err| { tracing::error!("Error deleting file: {:?}", err); diff --git a/backend/windmill-api/src/args.rs b/backend/windmill-api/src/args.rs index 7e676989b2..6c1c9824bd 100644 --- a/backend/windmill-api/src/args.rs +++ b/backend/windmill-api/src/args.rs @@ -139,13 +139,13 @@ impl RawWebhookArgs { get_random_file_name, get_workspace_s3_resource, upload_file_internal, }; use futures::TryStreamExt; - use windmill_object_store::build_object_store_client; + use windmill_object_store::fork_store::workspace_object_store; use windmill_object_store::object_store_reexports::{Attribute, Attributes}; let (_, s3_resource) = get_workspace_s3_resource(authed, db, None, w_id, None).await?; if let Some(s3_resource) = s3_resource { - let s3_client = build_object_store_client(&s3_resource).await?; + let s3_client = workspace_object_store(db, w_id, None, &s3_resource).await?; let mut parts: Vec<(String, MultipartValue)> = Vec::new(); diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index c567a593d9..a7e2915571 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -9264,6 +9264,7 @@ async fn run_inline_preview_script( return Err(operator_preview_refusal(job_id)); } check_scopes(&authed, || format!("jobs:run"))?; + windmill_queue::tags::check_inline_run_allowed(&w_id, &db).await?; if let Some(job_id) = job_id { register_potential_assets_on_inline_execution(job_id, &w_id, &preview); } @@ -9383,6 +9384,7 @@ async fn run_inline_script_inner( args: Option>>, user_db: Option, ) -> error::Result { + windmill_queue::tags::check_inline_run_allowed(&w_id, &db).await?; // An inline run executes with the caller's own token, so it cannot honour a script's // `job_token_scopes`: such a script only runs as a job. A path is resolved here, once, and // the version checked is the version run. @@ -10183,17 +10185,22 @@ async fn add_batch_jobs( let language = language.unwrap_or(ScriptLang::Deno); - let tag = if let Some(dedicated_worker) = dedicated_worker { + let tag = match (dedicated_worker, batch_info.tag) { // Same rule as `push`: a dedicated worker would run it with its own unscoped token. - if dedicated_worker && path.is_some() && job_token_scopes.is_none() { + (Some(true), _) if path.is_some() && job_token_scopes.is_none() => { windmill_common::worker::dedicated_worker_tag(&w_id, &path.clone().unwrap()) - } else { - format!("{}", language.as_str()) } - } else if let Some(tag) = batch_info.tag { - tag - } else { - format!("{}", language.as_str()) + (None, Some(tag)) => { + windmill_queue::tags::apply_dev_workspace_suffix(tag, &w_id, &db).await? + } + _ => { + windmill_queue::tags::apply_dev_workspace_suffix( + language.as_str().to_string(), + &w_id, + &db, + ) + .await? + } }; let mut tx = user_db.begin(&authed).await?; diff --git a/backend/windmill-api/src/triggers/http/handler.rs b/backend/windmill-api/src/triggers/http/handler.rs index 3d85904e50..5db6bf303d 100644 --- a/backend/windmill-api/src/triggers/http/handler.rs +++ b/backend/windmill-api/src/triggers/http/handler.rs @@ -34,10 +34,7 @@ use windmill_store::resources::try_get_resource_from_db_as; use windmill_trigger::TriggerMode; #[cfg(feature = "parquet")] -use { - crate::job_helpers_oss::get_workspace_s3_resource, - windmill_object_store::build_object_store_client, -}; +use crate::job_helpers_oss::get_workspace_s3_resource; /// Which router a request's CORS decision must be looked up in. /// @@ -624,7 +621,13 @@ async fn route_job( let s3_resource = s3_resource_opt.ok_or_else(|| { windmill_object_store::workspace_storage_misconfigured(config.storage.as_deref()) })?; - let s3_client = build_object_store_client(&s3_resource).await?; + let s3_client = windmill_object_store::fork_store::workspace_object_store( + &db, + &trigger.workspace_id, + config.storage.as_deref(), + &s3_resource, + ) + .await?; let path = if trigger.is_static_website { let subpath = params diff --git a/backend/windmill-audit/Cargo.toml b/backend/windmill-audit/Cargo.toml index 8c26615664..a1491b3b5d 100644 --- a/backend/windmill-audit/Cargo.toml +++ b/backend/windmill-audit/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_audit" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] enterprise = ["windmill-common/enterprise"] diff --git a/backend/windmill-autoscaling/Cargo.toml b/backend/windmill-autoscaling/Cargo.toml index fd5c5f4703..592529b2fe 100644 --- a/backend/windmill-autoscaling/Cargo.toml +++ b/backend/windmill-autoscaling/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_autoscaling" path = "./src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] enterprise = ["windmill-queue/enterprise", "windmill-common/enterprise"] diff --git a/backend/windmill-common/Cargo.toml b/backend/windmill-common/Cargo.toml index e447baf563..52c38908b5 100644 --- a/backend/windmill-common/Cargo.toml +++ b/backend/windmill-common/Cargo.toml @@ -46,6 +46,7 @@ chrono.workspace = true chrono-tz.workspace = true hex.workspace = true async-trait.workspace = true +http.workspace = true reqwest-middleware = { workspace = true } reqwest-retry = { workspace = true } rand.workspace = true @@ -110,6 +111,7 @@ strum.workspace = true strum_macros.workspace = true windmill-types.workspace = true url.workspace = true +ipnet.workspace = true urlencoding.workspace = true async-recursion.workspace = true pep440_rs.workspace = true diff --git a/backend/windmill-common/src/agent_workers.rs b/backend/windmill-common/src/agent_workers.rs index 30c84f5807..33304dec94 100644 --- a/backend/windmill-common/src/agent_workers.rs +++ b/backend/windmill-common/src/agent_workers.rs @@ -6,37 +6,83 @@ pub struct QueueInitJob { } use lazy_static::lazy_static; -use std::time::Duration; +use std::{path::PathBuf, time::Duration}; use reqwest_middleware::ClientBuilder; use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware}; use crate::{jwt::decode_without_verify, utils::configure_client, worker::HttpClient}; -/// Configuration required for agent mode. Both fields are mandatory when running in agent mode. +/// How an agent proves its identity to the server. +#[derive(Clone)] +pub enum AgentCredential { + /// `AGENT_TOKEN`: an agent token a superadmin minted. + Token(String), + /// `AGENT_IDENTITY_TOKEN_FILE`: a workload identity token the platform keeps rotating on + /// disk, re-read on every request. + IdentityTokenFile(PathBuf), +} + +/// Configuration required for agent mode: a credential and the server's URL. #[derive(Clone)] pub struct AgentConfig { - pub agent_token: String, + pub credential: AgentCredential, pub base_internal_url: String, } impl AgentConfig { pub fn from_env() -> Result { - let agent_token = - std::env::var("AGENT_TOKEN").map_err(|_| AgentConfigError::MissingAgentToken)?; + let credential = match ( + std::env::var("AGENT_TOKEN").ok(), + std::env::var(AGENT_IDENTITY_TOKEN_FILE_ENV).ok(), + ) { + (Some(_), Some(_)) => return Err(AgentConfigError::BothCredentials), + (Some(token), None) => AgentCredential::Token(token), + (None, Some(path)) => AgentCredential::IdentityTokenFile(PathBuf::from(path)), + (None, None) => return Err(AgentConfigError::MissingAgentToken), + }; let base_internal_url = std::env::var("BASE_INTERNAL_URL") .map_err(|_| AgentConfigError::MissingBaseInternalUrl)?; - Ok(Self { agent_token, base_internal_url }) + Ok(Self { credential, base_internal_url }) } pub fn build_http_client(&self, worker_suffix: &str) -> HttpClient { - build_agent_http_client(worker_suffix, &self.agent_token, &self.base_internal_url) + match &self.credential { + AgentCredential::Token(token) => { + build_agent_http_client(worker_suffix, token, &self.base_internal_url) + } + AgentCredential::IdentityTokenFile(path) => { + build_agent_http_client_inner(&self.base_internal_url, None, |builder| { + builder.with(IdentityTokenAuth { + path: path.clone(), + worker_suffix: worker_suffix.to_string(), + }) + }) + } + } + } + + /// With a workload identity token the worker group and tags are whatever rule the server + /// matched, so they are asked for before anything reads [`DECODED_AGENT_TOKEN`] (and + /// through it `WORKER_GROUP`). A no-op with a static agent token, which carries them. + pub async fn resolve_workload_identity(&self, worker_suffix: &str) -> anyhow::Result<()> { + if let AgentCredential::IdentityTokenFile(_) = self.credential { + let auth: AgentAuth = self + .build_http_client(worker_suffix) + .get("/api/agent_workers/whoami") + .await?; + let _ = AGENT_WORKLOAD_IDENTITY_AUTH.set(auth); + } + Ok(()) } } +pub const AGENT_IDENTITY_TOKEN_FILE_ENV: &str = "AGENT_IDENTITY_TOKEN_FILE"; + #[derive(Debug)] pub enum AgentConfigError { MissingAgentToken, + BothCredentials, MissingBaseInternalUrl, } @@ -46,7 +92,13 @@ impl std::fmt::Display for AgentConfigError { AgentConfigError::MissingAgentToken => { write!( f, - "AGENT_TOKEN environment variable is not set but required for agent mode" + "AGENT_TOKEN or AGENT_IDENTITY_TOKEN_FILE environment variable is required for agent mode" + ) + } + AgentConfigError::BothCredentials => { + write!( + f, + "AGENT_TOKEN and AGENT_IDENTITY_TOKEN_FILE are mutually exclusive, set only one" ) } AgentConfigError::MissingBaseInternalUrl => { @@ -61,17 +113,56 @@ impl std::fmt::Display for AgentConfigError { impl std::error::Error for AgentConfigError {} +/// Sets the bearer from the identity token file on each request, so a token the platform +/// rotated on disk is picked up without a restart. +struct IdentityTokenAuth { + path: PathBuf, + worker_suffix: String, +} + +#[async_trait::async_trait] +impl reqwest_middleware::Middleware for IdentityTokenAuth { + async fn handle( + &self, + mut req: reqwest::Request, + extensions: &mut http::Extensions, + next: reqwest_middleware::Next<'_>, + ) -> reqwest_middleware::Result { + let token = tokio::fs::read_to_string(&self.path).await.map_err(|e| { + reqwest_middleware::Error::middleware(std::io::Error::new( + e.kind(), + format!( + "reading {AGENT_IDENTITY_TOKEN_FILE_ENV} {}: {e}", + self.path.display() + ), + )) + })?; + let header = format!( + "Bearer {AGENT_WORKLOAD_IDENTITY_PREFIX}{}{AGENT_WORKLOAD_IDENTITY_SEPARATOR}{}", + self.worker_suffix, + token.trim() + ) + .parse() + .map_err(reqwest_middleware::Error::middleware)?; + req.headers_mut() + .insert(reqwest::header::AUTHORIZATION, header); + next.run(req, extensions).await + } +} + lazy_static! { pub static ref DECODED_AGENT_TOKEN: Option = { let agent_token = std::env::var("AGENT_TOKEN"); if let Ok(token) = agent_token { decode_without_verify::(token.trim_start_matches(AGENT_JWT_PREFIX)).ok() } else { - None + AGENT_WORKLOAD_IDENTITY_AUTH.get().cloned() } }; } +static AGENT_WORKLOAD_IDENTITY_AUTH: std::sync::OnceLock = std::sync::OnceLock::new(); + #[derive(Clone, Debug, Deserialize, Serialize)] pub struct AgentAuth { pub worker_group: String, @@ -81,11 +172,29 @@ pub struct AgentAuth { } pub const AGENT_JWT_PREFIX: &str = "jwt_agent_"; +/// `wid_agent_:`. A worker suffix may contain `_` (a +/// `WORKER_SUFFIX` label) and a JWT may contain `_` (base64url) but neither contains `:`. +pub const AGENT_WORKLOAD_IDENTITY_PREFIX: &str = "wid_agent_"; +pub const AGENT_WORKLOAD_IDENTITY_SEPARATOR: char = ':'; pub fn build_agent_http_client( worker_suffix: &str, agent_token: &str, base_internal_url: &str, +) -> HttpClient { + let token = format!( + "{}{}_{}", + AGENT_JWT_PREFIX, + worker_suffix, + agent_token.trim_start_matches(AGENT_JWT_PREFIX) + ); + build_agent_http_client_inner(base_internal_url, Some(token), |builder| builder) +} + +fn build_agent_http_client_inner( + base_internal_url: &str, + static_token: Option, + with_auth: impl FnOnce(ClientBuilder) -> ClientBuilder, ) -> HttpClient { let client = ClientBuilder::new( configure_client( @@ -101,16 +210,12 @@ pub fn build_agent_http_client( "User-Agent", // Replace with your desired header name "Windmill-Agent/1.0".parse().unwrap(), // Replace with your desired header value ); - let token = format!( - "{}{}_{}", - AGENT_JWT_PREFIX, - worker_suffix, - agent_token.trim_start_matches(AGENT_JWT_PREFIX) - ); - headers.insert( - "Authorization", - format!("Bearer {}", token).parse().unwrap(), - ); + if let Some(token) = static_token { + headers.insert( + "Authorization", + format!("Bearer {}", token).parse().unwrap(), + ); + } headers }) .build() @@ -118,10 +223,12 @@ pub fn build_agent_http_client( ) .with(RetryTransientMiddleware::new_with_policy( ExponentialBackoff::builder().build_with_max_retries(5), - )) - .build(); + )); - HttpClient { client, base_internal_url: base_internal_url.to_string() } + HttpClient { + client: with_auth(client).build(), + base_internal_url: base_internal_url.to_string(), + } } #[derive(Deserialize, Serialize)] diff --git a/backend/windmill-common/src/agent_workload_identity.rs b/backend/windmill-common/src/agent_workload_identity.rs new file mode 100644 index 0000000000..437b867063 --- /dev/null +++ b/backend/windmill-common/src/agent_workload_identity.rs @@ -0,0 +1,475 @@ +//! Agent worker authentication with a workload identity token: a JWT the platform the agent +//! runs on issues to it (a Kubernetes projected service account token, a SPIFFE JWT-SVID, ...), +//! verified against an issuer the superadmin trusts in `agent_workload_identity_issuers`. +//! The worker group and tags come from the first rule whose claims the token matches, never +//! from the token's own say, so the tag checks the static agent token path applies hold as is. + +use std::collections::HashMap; +use std::sync::Arc; + +use jsonwebtoken::{jwk::Jwk, Algorithm, DecodingKey, Validation}; +use serde_json::Value; + +use crate::error::Result; +use crate::guest_jwt::{cached_jwks_keys, jwk_algorithms, parse_jwks_keys, JwksSource}; +use crate::instance_config::{AgentWorkloadIdentityIssuer, AgentWorkloadIdentityRule}; + +/// A projected service account token is about 1 KB; refused past this before any work. +const MAX_TOKEN_LEN: usize = 16 * 1024; + +/// Why a token was refused. `issuer` is set once the token named a trusted one. The reason +/// goes to the server log and the audit log, never to the client. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refusal { + pub issuer: Option, + /// The token's `sub`, set only once its signature verified, so a caller cannot vary it. + pub verified_subject: Option, + pub reason: String, +} + +impl Refusal { + fn new(issuer: Option<&str>, reason: impl Into) -> Self { + Self { issuer: issuer.map(str::to_string), verified_subject: None, reason: reason.into() } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WorkloadIdentity { + pub issuer: String, + pub subject: Option, + pub worker_group: String, + pub tags: Vec, + pub exp: u64, +} + +/// The setting's raw value, as both the settings API and the declarative sync receive it. +pub fn validate_issuers_value(value: &Value) -> std::result::Result<(), String> { + let issuers: Vec = + serde_json::from_value(value.clone()).map_err(|e| e.to_string())?; + validate_issuers(&issuers) +} + +/// Rejects what would make a rule set ambiguous or a rule match more than intended. Runtime +/// matching skips a rule without claims too, so a setting planted around this check cannot +/// admit every token of an issuer. +pub fn validate_issuers( + issuers: &[AgentWorkloadIdentityIssuer], +) -> std::result::Result<(), String> { + let mut seen = std::collections::HashSet::new(); + for (i, cfg) in issuers.iter().enumerate() { + let at = format!("issuer #{} ({})", i + 1, cfg.issuer); + if cfg.issuer.trim().is_empty() { + return Err(format!("issuer #{}: issuer is required", i + 1)); + } + if !seen.insert(cfg.issuer.as_str()) { + return Err(format!("{at}: listed more than once")); + } + if cfg.audience.trim().is_empty() { + return Err(format!("{at}: audience is required")); + } + match (&cfg.jwks, &cfg.jwks_uri) { + (Some(jwks), _) if !jwks.trim().is_empty() => { + parse_jwks_keys(jwks.as_bytes()).map_err(|e| format!("{at}: inline JWKS: {e}"))?; + } + (_, Some(uri)) if !uri.trim().is_empty() => { + if !(uri.starts_with("https://") || uri.starts_with("http://")) { + return Err(format!("{at}: jwks_uri must be an http(s) URL")); + } + } + _ => { + if !(cfg.issuer.starts_with("https://") || cfg.issuer.starts_with("http://")) { + return Err(format!( + "{at}: without jwks_uri or an inline JWKS, the issuer must be an http(s) URL \ + serving OIDC discovery" + )); + } + } + } + if cfg.rules.is_empty() { + return Err(format!("{at}: at least one rule is required")); + } + for (j, rule) in cfg.rules.iter().enumerate() { + let at = format!("{at}, rule #{}", j + 1); + if rule.claims.is_empty() + || rule + .claims + .iter() + .any(|(k, v)| k.trim().is_empty() || v.trim().is_empty()) + { + return Err(format!( + "{at}: at least one claim to match is required, each with a path and a value" + )); + } + if rule.worker_group.trim().is_empty() + || rule.worker_group.contains(char::is_whitespace) + { + return Err(format!("{at}: worker group is required and has no spaces")); + } + if rule.tags.is_empty() || rule.tags.iter().any(|t| t.trim().is_empty()) { + return Err(format!("{at}: at least one non-empty tag is required")); + } + } + } + Ok(()) +} + +/// The value at a dot separated claim path. At each level the longest key that prefixes the +/// remaining path is tried first, so `kubernetes.io.namespace` reaches `namespace` under the +/// `kubernetes.io` key. +fn claim_at<'a>(value: &'a Value, path: &str) -> Option<&'a Value> { + let obj = value.as_object()?; + if let Some(v) = obj.get(path) { + return Some(v); + } + path.match_indices('.') + .rev() + .find_map(|(i, _)| claim_at(obj.get(&path[..i])?, &path[i + 1..])) +} + +fn claim_matches(claims: &Value, path: &str, expected: &str) -> bool { + match claim_at(claims, path) { + Some(Value::String(s)) => s == expected, + Some(v @ (Value::Number(_) | Value::Bool(_))) => v.to_string() == expected, + _ => false, + } +} + +pub fn matching_rule<'a>( + rules: &'a [AgentWorkloadIdentityRule], + claims: &Value, +) -> Option<&'a AgentWorkloadIdentityRule> { + rules.iter().find(|rule| { + !rule.claims.is_empty() + && rule + .claims + .iter() + .all(|(path, expected)| claim_matches(claims, path, expected)) + }) +} + +/// The header's `alg`, read raw: `jsonwebtoken` cannot parse `none`, and a refusal should say +/// which algorithm was offered rather than that the header is malformed. +fn header_alg(token: &str) -> std::result::Result { + use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; + let header = token.split('.').next().unwrap_or_default(); + let header: Value = URL_SAFE_NO_PAD + .decode(header.trim_end_matches('=')) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .ok_or("malformed JWT header")?; + let alg = header.get("alg").and_then(Value::as_str).unwrap_or(""); + match alg.parse::() { + Ok( + a @ (Algorithm::RS256 + | Algorithm::RS384 + | Algorithm::RS512 + | Algorithm::PS256 + | Algorithm::PS384 + | Algorithm::PS512 + | Algorithm::ES256 + | Algorithm::ES384), + ) => Ok(a), + _ => Err(format!( + "alg {alg:?} is not accepted, only RS*, PS* and ES*" + )), + } +} + +/// Verify `token` against the trusted `issuers` and map it to a worker group and tags. +pub async fn verify( + issuers: &[AgentWorkloadIdentityIssuer], + token: &str, +) -> std::result::Result { + if token.len() > MAX_TOKEN_LEN { + return Err(Refusal::new(None, "token is too long")); + } + let alg = header_alg(token).map_err(|r| Refusal::new(None, r))?; + let kid = jsonwebtoken::decode_header(token) + .map_err(|e| Refusal::new(None, format!("malformed JWT header: {e}")))? + .kid; + let unverified: Value = crate::jwt::decode_without_verify(token) + .map_err(|e| Refusal::new(None, format!("malformed JWT payload: {e}")))?; + let iss = unverified.get("iss").and_then(Value::as_str).unwrap_or(""); + let cfg = issuers + .iter() + .find(|c| c.issuer == iss) + .ok_or_else(|| Refusal::new(None, format!("issuer {iss:?} is not trusted")))?; + let refuse = |reason: String| Refusal::new(Some(&cfg.issuer), reason); + + let keys = issuer_keys(cfg) + .await + .map_err(|e| refuse(format!("signing keys unavailable: {e}")))?; + let candidates: Vec<&Jwk> = match &kid { + Some(kid) => keys.get(kid).into_iter().collect(), + None => keys.values().collect(), + }; + let candidates: Vec<&Jwk> = candidates + .into_iter() + .filter(|jwk| jwk_algorithms(jwk).is_some_and(|algs| algs.contains(&alg))) + .collect(); + if candidates.is_empty() { + return Err(refuse(match &kid { + Some(kid) => format!("no {alg:?} signing key with kid {kid:?} in the issuer's JWKS"), + None => format!("no {alg:?} signing key in the issuer's JWKS"), + })); + } + + let mut validation = Validation::new(alg); + validation.set_audience(&[&cfg.audience]); + validation.set_issuer(&[&cfg.issuer]); + validation.set_required_spec_claims(&["exp", "iss", "aud"]); + validation.validate_nbf = true; + let mut last_err = None; + let mut claims = None; + for jwk in candidates { + let key = match DecodingKey::from_jwk(jwk) { + Ok(key) => key, + Err(e) => { + last_err = Some(e.to_string()); + continue; + } + }; + match jsonwebtoken::decode::(token, &key, &validation) { + Ok(data) => { + claims = Some(data.claims); + break; + } + Err(e) => last_err = Some(describe_jwt_error(&e, &cfg.audience)), + } + } + let claims = claims.ok_or_else(|| refuse(last_err.unwrap_or_default()))?; + + let subject = claims + .get("sub") + .and_then(Value::as_str) + .map(str::to_string); + let rule = matching_rule(&cfg.rules, &claims).ok_or_else(|| Refusal { + verified_subject: subject.clone(), + ..refuse(format!( + "no rule matches the token (sub {})", + subject.as_deref().unwrap_or("") + )) + })?; + Ok(WorkloadIdentity { + issuer: cfg.issuer.clone(), + subject, + worker_group: rule.worker_group.clone(), + tags: rule.tags.clone(), + exp: claims.get("exp").and_then(Value::as_u64).unwrap_or(0), + }) +} + +fn describe_jwt_error(e: &jsonwebtoken::errors::Error, audience: &str) -> String { + use jsonwebtoken::errors::ErrorKind; + match e.kind() { + ErrorKind::InvalidSignature => "signature does not verify".to_string(), + ErrorKind::ExpiredSignature => "token is expired".to_string(), + ErrorKind::ImmatureSignature => "token is not valid yet (nbf)".to_string(), + ErrorKind::InvalidAudience => format!("aud does not include {audience:?}"), + ErrorKind::InvalidIssuer => "iss does not match".to_string(), + ErrorKind::MissingRequiredClaim(c) => format!("required claim {c} is missing"), + _ => format!("token refused: {e}"), + } +} + +async fn issuer_keys(cfg: &AgentWorkloadIdentityIssuer) -> Result>> { + if let Some(jwks) = cfg.jwks.as_deref().filter(|j| !j.trim().is_empty()) { + return Ok(Arc::new(parse_jwks_keys(jwks.as_bytes())?)); + } + cached_jwks_keys(&JwksSource::TrustedIssuer { + issuer: cfg.issuer.clone(), + jwks_uri: cfg.jwks_uri.clone(), + }) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + use jsonwebtoken::{EncodingKey, Header}; + use serde_json::json; + use std::collections::BTreeMap; + + // Throwaway P-256 keys, used nowhere else. `JWKS` publishes the first one. + const PRIV: &str = "-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgu7FqG4gEcV8logVI +B6/Lc5aFA8jxKmix7Jdcr/acid2hRANCAATV+8XhZlMNXkRAy7FZ4nbQkBOechNv +a2U/COEBOOauFRMd0NB5bi2DAqO1r/h7eN7fLMGYLXVPlSvNdJuYL4F8 +-----END PRIVATE KEY-----"; + const OTHER_PRIV: &str = "-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgcU92tN6g4nOPoxQm +6KLBG0mtRL4gZ6/BNcrNPXiRammhRANCAASu64yo/1u80XgfncT4r9QMORMHZjDM +Sa6vBkm9YSs4MMV6K5vCIyow+i712HgUL/FNZ55GJVwXF77JffommMAk +-----END PRIVATE KEY-----"; + const JWKS: &str = r#"{"keys":[{"kty":"EC","crv":"P-256","alg":"ES256","use":"sig","kid":"k1", + "x":"1fvF4WZTDV5EQMuxWeJ20JATnnITb2tlPwjhATjmrhU", + "y":"Ex3Q0HluLYMCo7Wv-Ht43t8swZgtdU-VK810m5gvgXw"}]}"#; + const ISS: &str = "https://kubernetes.default.svc.cluster.local"; + + fn issuer() -> AgentWorkloadIdentityIssuer { + AgentWorkloadIdentityIssuer { + issuer: ISS.to_string(), + jwks_uri: None, + jwks: Some(JWKS.to_string()), + audience: "windmill".to_string(), + rules: vec![ + AgentWorkloadIdentityRule { + claims: BTreeMap::from([( + "sub".to_string(), + "system:serviceaccount:agents:gpu".to_string(), + )]), + worker_group: "gpu".to_string(), + tags: vec!["gpu".to_string()], + }, + AgentWorkloadIdentityRule { + claims: BTreeMap::from([( + "kubernetes.io.namespace".to_string(), + "agents".to_string(), + )]), + worker_group: "agents".to_string(), + tags: vec!["dbt".to_string(), "etl".to_string()], + }, + ], + } + } + + fn claims(sub: &str, ns: &str) -> Value { + let now = jsonwebtoken::get_current_timestamp(); + json!({ + "iss": ISS, "aud": ["windmill"], "sub": sub, "exp": now + 600, "iat": now, "nbf": now, + "kubernetes.io": {"namespace": ns, "serviceaccount": {"name": "x"}}, + }) + } + + fn sign(claims: &Value, pem: &str, alg: Algorithm) -> String { + let mut header = Header::new(alg); + header.kid = Some("k1".to_string()); + jsonwebtoken::encode( + &header, + claims, + &EncodingKey::from_ec_pem(pem.as_bytes()).unwrap(), + ) + .unwrap() + } + + async fn reason(token: &str) -> String { + verify(&[issuer()], token).await.unwrap_err().reason + } + + #[tokio::test] + async fn first_matching_rule_decides_group_and_tags() { + let id = verify( + &[issuer()], + &sign( + &claims("system:serviceaccount:agents:gpu", "agents"), + PRIV, + Algorithm::ES256, + ), + ) + .await + .unwrap(); + assert_eq!( + (id.worker_group.as_str(), id.tags), + ("gpu", vec!["gpu".to_string()]) + ); + // A dotted key (`kubernetes.io`) is reached through a nested path. + let id = verify( + &[issuer()], + &sign( + &claims("system:serviceaccount:agents:etl", "agents"), + PRIV, + Algorithm::ES256, + ), + ) + .await + .unwrap(); + assert_eq!(id.worker_group, "agents"); + assert!(reason(&sign( + &claims("system:serviceaccount:other:etl", "other"), + PRIV, + Algorithm::ES256 + )) + .await + .starts_with("no rule matches")); + } + + #[tokio::test] + async fn refuses_wrong_iss_aud_exp_key_and_alg() { + let ok = claims("system:serviceaccount:agents:gpu", "agents"); + let with = |k: &str, v: Value| { + let mut c = ok.clone(); + c[k] = v; + sign(&c, PRIV, Algorithm::ES256) + }; + assert!(reason(&with("iss", json!("https://evil"))) + .await + .contains("not trusted")); + assert!(reason(&with("aud", json!("other"))).await.contains("aud")); + assert!(reason(&with("exp", json!(1_000_000))) + .await + .contains("expired")); + assert!(reason(&sign(&ok, OTHER_PRIV, Algorithm::ES256)) + .await + .contains("signature")); + + let hs = jsonwebtoken::encode( + &Header::new(Algorithm::HS256), + &ok, + &EncodingKey::from_secret(b"s"), + ) + .unwrap(); + assert!(reason(&hs).await.contains("not accepted")); + use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; + let none = format!( + "{}.{}.", + URL_SAFE_NO_PAD.encode(br#"{"alg":"none","kid":"k1"}"#), + URL_SAFE_NO_PAD.encode(ok.to_string()) + ); + assert!(reason(&none).await.contains("not accepted")); + } + + #[tokio::test] + async fn failed_key_fetches_are_throttled() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let hits = Arc::new(AtomicUsize::new(0)); + let counted = hits.clone(); + tokio::spawn(async move { + while let Ok((conn, _)) = listener.accept().await { + counted.fetch_add(1, Ordering::SeqCst); + drop(conn); + } + }); + let mut cfg = issuer(); + cfg.issuer = format!("https://throttle-test-{}", addr.port()); + cfg.jwks = None; + cfg.jwks_uri = Some(format!("http://{addr}/jwks")); + let mut c = claims("system:serviceaccount:agents:gpu", "agents"); + c["iss"] = json!(cfg.issuer); + for _ in 0..3 { + let refusal = verify(&[cfg.clone()], &sign(&c, PRIV, Algorithm::ES256)) + .await + .unwrap_err(); + assert!( + refusal.reason.contains("signing keys unavailable"), + "{}", + refusal.reason + ); + } + assert_eq!(hits.load(Ordering::SeqCst), 1); + } + + #[test] + fn rule_without_claims_never_matches() { + let rules = vec![AgentWorkloadIdentityRule { + claims: BTreeMap::new(), + worker_group: "g".to_string(), + tags: vec!["t".to_string()], + }]; + assert!(matching_rule(&rules, &json!({"sub": "x"})).is_none()); + let mut cfg = issuer(); + cfg.rules = rules; + assert!(validate_issuers(&[cfg]).is_err()); + } +} diff --git a/backend/windmill-common/src/fork_storage.rs b/backend/windmill-common/src/fork_storage.rs new file mode 100644 index 0000000000..8d2797ab3c --- /dev/null +++ b/backend/windmill-common/src/fork_storage.rs @@ -0,0 +1,394 @@ +//! Where a workspace's object keys live in a storage it may share with its fork ancestors. +//! +//! A fork that isolates a storage (a `fork_storage_namespace` row) writes logical key `k` at +//! `__wm_forks//k` and reads `k` from the first of its own and its ancestors' +//! locations that has it. Everything under `__wm_forks/` is reachable only through the areas of +//! the workspace's own chain, which is also what DuckLake's fork namespaces live in: those keys +//! arrive already prefixed and pass through unchanged. + +use std::sync::Arc; + +use quick_cache::sync::Cache; + +use crate::error::{Error, Result}; +use crate::workspaces::{ + fork_data_dir_segment, lfs_entry_storage_ref, workspace_with_fork_ancestors, + FORK_DUCKLAKE_DATA_DIR, +}; +use crate::DB; + +/// How one workspace's logical keys map to physical keys in one of its storages. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ForkStorageKeys { + /// Prefix of every write: `__wm_forks//` in an isolating fork, `""` otherwise. + write_prefix: String, + /// Prefixes a read tries in order, nearest first. + read_prefixes: Vec, + /// `__wm_forks//` of this workspace, writable as is. + own_area: String, + /// The fork areas of this workspace and its ancestors, readable as is. + readable_areas: Vec, +} + +/// A listing request translated to the physical storage. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ListMapping { + pub physical_prefix: String, + /// Stripped from each physical key to get the logical key returned to the caller. + strip: String, + /// Logical keys under `__wm_forks/` are dropped: reached only by listing that area itself. + hide_fork_area: bool, +} + +impl ListMapping { + /// Whether listed keys differ from what the caller may see: false lets a listing response + /// be passed through untouched. + pub fn rewrites(&self) -> bool { + let fork_dir = format!("{FORK_DUCKLAKE_DATA_DIR}/"); + !self.strip.is_empty() + || (self.hide_fork_area && fork_dir.starts_with(&self.physical_prefix)) + } + + /// The physical form of a logical key of this listing, e.g. a start-after cursor. + pub fn physical_key(&self, logical: &str) -> String { + format!("{}{logical}", self.strip) + } + + /// The logical key for a listed physical key, or None when the caller must not see it. + pub fn logical_key(&self, physical: &str) -> Option { + let logical = physical.strip_prefix(self.strip.as_str())?; + if self.hide_fork_area && in_fork_area(logical) { + return None; + } + Some(logical.to_string()) + } +} + +fn in_fork_area(key: &str) -> bool { + key == FORK_DUCKLAKE_DATA_DIR + || key + .strip_prefix(FORK_DUCKLAKE_DATA_DIR) + .is_some_and(|rest| rest.starts_with('/')) +} + +fn fork_area(w_id: &str) -> String { + format!("{FORK_DUCKLAKE_DATA_DIR}/{}/", fork_data_dir_segment(w_id)) +} + +fn forbidden(key: &str) -> Error { + Error::NotAuthorized(format!( + "`{key}` is in another workspace's fork namespace (`{FORK_DUCKLAKE_DATA_DIR}/`)" + )) +} + +/// The S3 proxy forwards mapped keys in a URL, where clients and signers collapse `.` and `..` +/// segments: `../../k` would reach the parent's `k`. +fn reject_dot_segments(key: &str) -> Result<&str> { + let key = key.trim_start_matches('/'); + if key.split('/').any(|s| s == "." || s == "..") { + return Err(Error::BadRequest(format!( + "`{key}` has a `.` or `..` path segment, which object storage keys may not use here" + ))); + } + Ok(key) +} + +/// One workspace of a fork chain, nearest first, as the storage mapping needs it. +#[derive(Debug, Clone)] +pub struct ChainLink { + pub w_id: String, + /// Identity of the storage in this workspace's settings (`lfs_entry_storage_ref`). + pub storage_ref: Option, + pub isolated: bool, +} + +impl ForkStorageKeys { + /// The mapping of `chain[0]`. Reads stop at the first ancestor whose storage is a different + /// one: its keys are not in this bucket. + pub fn from_chain(chain: &[ChainLink]) -> Self { + let own = &chain[0]; + let mut read_prefixes = vec![]; + let mut reached_root = true; + for link in chain { + if link.storage_ref != own.storage_ref { + reached_root = false; + break; + } + if link.isolated { + read_prefixes.push(fork_area(&link.w_id)); + } + } + if reached_root || read_prefixes.is_empty() { + read_prefixes.push(String::new()); + } + Self { + write_prefix: read_prefixes[0].clone(), + read_prefixes, + own_area: fork_area(&own.w_id), + readable_areas: chain.iter().map(|l| fork_area(&l.w_id)).collect(), + } + } + + /// Whether logical keys map to themselves (only the fork-area boundary applies). + pub fn is_identity(&self) -> bool { + self.write_prefix.is_empty() && self.read_prefixes.len() == 1 + } + + /// The same mapping with reads confined to the workspace's own copy, for sizing what a + /// write replaces: an ancestor's object is not overwritten by it. + pub fn own_only(&self) -> Self { + Self { read_prefixes: vec![self.write_prefix.clone()], ..self.clone() } + } + + /// The physical key a write (put, multipart, delete, copy destination) of `key` goes to. + pub fn write_key(&self, key: &str) -> Result { + let key = reject_dot_segments(key)?; + if in_fork_area(key) { + return if key.starts_with(&self.own_area) { + Ok(key.to_string()) + } else { + Err(forbidden(key)) + }; + } + Ok(format!("{}{key}", self.write_prefix)) + } + + /// The physical keys a read of `key` tries, in order, until one exists. + pub fn read_keys(&self, key: &str) -> Result> { + let key = reject_dot_segments(key)?; + if in_fork_area(key) { + return if self.readable_areas.iter().any(|a| key.starts_with(a)) { + Ok(vec![key.to_string()]) + } else { + Err(forbidden(key)) + }; + } + Ok(self + .read_prefixes + .iter() + .map(|p| format!("{p}{key}")) + .collect()) + } + + /// A listing of `prefix` covers this workspace's own objects only: an isolating fork does + /// not list its ancestors' keys. + pub fn list(&self, prefix: &str) -> Result { + let prefix = reject_dot_segments(prefix)?; + if in_fork_area(prefix) { + if !self.readable_areas.iter().any(|a| prefix.starts_with(a)) { + return Err(forbidden(prefix)); + } + return Ok(ListMapping { + physical_prefix: prefix.to_string(), + strip: String::new(), + hide_fork_area: false, + }); + } + Ok(ListMapping { + physical_prefix: format!("{}{prefix}", self.write_prefix), + strip: self.write_prefix.clone(), + hide_fork_area: true, + }) + } +} + +lazy_static::lazy_static! { + static ref FORK_STORAGE_KEYS_CACHE: Cache<(String, String), (Arc, i64)> = + Cache::new(1000); +} + +/// Drop the cached mappings of a workspace whose isolation rows or lineage just changed. +pub fn invalidate_fork_storage_keys_cache(w_id: &str) { + FORK_STORAGE_KEYS_CACHE.retain(|(w, _), _| w != w_id); +} + +pub fn clear_fork_storage_keys_cache() { + FORK_STORAGE_KEYS_CACHE.clear(); +} + +/// `storage` as the registry keys it: '' for the default storage. +pub fn registry_storage_name(storage: Option<&str>) -> &str { + match storage { + None | Some("") | Some(windmill_types::s3::DEFAULT_STORAGE) => "", + Some(s) => s, + } +} + +/// The storage entry named `storage` (registry form) in a `large_file_storage` value. +pub fn lfs_entry<'a>(lfs: &'a serde_json::Value, storage: &str) -> Option<&'a serde_json::Value> { + if storage.is_empty() { + Some(lfs) + } else { + lfs.get("secondary_storage")?.get(storage) + } +} + +/// How `w_id`'s keys map in `storage`. Reads lineage for any `w_id` with no authorization +/// check, like [`workspace_with_fork_ancestors`]: callers must be authorized for `w_id`. +pub async fn fork_storage_keys( + db: &DB, + w_id: &str, + storage: Option<&str>, +) -> Result> { + let storage = registry_storage_name(storage).to_string(); + let cache_key = (w_id.to_string(), storage.clone()); + let now = chrono::Utc::now().timestamp(); + if let Some((keys, expiry)) = FORK_STORAGE_KEYS_CACHE.get(&cache_key) { + if expiry > now { + return Ok(keys); + } + } + + let chain_ids = workspace_with_fork_ancestors(db, w_id).await?; + let rows = sqlx::query!( + r#"SELECT c.id AS "id!", ws.large_file_storage, + EXISTS (SELECT 1 FROM fork_storage_namespace f + WHERE f.workspace_id = c.id AND f.storage = $2) AS "isolated!" + FROM unnest($1::text[]) WITH ORDINALITY AS c(id, ord) + LEFT JOIN workspace_settings ws ON ws.workspace_id = c.id + ORDER BY c.ord"#, + &chain_ids, + &storage, + ) + .fetch_all(db) + .await?; + let chain: Vec = rows + .into_iter() + .map(|r| ChainLink { + storage_ref: r + .large_file_storage + .as_ref() + .and_then(|lfs| lfs_entry(lfs, &storage)) + .and_then(lfs_entry_storage_ref), + w_id: r.id, + isolated: r.isolated, + }) + .collect(); + let keys = Arc::new(if chain.is_empty() { + ForkStorageKeys::from_chain(&[ChainLink { + w_id: w_id.to_string(), + storage_ref: None, + isolated: false, + }]) + } else { + ForkStorageKeys::from_chain(&chain) + }); + FORK_STORAGE_KEYS_CACHE.insert(cache_key, (keys.clone(), now + 30)); + Ok(keys) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn link(w_id: &str, storage_ref: &str, isolated: bool) -> ChainLink { + ChainLink { w_id: w_id.into(), storage_ref: Some(storage_ref.into()), isolated } + } + + #[test] + fn root_is_identity_but_keeps_fork_areas_out_of_reach() { + let keys = ForkStorageKeys::from_chain(&[link("prod", "S3Storage:u/a/s3", false)]); + assert!(keys.is_identity()); + assert_eq!(keys.write_key("a/b.csv").unwrap(), "a/b.csv"); + assert_eq!(keys.read_keys("a/b.csv").unwrap(), vec!["a/b.csv"]); + let other = fork_area("wm-fork-x"); + assert!(keys.write_key(&format!("{other}a")).is_err()); + assert!(keys.read_keys(&format!("{other}a")).is_err()); + let listing = keys.list("").unwrap(); + assert_eq!(listing.logical_key("a/b.csv").as_deref(), Some("a/b.csv")); + assert_eq!(listing.logical_key(&format!("{other}a")), None); + } + + #[test] + fn isolated_fork_writes_its_area_and_reads_through_to_ancestors() { + let s = "S3Storage:u/a/s3"; + let chain = [ + link("wm-fork-b", s, true), + link("wm-fork-a", s, false), + link("dev", s, true), + link("prod", s, false), + ]; + let keys = ForkStorageKeys::from_chain(&chain); + let (b, dev) = (fork_area("wm-fork-b"), fork_area("dev")); + assert_eq!(keys.write_key("x.csv").unwrap(), format!("{b}x.csv")); + assert_eq!( + keys.read_keys("x.csv").unwrap(), + vec![ + format!("{b}x.csv"), + format!("{dev}x.csv"), + "x.csv".to_string() + ] + ); + // DuckLake's own fork namespace and its ancestors' pass through as is. + assert_eq!( + keys.write_key(&format!("{b}lake/f")).unwrap(), + format!("{b}lake/f") + ); + let a = fork_area("wm-fork-a"); + assert_eq!( + keys.read_keys(&format!("{a}lake/f")).unwrap(), + vec![format!("{a}lake/f")] + ); + assert!(keys.write_key(&format!("{a}lake/f")).is_err()); + let listing = keys.list("dir/").unwrap(); + assert_eq!(listing.physical_prefix, format!("{b}dir/")); + assert_eq!( + listing.logical_key(&format!("{b}dir/f")).as_deref(), + Some("dir/f") + ); + } + + #[test] + fn shared_fork_writes_where_its_parent_does() { + let s = "S3Storage:u/a/s3"; + let keys = ForkStorageKeys::from_chain(&[ + link("wm-fork-c", s, false), + link("dev", s, true), + link("prod", s, false), + ]); + let dev = fork_area("dev"); + assert_eq!(keys.write_key("x").unwrap(), format!("{dev}x")); + assert_eq!( + keys.read_keys("x").unwrap(), + vec![format!("{dev}x"), "x".into()] + ); + } + + #[test] + fn reads_stop_at_an_ancestor_on_another_storage() { + let keys = ForkStorageKeys::from_chain(&[ + link("wm-fork-d", "S3Storage:u/a/other", true), + link("prod", "S3Storage:u/a/s3", false), + ]); + let d = fork_area("wm-fork-d"); + assert_eq!(keys.read_keys("x").unwrap(), vec![format!("{d}x")]); + } + + #[test] + fn dot_segments_cannot_climb_out_of_the_fork_area() { + let keys = ForkStorageKeys::from_chain(&[ + link("wm-fork-a", "S3Storage:u/a/s3", true), + link("prod", "S3Storage:u/a/s3", false), + ]); + let area = fork_area("wm-fork-a"); + assert!(keys.write_key("../../prod.csv").is_err()); + assert!(keys.write_key(&format!("{area}lake/../../x")).is_err()); + assert!(keys.read_keys("a/./b").is_err()); + assert!(keys.list("..").is_err()); + assert_eq!( + keys.write_key("a..b/c.d").unwrap(), + format!("{area}a..b/c.d") + ); + } + + #[test] + fn fork_area_match_is_on_whole_segments() { + assert!(in_fork_area("__wm_forks/a")); + assert!(!in_fork_area("__wm_forks_backup/a")); + let keys = ForkStorageKeys::from_chain(&[link("prod", "S3Storage:u/a/s3", false)]); + assert_eq!( + keys.write_key("__wm_forks_backup/a").unwrap(), + "__wm_forks_backup/a" + ); + } +} diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index 2bc303f5c2..07a05f5ab4 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -10,6 +10,10 @@ pub const FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX_SETTING: &str = "fork_workspace_tag_append_fork_suffix"; pub const PREVIEW_TAGS_OVERRIDE_SETTING: &str = "preview_tags_override"; pub const DEPENDENCY_JOB_TAG_SETTING: &str = "dependency_job_tag"; +pub const DEV_WORKSPACE_ISOLATION_SETTING: &str = "dev_workspace_isolation"; +pub const DEV_WORKSPACE_TAG_SUFFIX_SETTING: &str = "dev_workspace_tag_suffix"; +pub const DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING: &str = + "dev_workspace_isolation_skip_non_dev_forks"; pub const BASE_URL_SETTING: &str = "base_url"; pub const WS_BASE_URL_SETTING: &str = "ws_base_url"; pub const OAUTH_SETTING: &str = "oauths"; @@ -64,6 +68,7 @@ pub const EXTERNAL_INSTANCE_PG_SETTING: &str = "external_instance_pg"; pub const INSTANCE_PG_DISABLED_SETTING: &str = "instance_pg_disabled"; pub const EXTERNAL_INSTANCE_PG_STATE_SETTING: &str = "external_instance_pg_state"; pub const TIMEOUT_WAIT_RESULT_SETTING: &str = "timeout_wait_result"; +pub const AGENT_WORKLOAD_IDENTITY_ISSUERS_SETTING: &str = "agent_workload_identity_issuers"; pub const UNIQUE_ID_SETTING: &str = "uid"; pub const DISABLE_STATS_SETTING: &str = "disable_stats"; @@ -315,6 +320,21 @@ pub fn validate_accent_color(value: &serde_json::Value) -> Result<(), String> { Ok(()) } +/// Validate a non-empty [`DEV_WORKSPACE_TAG_SUFFIX_SETTING`] value. Every writer must call +/// it: a suffix that fails it is ignored at load, so the workers would listen on a suffix +/// the setting does not show. +pub fn validate_dev_workspace_tag_suffix(value: &serde_json::Value) -> Result<(), String> { + let s = value + .as_str() + .ok_or_else(|| "must be a string".to_string())?; + if !crate::worker::is_valid_dev_workspace_tag_suffix(s.trim()) { + return Err( + "may only contain letters, digits, '-', '_' and '.', up to 32 characters".to_string(), + ); + } + Ok(()) +} + /// The settings every signed-in browser reads on each full page load. #[derive(serde::Serialize, Clone, Debug, Default, PartialEq)] pub struct InstanceUi { @@ -620,6 +640,7 @@ pub fn parse_allowed_origins_setting( pub const ENV_SETTINGS: &[&str] = &[ "DISABLE_NSJAIL", + "DISABLE_BUN_INSTALL_SANDBOX", "MODE", "NUM_WORKERS", "METRICS_ADDR", diff --git a/backend/windmill-common/src/guest_jwt.rs b/backend/windmill-common/src/guest_jwt.rs index dc0407163d..aa308e7c9e 100644 --- a/backend/windmill-common/src/guest_jwt.rs +++ b/backend/windmill-common/src/guest_jwt.rs @@ -328,7 +328,6 @@ pub const MAX_GUEST_JWT_LEN: usize = 8 * 1024; /// self-hosted internal (http/private) issuer that works for `jwt_ext_` works for guests too. /// The body is read with a cap so a hostile endpoint cannot exhaust memory. pub async fn fetch_jwks(url: &str) -> Result> { - use futures::StreamExt; if url.len() > MAX_JWKS_URL_LEN { return Err(Error::BadRequest(format!( "JWKS URL is longer than {MAX_JWKS_URL_LEN} bytes" @@ -356,6 +355,13 @@ pub async fn fetch_jwks(url: &str) -> Result> { } .and_then(|r| r.error_for_status()) .map_err(|e| Error::BadRequest(format!("could not fetch JWKS: {e}")))?; + parse_jwks_keys(&read_capped_body(resp).await?) +} + +/// A JWKS (or OIDC discovery) response body, refused past `JWKS_MAX_BYTES` rather than +/// buffered: the server behind a configured URL may be hostile. +pub(crate) async fn read_capped_body(resp: reqwest::Response) -> Result> { + use futures::StreamExt; let mut stream = resp.bytes_stream(); let mut body: Vec = Vec::new(); while let Some(chunk) = stream.next().await { @@ -367,7 +373,7 @@ pub async fn fetch_jwks(url: &str) -> Result> { } body.extend_from_slice(&chunk); } - parse_jwks_keys(&body) + Ok(body) } /// The usable signing keys in a JWKS body, by `kid`. Each key is parsed on its own and @@ -378,7 +384,7 @@ pub async fn fetch_jwks(url: &str) -> Result> { /// A key is kept only if its material actually decodes (`DecodingKey::from_jwk`): jsonwebtoken /// carries `n`/`e`/`x`/`y` as strings and defers decoding to auth time, so without this a JWKS /// whose only key is malformed would be accepted at save time and fail every token later. -fn parse_jwks_keys(body: &[u8]) -> Result> { +pub(crate) fn parse_jwks_keys(body: &[u8]) -> Result> { let set: serde_json::Value = serde_json::from_slice(body) .map_err(|e| Error::BadRequest(format!("JWKS is not JSON: {e}")))?; let entries = set @@ -422,13 +428,75 @@ fn parse_jwks_keys(body: &[u8]) -> Result> { fn servable(entry: Arc) -> Result> { if entry.keys.is_empty() { Err(Error::NotAuthorized( - "guest JWT refused: the JWKS issuer is unreachable".to_string(), + "the JWKS issuer is unreachable".to_string(), )) } else { Ok(entry) } } +/// Where a cached JWKS comes from. Both kinds share the cache, its single-flight refresh and +/// its staleness bounds; they differ only in how a fetch reaches the issuer. +#[derive(Clone)] +pub enum JwksSource { + /// A workspace guest key URL: SSRF-restricted unless it is the instance issuer + /// (`fetch_jwks`). + GuestUrl(String), + /// An issuer a superadmin trusts for agent workload identity. Trusted like + /// `JWT_EXT_JWKS_URL`, so fetched with the permissive client: an in-cluster or + /// self-signed issuer has to work. Without `jwks_uri`, OIDC discovery finds it. + TrustedIssuer { issuer: String, jwks_uri: Option }, +} + +impl JwksSource { + fn cache_key(&self) -> String { + match self { + JwksSource::GuestUrl(url) => url.clone(), + JwksSource::TrustedIssuer { issuer, jwks_uri } => { + format!("issuer:{issuer}\n{}", jwks_uri.as_deref().unwrap_or("")) + } + } + } + + async fn fetch(&self) -> Result> { + match self { + JwksSource::GuestUrl(url) => fetch_jwks(url).await, + JwksSource::TrustedIssuer { issuer, jwks_uri } => { + let jwks_uri = match jwks_uri.as_deref().filter(|u| !u.trim().is_empty()) { + Some(uri) => uri.to_string(), + None => { + let discovery = format!( + "{}/.well-known/openid-configuration", + issuer.trim_end_matches('/') + ); + let doc: serde_json::Value = + serde_json::from_slice(&get_trusted(&discovery).await?).map_err( + |e| Error::BadRequest(format!("OIDC discovery is not JSON: {e}")), + )?; + doc.get("jwks_uri") + .and_then(|u| u.as_str()) + .ok_or_else(|| { + Error::BadRequest("OIDC discovery has no jwks_uri".to_string()) + })? + .to_string() + } + }; + parse_jwks_keys(&get_trusted(&jwks_uri).await?) + } + } + } +} + +async fn get_trusted(url: &str) -> Result> { + let resp = crate::utils::HTTP_CLIENT_PERMISSIVE + .get(url) + .send() + .await + .and_then(|r| r.error_for_status()) + .map_err(|e| Error::BadRequest(format!("fetching {url}: {e}")))?; + read_capped_body(resp).await +} + /// A held single-flight lock for one JWKS URL. Dropping it removes the URL from /// `JWKS_FETCH_LOCKS` once no other holder remains, so the registry never keeps a lock past /// its fetch and stays bounded by the number of fetches in flight, not by URLs ever seen. @@ -468,13 +536,14 @@ impl Drop for JwksFetchLock { /// Refresh a URL's JWKS off the request path, under the single-flight lock. A held /// lock means a refresh is already running, so this is a no-op. A failed refresh /// leaves the served stale keys in place rather than dropping them. -fn spawn_jwks_refresh(url: String) { +fn spawn_jwks_refresh(source: JwksSource) { tokio::spawn(async move { + let url = source.cache_key(); let fetch_lock = JwksFetchLock::acquire(&url); let Ok(_guard) = fetch_lock.lock.try_lock() else { return; }; - match fetch_jwks(&url).await { + match source.fetch().await { Ok(keys) => { let now = Instant::now(); JWKS_CACHE.insert( @@ -486,7 +555,7 @@ fn spawn_jwks_refresh(url: String) { }), ); } - Err(e) => tracing::warn!("guest JWKS background refresh failed for {url}: {e:#}"), + Err(e) => tracing::warn!("JWKS background refresh failed for {url}: {e:#}"), } }); } @@ -498,7 +567,9 @@ fn spawn_jwks_refresh(url: String) { /// entry that reads as "issuer unreachable", so an unreachable issuer is hit at most /// once per `JWKS_NEGATIVE_TTL`. Fetches follow a schedule, never a per-request, /// attacker-chosen `kid`. -async fn cached_jwks(url: &str) -> Result> { +async fn cached_jwks(source: &JwksSource) -> Result> { + let key = source.cache_key(); + let url = key.as_str(); if let Some(entry) = JWKS_CACHE.get(url) { // Keys past JWKS_MAX_STALE are never served, even while revalidating: a stale re-serve // bumps expires_at but keeps fetched_at, so a persistently failing refresh would @@ -519,7 +590,7 @@ async fn cached_jwks(url: &str) -> Result> { fetched_at: entry.fetched_at, }); JWKS_CACHE.insert(url.to_string(), served.clone()); - spawn_jwks_refresh(url.to_string()); + spawn_jwks_refresh(source.clone()); return Ok(served); } } @@ -535,7 +606,7 @@ async fn cached_jwks(url: &str) -> Result> { return servable(entry); } } - match fetch_jwks(url).await { + match source.fetch().await { Ok(keys) => { let now = Instant::now(); let entry = Arc::new(JwksEntry { @@ -573,7 +644,12 @@ pub async fn jwks_key_for(url: &str, token: &str) -> Result<(DecodingKey, Vec Error::NotAuthorized(format!("guest JWT refused: {m}")), + e => e, + })?; let jwk = entry.keys.get(&kid).ok_or_else(|| { Error::NotAuthorized(format!("guest JWT refused: kid {kid} is not in the JWKS")) })?; @@ -585,6 +661,12 @@ pub async fn jwks_key_for(url: &str, token: &str) -> Result<(DecodingKey, Vec Result>> { + Ok(cached_jwks(source).await?.keys.clone()) +} + /// Verify `token` for `w_id` against whatever key the workspace configured. A PEM key /// ignores `kid`; a JWKS selects by it. pub async fn verify_for_workspace(db: &DB, w_id: &str, token: &str) -> Result { @@ -950,7 +1032,9 @@ y9rTR828ADcaZ63Ej1oL4GcqmGhODxCLy1YKKcy0FHzChqPMV6g=\n\ for _ in 0..10 { let u = url.clone(); handles.push(tokio::spawn(async move { - cached_jwks(&u).await.map(|e| e.keys.len()) + cached_jwks(&JwksSource::GuestUrl(u)) + .await + .map(|e| e.keys.len()) })); } for h in handles { @@ -1013,7 +1097,7 @@ y9rTR828ADcaZ63Ej1oL4GcqmGhODxCLy1YKKcy0FHzChqPMV6g=\n\ }), ); assert!( - cached_jwks(&within).await.is_ok(), + cached_jwks(&JwksSource::GuestUrl(within)).await.is_ok(), "stale keys within the grace window are still served" ); @@ -1030,7 +1114,7 @@ y9rTR828ADcaZ63Ej1oL4GcqmGhODxCLy1YKKcy0FHzChqPMV6g=\n\ }), ); assert!( - cached_jwks(&beyond).await.is_err(), + cached_jwks(&JwksSource::GuestUrl(beyond)).await.is_err(), "keys past the grace window fail closed once the refresh fails" ); unsafe { std::env::remove_var("ALLOW_PRIVATE_GUEST_JWKS_URLS") }; diff --git a/backend/windmill-common/src/instance_config.rs b/backend/windmill-common/src/instance_config.rs index d19de41dcc..2b476b338a 100644 --- a/backend/windmill-common/src/instance_config.rs +++ b/backend/windmill-common/src/instance_config.rs @@ -263,6 +263,10 @@ pub struct GlobalSettings { #[serde(skip_serializing_if = "Option::is_none")] pub default_tags_per_workspace: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub dev_workspace_isolation: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub dev_workspace_isolation_skip_non_dev_forks: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub preview_tags_override: Option, #[serde(skip_serializing_if = "Option::is_none")] pub disable_hub: Option, @@ -279,6 +283,8 @@ pub struct GlobalSettings { #[serde(skip_serializing_if = "Option::is_none")] pub dependency_job_tag: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub dev_workspace_tag_suffix: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub ws_base_url: Option, #[serde(skip_serializing_if = "Option::is_none")] pub github_app_webhook_base_url: Option, @@ -362,6 +368,8 @@ pub struct GlobalSettings { pub custom_instance_pg_databases: Option, #[serde(skip_serializing_if = "Option::is_none")] pub external_instance_pg: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub agent_workload_identity_issuers: Option>, // Opaque settings (EE-private structs or no clear schema) #[serde(skip_serializing_if = "Option::is_none")] @@ -732,6 +740,42 @@ pub struct TeamsChannel { pub channel_name: String, } +// --------------------------------------------------------------------------- +// Agent worker workload identity +// --------------------------------------------------------------------------- + +/// An issuer whose workload identity tokens (Kubernetes projected service account tokens, +/// SPIFFE JWT-SVIDs, ...) an agent worker may authenticate with instead of an agent token. +#[derive(Deserialize, Serialize, Clone, Debug, Default, PartialEq)] +#[cfg_attr(feature = "instance_config_schema", derive(schemars::JsonSchema))] +pub struct AgentWorkloadIdentityIssuer { + /// Must equal the token's `iss` exactly. + pub issuer: String, + /// Where the signing keys are published. Defaults to the `jwks_uri` of the issuer's OIDC + /// discovery document. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub jwks_uri: Option, + /// The JWKS document itself, as JSON text, for an issuer this instance cannot reach. + /// Takes precedence over `jwks_uri`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub jwks: Option, + /// Must be one of the token's `aud`. + pub audience: String, + /// Tried in order; the first whose claims all match decides the worker group and tags. + #[serde(default)] + pub rules: Vec, +} + +#[derive(Deserialize, Serialize, Clone, Debug, Default, PartialEq)] +#[cfg_attr(feature = "instance_config_schema", derive(schemars::JsonSchema))] +pub struct AgentWorkloadIdentityRule { + /// Claim path (dot separated, a key that itself contains dots such as `kubernetes.io` + /// is matched whole) to the exact value it must hold. + pub claims: BTreeMap, + pub worker_group: String, + pub tags: Vec, +} + // --------------------------------------------------------------------------- // DB oversize alert // --------------------------------------------------------------------------- @@ -970,6 +1014,9 @@ pub struct WorkerGroupConfig { /// Workers of the group pull no new job while this is set; queued jobs wait. #[serde(skip_serializing_if = "Option::is_none")] pub paused: Option, + /// The group listens to its tags suffixed with the dev workspace tag suffix, and only to them. + #[serde(skip_serializing_if = "Option::is_none")] + pub serves_dev_workspaces: Option, /// Object store this group's dependency cache uses instead of the instance one. Same shape /// as the instance `object_store_cache_config`. #[serde(skip_serializing_if = "Option::is_none")] @@ -1499,6 +1546,21 @@ pub async fn sync_global_settings_declarative( .map_err(|e| anyhow::anyhow!("{accent_key}: {e}"))?, } + let issuers_key = crate::global_settings::AGENT_WORKLOAD_IDENTITY_ISSUERS_SETTING; + match desired.get(issuers_key) { + None | Some(serde_json::Value::Null) => {} + Some(issuers) => crate::agent_workload_identity::validate_issuers_value(issuers) + .map_err(|e| anyhow::anyhow!("{issuers_key}: {e}"))?, + } + + let suffix_key = crate::global_settings::DEV_WORKSPACE_TAG_SUFFIX_SETTING; + match desired.get(suffix_key) { + None | Some(serde_json::Value::Null) => {} + Some(serde_json::Value::String(s)) if s.trim().is_empty() => {} + Some(suffix) => crate::global_settings::validate_dev_workspace_tag_suffix(suffix) + .map_err(|e| anyhow::anyhow!("{suffix_key}: {e}"))?, + } + // An origin list that cannot be parsed is dropped at boot, leaving the // empty default — which is no restriction at all. Rejecting it here is what // keeps a typo in a ConfigMap from silently widening CORS instance-wide. diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 58a477d7b9..9f1ccf7211 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -27,6 +27,7 @@ use scripts::ScriptLang; use sqlx::{Acquire, Postgres}; pub mod agent_workers; +pub mod agent_workload_identity; pub mod apps; pub mod assets; pub mod audit; @@ -73,6 +74,7 @@ pub use feature_usage_oss as feature_usage; pub mod flow_conversations; pub mod flow_status; pub mod flows; +pub mod fork_storage; pub mod folders; pub mod global_settings; pub mod hub_resource_types; @@ -170,6 +172,9 @@ pub const DEFAULT_SERVICE_LOG_RETENTION_SECS: i64 = 60 * 60 * 24 * 14; // 2 week pub const DEFAULT_OTEL_TRACES_RETENTION_SECS: i64 = 60 * 60 * 24 * 7; // 1 week retention period for HTTP request spans pub const DEFAULT_AI_SHARED_ARTIFACT_RETENTION_SECS: i64 = 60 * 60 * 24 * 30; pub const WM_DEPLOYERS_GROUP: &str = "wm_deployers"; +/// Groups Windmill creates lazily (`ON CONFLICT DO NOTHING`) and grants permissions to before +/// they exist; a member who created one first would inherit those grants. +pub const RESERVED_GROUP_NAMES: &[&str] = &["error_handler", "success_handler", "slack", "teams"]; /// A century. Every consumer has to survive `now - retention`, and the ceilings are much lower /// than an `i64`: `DateTime` subtraction panics past year 262143, and the `( s)::interval` diff --git a/backend/windmill-common/src/oauth2.rs b/backend/windmill-common/src/oauth2.rs index faa1f1b942..04a8a6f227 100644 --- a/backend/windmill-common/src/oauth2.rs +++ b/backend/windmill-common/src/oauth2.rs @@ -21,6 +21,15 @@ pub const GLOBAL_SLACK_BOT_TOKEN_PATH: &str = "f/slack_bot/global_bot_token"; pub const GLOBAL_TEAMS_BOT_TOKEN_PATH: &str = "f/teams_bot/global_bot_token"; pub const GLOBAL_TEAMS_API_TOKEN_PATH: &str = "f/teams_bot/global_api_token"; + +/// Key under the `oauths` setting holding the Teams Entra app (id, secret, tenant). One app +/// serves the Enterprise bot and Graph connect for the `ms_teams` resource type. +pub const TEAMS_OAUTH_KEY: &str = "ms_teams"; + +/// Pre-rename key for the same entry. The 20261016120000 migration copies it to `ms_teams` +/// and keeps it so servers still on the old version work during a rolling upgrade. +/// TODO: drop this fallback once every supported version reads `ms_teams`. +pub const LEGACY_TEAMS_OAUTH_KEY: &str = "teams"; lazy_static::lazy_static! { pub static ref REQUIRE_PREEXISTING_USER_FOR_OAUTH: AtomicBool = AtomicBool::new(std::env::var("REQUIRE_PREEXISTING_USER_FOR_OAUTH") diff --git a/backend/windmill-common/src/ssrf.rs b/backend/windmill-common/src/ssrf.rs index 583b1e81ab..c95137a8bb 100644 --- a/backend/windmill-common/src/ssrf.rs +++ b/backend/windmill-common/src/ssrf.rs @@ -197,12 +197,6 @@ pub async fn validate_url_for_ssrf(url: &str) -> Result bool { - std::env::var(ALLOW_PRIVATE_MCP_SERVER_URLS_ENV) - .ok() - .is_some_and(|v| v == "true" || v == "1") -} - pub fn allow_private_saml_metadata_urls() -> bool { std::env::var(ALLOW_PRIVATE_SAML_METADATA_URLS_ENV) .ok() @@ -311,22 +305,22 @@ pub async fn validate_guest_jwks_url(url: &str) -> Result Result { - let parsed = - url::Url::parse(url).map_err(|e| SsrfValidationError::InvalidUrl(e.to_string()))?; - - match parsed.scheme() { - "http" | "https" => {} - scheme => return Err(SsrfValidationError::DisallowedScheme(scheme.to_string())), + // Read per call rather than cached, so warn about bad entries once, not on every connect. + static WARN_INVALID: std::sync::Once = std::sync::Once::new(); + let value = std::env::var(ALLOW_PRIVATE_MCP_SERVER_URLS_ENV).unwrap_or_default(); + let (allowance, invalid) = PrivateHostAllowance::parse(&value); + if !invalid.is_empty() { + WARN_INVALID.call_once(|| { + tracing::warn!( + "Ignoring {ALLOW_PRIVATE_MCP_SERVER_URLS_ENV} entries {invalid:?}: expected a \ + host, host:port, IP address or CIDR range" + ) + }); } - - let host = parsed.host_str().ok_or(SsrfValidationError::MissingHost)?; - - if allow_private_mcp_server_urls() { - return Ok(ValidatedTarget::unpinned(host)); - } - - validate_url_for_ssrf(url).await + validate_url_for_ssrf_allowing(url, &allowance).await } /// Save-time check only: the webhook is sent later from another task that resolves @@ -369,8 +363,9 @@ pub async fn validate_mcp_server_url_for_bad_request( pub fn mcp_ssrf_error_message(e: &SsrfValidationError) -> String { match e { SsrfValidationError::Private { .. } => format!( - "{e}. If you need to use private/internal MCP server URLs, \ - set the {ALLOW_PRIVATE_MCP_SERVER_URLS_ENV}=true environment variable" + "{e}. To use a private/internal MCP server, add its host (host, host:port or \ + CIDR range) to the comma-separated {ALLOW_PRIVATE_MCP_SERVER_URLS_ENV} environment \ + variable, or set it to true to allow every private host" ), _ => e.to_string(), } @@ -396,6 +391,188 @@ pub fn webhook_ssrf_error_message(e: &SsrfValidationError) -> String { } } +/// Which private hosts an `ALLOW_PRIVATE_*` opt-in lets a URL reach. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub enum PrivateHostAllowance { + /// Private hosts are refused. + #[default] + None, + /// Every private host is allowed; only the URL's scheme and host are checked (`true` / `1`). + All, + /// Only the private hosts these entries name are allowed. + Hosts(Vec), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AllowedPrivateHost { + /// A host name, trusted whatever it resolves to. + Name { name: String, port: Option }, + /// An address or network a URL's host may resolve into. + Net { net: ipnet::IpNet, port: Option }, +} + +impl AllowedPrivateHost { + fn parse(entry: &str) -> Option { + if let Ok(net) = entry.parse::() { + return Some(Self::Net { net: net.trunc(), port: None }); + } + let unbracketed = entry + .strip_prefix('[') + .and_then(|e| e.strip_suffix(']')) + .unwrap_or(entry); + if let Ok(ip) = unbracketed.parse::() { + return Some(Self::Net { net: ip.into(), port: None }); + } + if let Ok(addr) = entry.parse::() { + return Some(Self::Net { net: addr.ip().into(), port: Some(addr.port()) }); + } + let (host, port) = match entry.rsplit_once(':') { + Some((host, port)) => (host, Some(port.parse::().ok()?)), + None => (entry, None), + }; + // Normalized the way `url::Url` normalizes the host it is compared against. An address + // reaching here is a loose WHATWG form (`10` is 0.0.0.10, not 10/8) and a `*` is not a + // wildcard, so both are refused rather than read as something the operator never meant. + match url::Host::parse(host.trim_end_matches('.')).ok()? { + url::Host::Domain(name) if !name.is_empty() && !name.contains('*') => { + Some(Self::Name { name, port }) + } + _ => None, + } + } +} + +fn port_allowed(allowed: Option, port: u16) -> bool { + allowed.map_or(true, |p| p == port) +} + +impl PrivateHostAllowance { + /// `true`/`1` allows every private host; anything else is a comma-separated list of + /// `host`, `host:port`, IP address, `ip:port` (`[v6]:port`) or CIDR entries. Also returns + /// the entries that parse as none of these, which allow nothing. + pub fn parse(value: &str) -> (Self, Vec) { + match value.trim() { + "true" | "1" => return (Self::All, vec![]), + "" | "false" | "0" => return (Self::None, vec![]), + _ => {} + } + let mut hosts = vec![]; + let mut invalid = vec![]; + for entry in value.split(',').map(str::trim).filter(|e| !e.is_empty()) { + match AllowedPrivateHost::parse(entry) { + Some(host) => hosts.push(host), + None => invalid.push(entry.to_string()), + } + } + let allowance = if hosts.is_empty() { + Self::None + } else { + Self::Hosts(hosts) + }; + (allowance, invalid) + } + + pub fn from_env(var: &str) -> Self { + let Ok(value) = std::env::var(var) else { + return Self::None; + }; + let (allowance, invalid) = Self::parse(&value); + for entry in invalid { + tracing::warn!( + "Ignoring {var} entry {entry:?}: expected a host, host:port, IP address or CIDR range" + ); + } + allowance + } + + fn allows_name(&self, name: &str, port: u16) -> bool { + let name = name.trim_end_matches('.'); + matches!(self, Self::Hosts(hosts) if hosts.iter().any(|h| matches!(h, + AllowedPrivateHost::Name { name: n, port: p } if n == name && port_allowed(*p, port)))) + } + + fn allows_ip(&self, ip: &IpAddr, port: u16) -> bool { + // Judged by where it is delivered: an allowed v6 range such as an operator's NAT64 + // prefix must not carry a request on to an embedded private v4 like 169.254.169.254. + let ip = &match ip { + // The local-use NAT64 prefix places its v4 by a prefix length only the site knows, + // so the destination cannot be judged and no network entry admits it. + IpAddr::V6(v6) if v6.segments()[..3] == [0x0064, 0xff9b, 0x0001] => return false, + // `::1` and `::` sit inside the IPv4-compatible block but are v6's own. + IpAddr::V6(v6) if !v6.is_loopback() && !v6.is_unspecified() => { + embedded_ipv4(v6).map_or(*ip, IpAddr::V4) + } + IpAddr::V6(_) => *ip, + IpAddr::V4(_) => *ip, + }; + matches!(self, Self::Hosts(hosts) if hosts.iter().any(|h| matches!(h, + AllowedPrivateHost::Net { net, port: p } if net.contains(ip) && port_allowed(*p, port)))) + } +} + +/// [`validate_url_for_ssrf`], except that the URL may also reach the private hosts +/// `allowance` names. +/// +/// A host matched by name is trusted whatever it resolves to, so it is left unpinned. Any +/// other host must resolve only to public addresses or ones inside an allowed network, and +/// those addresses are pinned as usual. +pub async fn validate_url_for_ssrf_allowing( + url: &str, + allowance: &PrivateHostAllowance, +) -> Result { + if *allowance == PrivateHostAllowance::None { + return validate_url_for_ssrf(url).await; + } + + let parsed = + url::Url::parse(url).map_err(|e| SsrfValidationError::InvalidUrl(e.to_string()))?; + let port = match parsed.scheme() { + "http" | "https" => parsed.port_or_known_default().unwrap_or(80), + scheme => return Err(SsrfValidationError::DisallowedScheme(scheme.to_string())), + }; + let host_str = parsed.host_str().ok_or(SsrfValidationError::MissingHost)?; + + if *allowance == PrivateHostAllowance::All { + return Ok(ValidatedTarget::unpinned(host_str)); + } + + let ip = match parsed.host().ok_or(SsrfValidationError::MissingHost)? { + url::Host::Domain(name) => { + if allowance.allows_name(name, port) { + return Ok(ValidatedTarget::unpinned(host_str)); + } + None + } + url::Host::Ipv4(ip) => Some(IpAddr::V4(ip)), + url::Host::Ipv6(ip) => Some(IpAddr::V6(ip)), + }; + + if let Some(ip) = ip { + if is_private_ip(&ip) && !allowance.allows_ip(&ip, port) { + return Err(SsrfValidationError::Private { resolved: false }); + } + return Ok(ValidatedTarget::unpinned(host_str)); + } + + let addrs: Vec = tokio::net::lookup_host(format!("{host_str}:{port}")) + .await + .map_err(|e| SsrfValidationError::ResolutionFailed { + host: host_str.to_string(), + source: e.to_string(), + })? + .collect(); + if addrs.is_empty() { + return Err(SsrfValidationError::NoAddresses(host_str.to_string())); + } + for addr in &addrs { + if is_private_ip(&addr.ip()) && !allowance.allows_ip(&addr.ip(), port) { + return Err(SsrfValidationError::Private { resolved: true }); + } + } + + Ok(ValidatedTarget { host: host_str.to_string(), addrs }) +} + /// Whether `ip` is loopback, private, link-local, or otherwise not a public /// internet destination. The one predicate every server-side outbound-URL guard /// (SSRF checks, git remotes, object storage tests) judges addresses with. @@ -688,6 +865,25 @@ mod tests { assert!(validate_mcp_server_url("http://10.0.0.1/foo").await.is_ok()); } + #[tokio::test] + async fn validate_mcp_server_url_allows_only_listed_private_hosts() { + let _lock = TEST_ENV_LOCK.lock().await; + let _guard = PrivateMcpServerUrlsEnvGuard::set(Some("10.1.0.0/16, mcp.internal:8080")); + + assert!(validate_mcp_server_url("http://10.1.2.3/mcp").await.is_ok()); + assert!(validate_mcp_server_url("http://mcp.internal:8080/mcp") + .await + .is_ok()); + assert!(matches!( + validate_mcp_server_url("http://10.2.0.1/mcp").await, + Err(SsrfValidationError::Private { resolved: false }) + )); + assert!(matches!( + validate_mcp_server_url("http://169.254.169.254/").await, + Err(SsrfValidationError::Private { resolved: false }) + )); + } + #[tokio::test] async fn validate_mcp_server_url_keeps_syntax_guards_when_private_urls_are_allowed() { let _lock = TEST_ENV_LOCK.lock().await; @@ -711,9 +907,7 @@ mod tests { let private_error = validate_mcp_server_url("http://127.0.0.1/foo") .await .unwrap_err(); - assert!( - mcp_ssrf_error_message(&private_error).contains("ALLOW_PRIVATE_MCP_SERVER_URLS=true") - ); + assert!(mcp_ssrf_error_message(&private_error).contains(ALLOW_PRIVATE_MCP_SERVER_URLS_ENV)); let invalid_error = validate_mcp_server_url("localhost:11434/v1") .await @@ -877,4 +1071,66 @@ mod tests { !saml_ssrf_error_message(&invalid_error).contains(ALLOW_PRIVATE_SAML_METADATA_URLS_ENV) ); } + + #[test] + fn private_host_allowance_parses_flags_and_entries() { + assert_eq!( + PrivateHostAllowance::parse("true").0, + PrivateHostAllowance::All + ); + assert_eq!( + PrivateHostAllowance::parse("false").0, + PrivateHostAllowance::None + ); + let (parsed, invalid) = + PrivateHostAllowance::parse("Gateway.Internal., 10.1.0.0/16, x:y, 10, *.internal"); + // A bare `10` would otherwise be 0.0.0.10, and `*` is no wildcard. + assert_eq!(invalid, ["x:y", "10", "*.internal"]); + let PrivateHostAllowance::Hosts(hosts) = parsed else { + panic!("{parsed:?}") + }; + assert_eq!( + hosts[0], + AllowedPrivateHost::Name { name: "gateway.internal".into(), port: None } + ); + } + + #[tokio::test] + async fn private_host_allowance_admits_only_listed_hosts() { + let a = PrivateHostAllowance::parse( + "localhost:8080, 10.1.0.0/16, 127.0.0.2:9000, [::1]:443, 64:ff9b::/96, 64:ff9b:1::/48", + ) + .0; + let ok = |u: &'static str| { + let a = a.clone(); + async move { validate_url_for_ssrf_allowing(u, &a).await.is_ok() } + }; + // Trusted by name on its port only, so nothing to pin. + let target = validate_url_for_ssrf_allowing("http://localhost:8080/v1", &a) + .await + .unwrap(); + assert!(target.pinned_addrs().is_empty()); + assert!(!ok("http://localhost:8081/v1").await); + assert!(ok("http://10.1.2.3/v1").await); + assert!(ok("http://[::ffff:10.1.2.3]/v1").await); + assert!(!ok("http://10.2.0.1/v1").await); + assert!(ok("http://127.0.0.2:9000/v1").await); + assert!(!ok("http://127.0.0.2/v1").await); + assert!(ok("https://[::1]/v1").await); + assert!(!ok("http://[::1]/v1").await); + // An allowed v6 range does not reach the private v4 it embeds. + assert!(!ok("http://[64:ff9b::a9fe:a9fe]/").await); + assert!(!ok("http://[64:ff9b:1::a9fe:a9fe]/").await); + assert!(!ok("http://169.254.169.254/latest/meta-data").await); + assert!(ok("http://8.8.8.8/v1").await); + } + + #[tokio::test] + async fn private_host_allowance_pins_hosts_resolved_into_allowed_nets() { + let a = PrivateHostAllowance::parse("127.0.0.0/8, ::1").0; + let target = validate_url_for_ssrf_allowing("http://localhost:1234/", &a) + .await + .unwrap(); + assert!(!target.pinned_addrs().is_empty()); + } } diff --git a/backend/windmill-common/src/utils.rs b/backend/windmill-common/src/utils.rs index 116a15303e..c034edc203 100644 --- a/backend/windmill-common/src/utils.rs +++ b/backend/windmill-common/src/utils.rs @@ -124,8 +124,10 @@ lazy_static::lazy_static! { if std::env::var("BASE_INTERNAL_URL").is_err() { panic!("BASE_INTERNAL_URL is required in agent mode") } - if std::env::var("AGENT_TOKEN").is_err() { - println!("AGENT_TOKEN is not passed. This is required for the agent to work and contains the JWT to authenticate with the server.") + if std::env::var("AGENT_TOKEN").is_err() + && std::env::var(crate::agent_workers::AGENT_IDENTITY_TOKEN_FILE_ENV).is_err() + { + println!("Neither AGENT_TOKEN nor AGENT_IDENTITY_TOKEN_FILE is passed. One is required for the agent to authenticate with the server.") } #[cfg(not(feature = "enterprise"))] diff --git a/backend/windmill-common/src/worker.rs b/backend/windmill-common/src/worker.rs index f5743782e3..41d437c30a 100644 --- a/backend/windmill-common/src/worker.rs +++ b/backend/windmill-common/src/worker.rs @@ -451,6 +451,15 @@ lazy_static::lazy_static! { pub static ref FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX: AtomicBool = AtomicBool::new(false); pub static ref PREVIEW_TAGS_OVERRIDE: AtomicBool = AtomicBool::new(false); pub static ref DEPENDENCY_JOB_TAG: arc_swap::ArcSwap> = arc_swap::ArcSwap::from_pointee(None); + /// Whether the jobs of dev workspaces and forks are queued on suffixed tags. + pub static ref DEV_WORKSPACE_ISOLATION: AtomicBool = AtomicBool::new(false); + /// Whether a fork whose lineage holds no dev workspace runs on its parent's workers. + pub static ref DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS: AtomicBool = AtomicBool::new(false); + /// The suffix of those tags. Groups serving dev workspaces listen with it whether isolation is + /// on or not, so turning it off leaves no job already queued on a suffixed tag unserved. + pub static ref DEV_WORKSPACE_TAG_SUFFIX: arc_swap::ArcSwap = arc_swap::ArcSwap::from_pointee(DEFAULT_DEV_WORKSPACE_TAG_SUFFIX.to_string()); + /// Whether this process's worker group serves dev workspaces, set when its config is loaded. + pub static ref WORKER_SERVES_DEV_WORKSPACES: AtomicBool = AtomicBool::new(false); pub static ref MAX_TIMEOUT: u64 = std::env::var("TIMEOUT") .ok() @@ -1190,6 +1199,7 @@ pub struct RlangAnnotations { pub renv_verbose: bool, pub renv_install_verbose: bool, pub sandbox: bool, + pub no_network: bool, } #[annotations("#")] @@ -1205,6 +1215,7 @@ pub struct PythonAnnotations { pub py314: bool, pub py315: bool, pub sandbox: bool, + pub no_network: bool, } #[annotations("//")] @@ -1315,6 +1326,7 @@ impl SqlAnnotations { pub struct BashAnnotations { pub docker: bool, pub sandbox: bool, + pub no_network: bool, } impl BashAnnotations { @@ -2418,9 +2430,56 @@ pub async fn update_worker_ping_main_loop_query( // occupancy_rate = $3, memory_usage = $4, wm_memory_usage = $5, vcpus = COALESCE($7, vcpus), // memory = COALESCE($8, memory), occupancy_rate_15s = $9, occupancy_rate_5m = $10, occupancy_rate_30m = $11 WHERE worker = $6", -const MAX_TAG_LEN: usize = 50; +/// The length of `v2_job.tag`. +pub const MAX_TAG_LEN: usize = 50; const HASH_SUFFIX_LEN: usize = 16; +pub const DEFAULT_DEV_WORKSPACE_TAG_SUFFIX: &str = "-dev"; + +/// The suffix new jobs of dev workspaces and forks get, `None` while isolation is off. +pub fn dev_workspace_tag_suffix() -> Option { + DEV_WORKSPACE_ISOLATION + .load(std::sync::atomic::Ordering::Relaxed) + .then(|| DEV_WORKSPACE_TAG_SUFFIX.load().to_string()) +} + +/// Whether a workspace's jobs are isolated, given that it has a parent or a generated fork id +/// (`is_dev_or_fork`) and whether a dev workspace is on its ancestor chain, itself included +/// (`in_dev_lineage`). Leaves out only the forks of a non-dev workspace, and only when the +/// instance opts out of isolating them. +pub fn is_isolated_workspace(is_dev_or_fork: bool, in_dev_lineage: bool) -> bool { + is_dev_or_fork + && (in_dev_lineage + || !DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS + .load(std::sync::atomic::Ordering::Relaxed)) +} + +/// Worker tags are pasted into the pull queries as SQL literals and listed comma-separated, so +/// the suffix must not carry a quote, a comma or whitespace. +pub fn is_valid_dev_workspace_tag_suffix(suffix: &str) -> bool { + !suffix.is_empty() + && suffix.len() <= 32 + && suffix + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) +} + +/// `tag` as the workers serving dev workspaces listen to it. Idempotent, because a tag inherited +/// from a dev job (a flow step, an agent's tool) already carries the suffix. +pub fn with_dev_workspace_suffix(tag: &str, suffix: &str) -> String { + if tag.ends_with(suffix) { + tag.to_string() + } else { + format!("{tag}{suffix}") + } +} + +/// Whether `tag` has the shape of a [`dedicated_worker_tag`] too long to keep whole. Its prefix +/// alone does not tell whose it is: two workspaces may share it. +pub fn is_hashed_dedicated_worker_tag(tag: &str) -> bool { + tag.len() == MAX_TAG_LEN && tag.as_bytes().get(MAX_TAG_LEN - 1 - HASH_SUFFIX_LEN) == Some(&b'#') +} + pub fn dedicated_worker_tag(workspace_id: &str, path: &str) -> String { let full_tag = format!("{}:{}", workspace_id, path); if full_tag.len() <= MAX_TAG_LEN { @@ -2581,8 +2640,32 @@ pub async fn load_worker_config( }) .unwrap_or_else(|| DEFAULT_TAGS.clone()); + // A group serving dev workspaces listens to the suffixed form of its tags only, so it never + // takes a root workspace's job. Dedicated workers are placed by hand and keep their tags. + let dev_suffix = (config.serves_dev_workspaces == Some(true) + && dedicated_worker.is_none() + && dedicated_workers.is_none()) + .then(|| DEV_WORKSPACE_TAG_SUFFIX.load().to_string()); + WORKER_SERVES_DEV_WORKSPACES.store(dev_suffix.is_some(), std::sync::atomic::Ordering::Relaxed); + let worker_tags = match &dev_suffix { + Some(suffix) => worker_tags + .iter() + .map(|t| with_dev_workspace_suffix(t, suffix)) + .unique() + .collect_vec(), + None => worker_tags, + }; + let mut priority_tags_sorted: Vec = Vec::new(); - let priority_tags_map = config.priority_tags.unwrap_or_else(HashMap::new); + let priority_tags_map: HashMap = match &dev_suffix { + Some(suffix) => config + .priority_tags + .unwrap_or_default() + .into_iter() + .map(|(t, p)| (with_dev_workspace_suffix(&t, suffix), p)) + .collect(), + None => config.priority_tags.unwrap_or_else(HashMap::new), + }; if priority_tags_map.len() > 0 { let mut all_tags_set: HashSet = HashSet::from_iter(worker_tags.clone()); @@ -2728,6 +2811,93 @@ pub fn load_whitelist_env_vars_from_env() -> std::vec::IntoIter { .into_iter() } +/// Warns, by name only, about each `WHITELIST_ENVS` entry that looks like a credential: +/// every job on the worker can read what is listed there. +pub fn warn_secret_shaped_whitelist_envs() { + for name in load_whitelist_env_vars_from_env().sorted().unique() { + let value = std::env::var(&name).unwrap_or_default(); + if looks_like_secret(&name, &value) { + tracing::warn!( + "WHITELIST_ENVS forwards {name}, which looks like a secret, to every job on \ + this worker, where any script can read it. Store it as a secret variable or \ + resource, or in a secret backend, and remove it from WHITELIST_ENVS" + ); + } + } +} + +fn looks_like_secret(name: &str, value: &str) -> bool { + const SECRET_WORDS: &[&str] = &[ + "TOKEN", + "TOKENS", + "SECRET", + "SECRETS", + "PASSWORD", + "PASSWD", + "KEY", + "APIKEY", + "CREDENTIAL", + "CREDENTIALS", + "AUTH", + "PRIVATE", + ]; + let name_matches = name + .split(|c: char| !c.is_ascii_alphanumeric()) + .any(|word| SECRET_WORDS.contains(&word.to_ascii_uppercase().as_str())); + if name_matches { + return true; + } + + let value = value.trim(); + let is_private_pem = value.contains("-----BEGIN ") && value.contains("PRIVATE KEY-----"); + let is_jwt = value.starts_with("eyJ") && { + let parts: Vec<&str> = value.split('.').collect(); + parts.len() == 3 + && parts.iter().all(|p| { + !p.is_empty() + && p.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '=') + }) + }; + let has_url_password = url::Url::parse(value).is_ok_and(|u| u.password().is_some()); + is_private_pem || is_jwt || has_url_password || is_high_entropy(value) +} + +/// A single token whose longest run between separators is 24+ chars mixing letters and digits +/// with more than 4 bits of entropy per char: above what hex digests, UUIDs and words reach. +/// Scoring the whole value instead flags pod names and cloud resource paths, whose entropy +/// grows with their length. +fn is_high_entropy(value: &str) -> bool { + if !value + .chars() + .all(|c| c.is_ascii_alphanumeric() || "+/=_-".contains(c)) + { + return false; + } + let Some(run) = value.split(['-', '_', '/']).max_by_key(|s| s.len()) else { + return false; + }; + if run.len() < 24 + || !run.chars().any(|c| c.is_ascii_digit()) + || !run.chars().any(|c| c.is_ascii_alphabetic()) + { + return false; + } + let mut counts = HashMap::::new(); + for c in run.chars() { + *counts.entry(c).or_default() += 1; + } + let len = run.len() as f64; + let entropy: f64 = counts + .values() + .map(|&n| { + let p = n as f64 / len; + -p * p.log2() + }) + .sum(); + entropy > 4.0 +} + pub fn load_env_vars( iter: impl Iterator, env_vars_static: &HashMap, @@ -2778,6 +2948,7 @@ pub struct WorkerConfigOpt { pub native_mode: Option, pub object_store_cache_config: Option, pub paused: Option, + pub serves_dev_workspaces: Option, } impl Default for WorkerConfigOpt { @@ -2798,6 +2969,7 @@ impl Default for WorkerConfigOpt { native_mode: Default::default(), object_store_cache_config: Default::default(), paused: Default::default(), + serves_dev_workspaces: Default::default(), } } } @@ -3024,6 +3196,57 @@ mod tests { use super::*; use std::collections::HashMap; + #[test] + fn whitelist_env_secret_heuristic() { + let cases = [ + ("GITHUB_TOKEN", "x", true), + ("aws_secret_access_key", "", true), + ("DB-PASSWORD", "x", true), + ("OPENAI_APIKEY", "x", true), + ("MY_CREDENTIALS", "x", true), + ("PRIVATE_REGISTRY", "x", true), + ("MONKEY", "banana", false), + ("KEYCLOAK_URL", "https://kc.example.com", false), + ("TOKENIZER_PATH", "/opt/tok", false), + ( + "SSH_CFG", + "-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----", + true, + ), + ( + "CA_CERT", + "-----BEGIN CERTIFICATE-----\nabc\n-----END CERTIFICATE-----", + false, + ), + ( + "JWT_LIKE", + "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl", + true, + ), + ("DB_URL", "postgres://user:hunter2@db:5432/app", true), + ("PROXY", "http://proxy.local:3128", false), + ("PROXY_USER", "http://bob@proxy.local:3128", false), + ("OPAQUE", "app_51HxQ2vLk9Tq8ZpR3mNcY7wB4aD6eF0gJ", true), + ("GIT_SHA", "3f786850e387550fdab836ed7e6dc881de23001b", false), + ("RUN_ID", "123e4567-e89b-12d3-a456-426614174000", false), + ( + "SOME_PATH", + "/usr/local/lib/python3.11/site-packages/x1", + false, + ), + ("REGION", "eu-west-1", false), + ("HOSTNAME", "windmill-workers-7d9f8c6b5-x2k4p", false), + ( + "TOPIC", + "projects/my-gcp-project-123/locations/europe-west1", + false, + ), + ]; + for (name, value, expected) in cases { + assert_eq!(looks_like_secret(name, value), expected, "{name}={value}"); + } + } + #[cfg(not(windows))] #[test] fn cgroup_cpu_stat_is_normalized_to_microseconds() { @@ -3614,6 +3837,22 @@ mod tests { assert!(combined.prepare); } + #[test] + fn test_no_network_annotation() { + assert!(PythonAnnotations::parse("# sandbox\n# no_network\ndef main(): pass").no_network); + assert!(!PythonAnnotations::parse("# sandbox\ndef main(): pass").no_network); + assert!(RlangAnnotations::parse("#no_network\nmain <- function() {}").no_network); + assert!( + TypeScriptAnnotations::parse("// no_network\nexport function main() {}").no_network + ); + let bash = "# sandbox alpine\n# no_network\necho hi"; + assert!(BashAnnotations::parse(bash).no_network); + assert_eq!( + BashAnnotations::sandbox_image(bash), + Some("alpine".to_string()) + ); + } + #[test] fn test_python_sandbox_annotation_with_other_annotations() { let content = "# no_cache\n# sandbox\ndef main():\n pass"; diff --git a/backend/windmill-common/src/workspaces.rs b/backend/windmill-common/src/workspaces.rs index b76f006691..1b9412eb5a 100644 --- a/backend/windmill-common/src/workspaces.rs +++ b/backend/windmill-common/src/workspaces.rs @@ -73,6 +73,7 @@ bitflags::bitflags! { const RESTRICT_ANONYMOUS_APP_DEPLOYMENT = 1 << 3; const RESTRICT_PUBLIC_RUN_SHARING = 1 << 4; const RESTRICT_GUEST_APP_DEPLOYMENT = 1 << 5; + const REQUIRE_ISOLATED_FORKS = 1 << 6; } } @@ -86,6 +87,7 @@ pub enum ProtectionRuleKind { RestrictAnonymousAppDeployment, RestrictPublicRunSharing, RestrictGuestAppDeployment, + RequireIsolatedForks, } impl ProtectionRuleKind { @@ -109,6 +111,7 @@ impl ProtectionRuleKind { ProtectionRuleKind::RestrictGuestAppDeployment => { ProtectionRules::RESTRICT_GUEST_APP_DEPLOYMENT } + ProtectionRuleKind::RequireIsolatedForks => ProtectionRules::REQUIRE_ISOLATED_FORKS, } } @@ -130,6 +133,9 @@ impl ProtectionRuleKind { ProtectionRuleKind::RestrictGuestAppDeployment => { "Opening an app to guests (anyone who can sign in) is restricted in this workspace" } + ProtectionRuleKind::RequireIsolatedForks => { + "Forks of this workspace must isolate its data: no shared object storage or ducklake, and every data table cloned" + } } } } @@ -3000,6 +3006,8 @@ lazy_static::lazy_static! { /// broadcasts on `FORK_LINEAGE_CHANGE_CHANNEL`. A process that receives no broadcast — an agent /// worker polls no notify events — has only the TTL, and takes the shorter one. static ref ROOT_WORKSPACE_CACHE: Cache = Cache::new(5000); + /// workspace id -> ((dev or fork, dev lineage), expiry ts), swept with the cache above. + static ref DEV_LINEAGE_CACHE: Cache = Cache::new(5000); } const ROOT_WORKSPACE_CACHE_TTL_S: i64 = 300; @@ -3018,12 +3026,59 @@ const ROOT_WORKSPACE_UNRESOLVED_CACHE_TTL_S: i64 = 30; /// `windmill_queue::tags::invalidate_fork_parent_cache`. pub fn invalidate_root_workspace_cache(w_id: &str) { ROOT_WORKSPACE_CACHE.remove(w_id); + DEV_LINEAGE_CACHE.remove(w_id); } /// Drop every cached root workspace: the answer depends on the whole ancestor chain, so a mutation /// that reshapes the tree moves an unbounded set of descendants. pub fn clear_root_workspace_cache() { ROOT_WORKSPACE_CACHE.clear(); + DEV_LINEAGE_CACHE.clear(); +} + +/// Whether `w_id` has a parent or a generated fork id, and whether a dev workspace is on its +/// ancestor chain: the inputs of `worker::is_isolated_workspace`, as `windmill_queue::tags` reads +/// them, for callers outside that crate. `None` when the lookup failed, which is not cached. +pub async fn dev_lineage(db: &crate::DB, w_id: &str) -> Option<(bool, bool)> { + let now = chrono::Utc::now().timestamp(); + if let Some((lineage, expiry)) = DEV_LINEAGE_CACHE.get(w_id) { + if expiry > now { + return Some(lineage); + } + } + let (has_parent, in_dev_lineage) = sqlx::query_as::<_, (Option, Option)>( + r#" + WITH RECURSIVE chain AS ( + SELECT id, parent_workspace_id, is_dev_workspace, deleted, 0 AS depth + FROM workspace WHERE id = $1 + UNION ALL + SELECT w.id, w.parent_workspace_id, w.is_dev_workspace, w.deleted, chain.depth + 1 + FROM workspace w + JOIN chain ON w.id = chain.parent_workspace_id + WHERE chain.depth < 20 + ) + SELECT + (SELECT parent_workspace_id IS NOT NULL FROM chain WHERE depth = 0), + (SELECT bool_or(is_dev_workspace + OR (parent_workspace_id IS NULL AND id LIKE 'wm-fork-%') + OR (deleted AND parent_workspace_id IS NOT NULL)) + FROM chain) + "#, + ) + .bind(w_id) + .fetch_one(db) + .await + .map_err(|e| tracing::warn!("failed to resolve the dev lineage of {w_id}: {e:#}")) + .ok()?; + let lineage = ( + w_id.starts_with(WM_FORK_PREFIX) || has_parent == Some(true), + in_dev_lineage != Some(false), + ); + DEV_LINEAGE_CACHE.insert( + w_id.to_string(), + (lineage, now + ROOT_WORKSPACE_CACHE_TTL_S), + ); + Some(lineage) } /// Nearest ancestor-or-self of `w_id` that is an environment of its own: a root ("prod") workspace diff --git a/backend/windmill-common/tests/aws_sm_integration.rs b/backend/windmill-common/tests/aws_sm_integration.rs index 3b9aa2ece8..1030dc4d50 100644 --- a/backend/windmill-common/tests/aws_sm_integration.rs +++ b/backend/windmill-common/tests/aws_sm_integration.rs @@ -12,43 +12,24 @@ //! localstack/localstack:3.8 //! ``` //! -//! 2. Run the tests: +//! 2. Run the tests (they are `#[ignore]`d, so a plain `cargo test` skips them): //! //! ```bash -//! RUN_AWS_SM_TESTS=1 cargo test -p windmill-common --features private,enterprise \ -//! aws_sm_integration -- --nocapture +//! cargo test -p windmill-common --features private,enterprise \ +//! --test aws_sm_integration -- --ignored --nocapture //! ``` //! //! ## Environment variables //! -//! - `RUN_AWS_SM_TESTS=1` - Required to run the tests //! - `AWS_SM_ENDPOINT` - LocalStack endpoint (default: http://localhost:4566) //! - `AWS_SM_REGION` - AWS region (default: us-east-1) #[cfg(all(feature = "private", feature = "enterprise"))] mod tests { use windmill_common::secret_backend::{ - test_aws_sm_connection, AwsSecretsManagerBackend, AwsSecretsManagerSettings, - SecretBackend, + test_aws_sm_connection, AwsSecretsManagerBackend, AwsSecretsManagerSettings, SecretBackend, }; - fn should_run_aws_sm_tests() -> bool { - std::env::var("RUN_AWS_SM_TESTS") - .map(|v| v == "1" || v.to_lowercase() == "true") - .unwrap_or(false) - } - - macro_rules! skip_if_no_aws_sm { - () => { - if !should_run_aws_sm_tests() { - println!("Skipping test: RUN_AWS_SM_TESTS=1 not set"); - println!("To run: RUN_AWS_SM_TESTS=1 cargo test -p windmill-common --features private,enterprise aws_sm_integration -- --nocapture"); - println!("Requires: docker run -d -p 4566:4566 -e SERVICES=secretsmanager localstack/localstack:3.8"); - return; - } - }; - } - fn test_settings() -> AwsSecretsManagerSettings { AwsSecretsManagerSettings { region: std::env::var("AWS_SM_REGION").unwrap_or_else(|_| "us-east-1".to_string()), @@ -63,16 +44,16 @@ mod tests { } #[tokio::test] + #[ignore = "requires LocalStack secretsmanager at AWS_SM_ENDPOINT"] async fn test_connection() { - skip_if_no_aws_sm!(); let result = test_aws_sm_connection(&test_settings()).await; assert!(result.is_ok(), "Connection test failed: {:?}", result.err()); println!(" ✓ Connection test passed"); } #[tokio::test] + #[ignore = "requires LocalStack secretsmanager at AWS_SM_ENDPOINT"] async fn test_create_and_get_secret() { - skip_if_no_aws_sm!(); let backend = AwsSecretsManagerBackend::new_with_client(test_settings()) .await .unwrap(); @@ -81,16 +62,22 @@ mod tests { .set_secret("test-ws", "u/admin/my_secret", "super-secret-value") .await .unwrap(); - let value = backend.get_secret("test-ws", "u/admin/my_secret").await.unwrap(); + let value = backend + .get_secret("test-ws", "u/admin/my_secret") + .await + .unwrap(); assert_eq!(value, "super-secret-value"); - backend.delete_secret("test-ws", "u/admin/my_secret").await.unwrap(); + backend + .delete_secret("test-ws", "u/admin/my_secret") + .await + .unwrap(); println!(" ✓ Create + Get + Delete roundtrip passed"); } #[tokio::test] + #[ignore = "requires LocalStack secretsmanager at AWS_SM_ENDPOINT"] async fn test_update_secret() { - skip_if_no_aws_sm!(); let backend = AwsSecretsManagerBackend::new_with_client(test_settings()) .await .unwrap(); @@ -117,8 +104,8 @@ mod tests { } #[tokio::test] + #[ignore = "requires LocalStack secretsmanager at AWS_SM_ENDPOINT"] async fn test_delete_and_verify_gone() { - skip_if_no_aws_sm!(); let backend = AwsSecretsManagerBackend::new_with_client(test_settings()) .await .unwrap(); @@ -142,8 +129,8 @@ mod tests { } #[tokio::test] + #[ignore = "requires LocalStack secretsmanager at AWS_SM_ENDPOINT"] async fn test_delete_nonexistent_is_ok() { - skip_if_no_aws_sm!(); let backend = AwsSecretsManagerBackend::new_with_client(test_settings()) .await .unwrap(); @@ -160,8 +147,8 @@ mod tests { } #[tokio::test] + #[ignore = "requires LocalStack secretsmanager at AWS_SM_ENDPOINT"] async fn test_get_nonexistent_returns_not_found() { - skip_if_no_aws_sm!(); let backend = AwsSecretsManagerBackend::new_with_client(test_settings()) .await .unwrap(); @@ -178,8 +165,8 @@ mod tests { } #[tokio::test] + #[ignore = "requires LocalStack secretsmanager at AWS_SM_ENDPOINT"] async fn test_unicode_and_special_chars() { - skip_if_no_aws_sm!(); let backend = AwsSecretsManagerBackend::new_with_client(test_settings()) .await .unwrap(); @@ -203,8 +190,8 @@ mod tests { } #[tokio::test] + #[ignore = "requires LocalStack secretsmanager at AWS_SM_ENDPOINT"] async fn test_workspace_isolation() { - skip_if_no_aws_sm!(); let backend = AwsSecretsManagerBackend::new_with_client(test_settings()) .await .unwrap(); @@ -244,8 +231,8 @@ mod tests { } #[tokio::test] + #[ignore = "requires LocalStack secretsmanager at AWS_SM_ENDPOINT"] async fn test_backend_name() { - skip_if_no_aws_sm!(); let backend = AwsSecretsManagerBackend::new_with_client(test_settings()) .await .unwrap(); diff --git a/backend/windmill-common/tests/azure_kv_integration.rs b/backend/windmill-common/tests/azure_kv_integration.rs index 7606508abc..110678bd84 100644 --- a/backend/windmill-common/tests/azure_kv_integration.rs +++ b/backend/windmill-common/tests/azure_kv_integration.rs @@ -23,11 +23,12 @@ //! - Trust the emulator's certificate, or //! - Set `AZURE_KV_ALLOW_INSECURE=true` to skip TLS verification (test only) //! -//! 3. Run the tests: +//! 3. Run the tests (they are `#[ignore]`d, so a plain `cargo test` skips them; +//! `AZURE_KV_URL` overrides the default https://localhost:4997): //! //! ```bash -//! RUN_AZURE_KV_TESTS=1 cargo test -p windmill-common --features private,enterprise \ -//! azure_kv_integration -- --nocapture +//! cargo test -p windmill-common --features private,enterprise \ +//! --test azure_kv_integration -- --ignored --nocapture //! ``` //! //! ## Emulator authentication @@ -41,22 +42,6 @@ mod tests { test_azure_kv_connection, AzureKeyVaultBackend, AzureKeyVaultSettings, SecretBackend, }; - fn should_run_azure_kv_tests() -> bool { - std::env::var("RUN_AZURE_KV_TESTS") - .map(|v| v == "1" || v.to_lowercase() == "true") - .unwrap_or(false) - } - - macro_rules! skip_if_no_azure_kv { - () => { - if !should_run_azure_kv_tests() { - println!("Skipping test: RUN_AZURE_KV_TESTS=1 not set"); - println!("To run Azure KV tests: RUN_AZURE_KV_TESTS=1 cargo test ..."); - return; - } - }; - } - /// A minimal valid JWT token (the emulator doesn't verify signatures). /// Format: base64(header).base64(payload).base64(signature) fn dummy_jwt_token() -> String { @@ -82,9 +67,8 @@ mod tests { } #[tokio::test] + #[ignore = "requires an Azure Key Vault emulator at AZURE_KV_URL"] async fn test_azure_kv_connection_with_token() { - skip_if_no_azure_kv!(); - let settings = azure_kv_settings(); println!("Testing Azure KV connection..."); println!(" URL: {}", settings.vault_url); @@ -99,9 +83,8 @@ mod tests { } #[tokio::test] + #[ignore = "requires an Azure Key Vault emulator at AZURE_KV_URL"] async fn test_azure_kv_crud() { - skip_if_no_azure_kv!(); - let backend = create_backend(); let workspace_id = "test-crud"; let path = "test-secret"; @@ -160,9 +143,8 @@ mod tests { } #[tokio::test] + #[ignore = "requires an Azure Key Vault emulator at AZURE_KV_URL"] async fn test_azure_kv_not_found() { - skip_if_no_azure_kv!(); - let backend = create_backend(); let result = backend @@ -173,9 +155,8 @@ mod tests { } #[tokio::test] + #[ignore = "requires an Azure Key Vault emulator at AZURE_KV_URL"] async fn test_azure_kv_secret_name_encoding() { - skip_if_no_azure_kv!(); - let backend = create_backend(); let workspace_id = "demo"; let path = "u/admin/my_secret_key"; diff --git a/backend/windmill-common/tests/secret_backend_integration.rs b/backend/windmill-common/tests/secret_backend_integration.rs index ff41f3acf7..a94a67e336 100644 --- a/backend/windmill-common/tests/secret_backend_integration.rs +++ b/backend/windmill-common/tests/secret_backend_integration.rs @@ -3,24 +3,26 @@ //! These tests require: //! 1. A PostgreSQL database (handled by sqlx test framework) //! 2. A running HashiCorp Vault instance -//! 3. The RUN_VAULT_TESTS=1 environment variable to be set +//! +//! They are `#[ignore]`d, so a plain `cargo test` skips them without creating a +//! database; pass `--ignored` to run them. //! //! Environment variables: -//! - RUN_VAULT_TESTS=1 - Required to run the tests //! - VAULT_ADDR - Vault server address (default: http://127.0.0.1:8200) //! - VAULT_TOKEN - Static token for static token tests (default: test-root-token) //! - BASE_URL - Windmill instance URL for JWT tests (default: http://localhost:8000) //! //! Run tests (static token mode): //! ```bash -//! RUN_VAULT_TESTS=1 VAULT_TOKEN=your-token cargo test -p windmill \ -//! secret_backend_integration --features private,enterprise -- --nocapture +//! VAULT_TOKEN=your-token cargo test -p windmill-common \ +//! --test secret_backend_integration --features private,enterprise -- --ignored --nocapture //! ``` //! //! Run tests (JWT mode - requires Windmill instance running for JWKS endpoint): //! ```bash -//! RUN_VAULT_TESTS=1 BASE_URL=http://localhost:8000 cargo test -p windmill \ -//! secret_backend_integration --features private,enterprise,openidconnect -- --nocapture +//! BASE_URL=http://localhost:8000 cargo test -p windmill-common \ +//! --test secret_backend_integration --features private,enterprise,openidconnect \ +//! -- --ignored --nocapture //! ``` #[cfg(all(feature = "private", feature = "enterprise"))] @@ -62,12 +64,6 @@ mod tests { } } - fn should_run_vault_tests() -> bool { - std::env::var("RUN_VAULT_TESTS") - .map(|v| v == "1" || v.to_lowercase() == "true") - .unwrap_or(false) - } - #[cfg(feature = "openidconnect")] async fn setup_base_url() { let base_url = @@ -75,16 +71,6 @@ mod tests { windmill_common::BASE_URL.store(std::sync::Arc::new(base_url)); } - macro_rules! skip_if_no_vault { - () => { - if !should_run_vault_tests() { - println!("Skipping test: RUN_VAULT_TESTS=1 not set"); - println!("To run vault tests: RUN_VAULT_TESTS=1 cargo test ..."); - return; - } - }; - } - fn vault_settings_static_token() -> VaultSettings { VaultSettings { address: std::env::var("VAULT_ADDR") @@ -120,9 +106,8 @@ mod tests { /// Test Vault connection with static token #[sqlx::test(migrations = "../migrations", fixtures("base", "secret_backend"))] + #[ignore = "requires a Vault server at VAULT_ADDR"] async fn test_vault_connection_static_token(db: Pool) { - skip_if_no_vault!(); - let settings = vault_settings_static_token(); println!("Testing Vault connection with static token..."); println!(" Address: {}", settings.address); @@ -138,9 +123,8 @@ mod tests { /// Test basic CRUD operations with static token #[sqlx::test(migrations = "../migrations", fixtures("base", "secret_backend"))] + #[ignore = "requires a Vault server at VAULT_ADDR"] async fn test_vault_crud_static_token(_db: Pool) { - skip_if_no_vault!(); - let settings = vault_settings_static_token(); let backend = VaultBackend::new(settings); @@ -199,8 +183,8 @@ mod tests { /// Test Vault connection with JWT authentication #[cfg(feature = "openidconnect")] #[sqlx::test(migrations = "../migrations", fixtures("base", "secret_backend"))] + #[ignore = "requires a Vault server at VAULT_ADDR and a Windmill instance at BASE_URL"] async fn test_vault_connection_jwt(db: Pool) { - skip_if_no_vault!(); setup_base_url().await; let settings = vault_settings_jwt(); @@ -224,8 +208,8 @@ mod tests { /// Test basic CRUD operations with JWT authentication #[cfg(feature = "openidconnect")] #[sqlx::test(migrations = "../migrations", fixtures("base", "secret_backend"))] + #[ignore = "requires a Vault server at VAULT_ADDR and a Windmill instance at BASE_URL"] async fn test_vault_crud_jwt(db: Pool) { - skip_if_no_vault!(); setup_base_url().await; let settings = vault_settings_jwt(); @@ -269,9 +253,8 @@ mod tests { /// Test migration from database to Vault #[sqlx::test(migrations = "../migrations", fixtures("base", "secret_backend"))] + #[ignore = "requires a Vault server at VAULT_ADDR"] async fn test_migrate_db_to_vault(db: Pool) { - skip_if_no_vault!(); - let settings = vault_settings_static_token(); test_vault_connection(&settings, Some(&db)) @@ -331,9 +314,8 @@ mod tests { /// Test migration from Vault back to database #[sqlx::test(migrations = "../migrations", fixtures("base", "secret_backend"))] + #[ignore = "requires a Vault server at VAULT_ADDR"] async fn test_migrate_vault_to_db(db: Pool) { - skip_if_no_vault!(); - let settings = vault_settings_static_token(); test_vault_connection(&settings, Some(&db)) @@ -396,8 +378,8 @@ mod tests { /// Test renaming a variable path in Vault #[sqlx::test(migrations = "../migrations", fixtures("base", "secret_backend"))] + #[ignore = "requires a Vault server at VAULT_ADDR"] async fn test_variable_rename(db: Pool) { - skip_if_no_vault!(); let _ = &db; // suppress unused warning let settings = vault_settings_static_token(); @@ -468,9 +450,8 @@ mod tests { /// Test full round-trip: DB -> Vault -> DB with verification #[sqlx::test(migrations = "../migrations", fixtures("base", "secret_backend"))] + #[ignore = "requires a Vault server at VAULT_ADDR"] async fn test_full_round_trip(db: Pool) { - skip_if_no_vault!(); - let settings = vault_settings_static_token(); test_vault_connection(&settings, Some(&db)) @@ -532,9 +513,8 @@ mod tests { /// Test that workspace isolation is maintained #[sqlx::test(migrations = "../migrations", fixtures("base", "secret_backend"))] + #[ignore = "requires a Vault server at VAULT_ADDR"] async fn test_workspace_isolation(db: Pool) { - skip_if_no_vault!(); - let settings = vault_settings_static_token(); let backend = VaultBackend::new(settings.clone()); diff --git a/backend/windmill-dep-map/Cargo.toml b/backend/windmill-dep-map/Cargo.toml index a93376d167..699ef89f53 100644 --- a/backend/windmill-dep-map/Cargo.toml +++ b/backend/windmill-dep-map/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_dep_map" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-git-sync/Cargo.toml b/backend/windmill-git-sync/Cargo.toml index 2b691ee48e..40752660f1 100644 --- a/backend/windmill-git-sync/Cargo.toml +++ b/backend/windmill-git-sync/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_git_sync" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] private = ["windmill-common/private", "windmill-dep-map/private", "windmill-audit/private"] diff --git a/backend/windmill-indexer/Cargo.toml b/backend/windmill-indexer/Cargo.toml index 09b2bbe5b1..a90d51c21d 100644 --- a/backend/windmill-indexer/Cargo.toml +++ b/backend/windmill-indexer/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_indexer" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-jseval/Cargo.toml b/backend/windmill-jseval/Cargo.toml index b2f7217404..ea5b22d3b4 100644 --- a/backend/windmill-jseval/Cargo.toml +++ b/backend/windmill-jseval/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_jseval" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-macros/Cargo.toml b/backend/windmill-macros/Cargo.toml index 5d7d12cc6a..bb4e5c0928 100644 --- a/backend/windmill-macros/Cargo.toml +++ b/backend/windmill-macros/Cargo.toml @@ -6,6 +6,9 @@ edition.workspace = true [lib] proc-macro = true +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] proc-macro2.workspace = true diff --git a/backend/windmill-mcp/Cargo.toml b/backend/windmill-mcp/Cargo.toml index 2c07b92d44..aac854024f 100644 --- a/backend/windmill-mcp/Cargo.toml +++ b/backend/windmill-mcp/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_mcp" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-mcp/src/client/mod.rs b/backend/windmill-mcp/src/client/mod.rs index 6f3928e112..49e71d9734 100644 --- a/backend/windmill-mcp/src/client/mod.rs +++ b/backend/windmill-mcp/src/client/mod.rs @@ -88,8 +88,9 @@ impl McpClient { // and does not legitimately rely on redirects. .redirect(reqwest::redirect::Policy::none()); // Pin DNS to the address validated above so the connect cannot rebind to - // an internal IP between the check and the request. Empty addrs (IP literal - // or ALLOW_PRIVATE_MCP_SERVER_URLS) leave resolution untouched. + // an internal IP between the check and the request. Empty addrs (IP literal, + // or a host ALLOW_PRIVATE_MCP_SERVER_URLS allows by name or by `true`) leave + // resolution untouched. if !validated.addrs.is_empty() { client_builder = client_builder.resolve_to_addrs(&validated.host, &validated.addrs); } diff --git a/backend/windmill-mcp/src/lib.rs b/backend/windmill-mcp/src/lib.rs index 33a20be2f0..c9daf25da9 100644 --- a/backend/windmill-mcp/src/lib.rs +++ b/backend/windmill-mcp/src/lib.rs @@ -81,8 +81,9 @@ pub mod oauth { /// guard validated for the request URL so the connect cannot rebind to an /// internal IP after the check (TOCTOU). The OAuth DCR/discovery/token /// requests target author-controlled URLs and carry secrets, so they must - /// go through this rather than the unpinned client. Empty `addrs` (IP literal - /// or ALLOW_PRIVATE_MCP_SERVER_URLS) leaves resolution untouched. + /// go through this rather than the unpinned client. Empty `addrs` (IP literal, + /// or a host ALLOW_PRIVATE_MCP_SERVER_URLS allows by name or by `true`) leaves + /// resolution untouched. pub fn no_redirect_http_client_pinned( target: &windmill_common::ssrf::ValidatedTarget, ) -> Result { diff --git a/backend/windmill-native-triggers/Cargo.toml b/backend/windmill-native-triggers/Cargo.toml index 126c22c7c0..1f14154b7e 100644 --- a/backend/windmill-native-triggers/Cargo.toml +++ b/backend/windmill-native-triggers/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_native_triggers" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-oauth/Cargo.toml b/backend/windmill-oauth/Cargo.toml index 85499442b9..d1014da07d 100644 --- a/backend/windmill-oauth/Cargo.toml +++ b/backend/windmill-oauth/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_oauth" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-object-store/Cargo.toml b/backend/windmill-object-store/Cargo.toml index f80eb88881..9737440196 100644 --- a/backend/windmill-object-store/Cargo.toml +++ b/backend/windmill-object-store/Cargo.toml @@ -24,6 +24,8 @@ openidconnect = ["windmill-common/openidconnect"] [lib] name = "windmill_object_store" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-common = { workspace = true, default-features = false } diff --git a/backend/windmill-object-store/src/fork_store.rs b/backend/windmill-object-store/src/fork_store.rs new file mode 100644 index 0000000000..a7d283a09e --- /dev/null +++ b/backend/windmill-object-store/src/fork_store.rs @@ -0,0 +1,260 @@ +//! An [`ObjectStore`] over one workspace storage that applies the workspace's +//! [`ForkStorageKeys`]: callers keep using logical keys. + +use std::sync::Arc; + +use futures::{stream::BoxStream, StreamExt, TryStreamExt}; +use object_store::path::Path; +use object_store::{ + GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, PutMultipartOpts, + PutOptions, PutPayload, PutResult, Result, +}; +use windmill_common::fork_storage::{fork_storage_keys, ForkStorageKeys}; + +use crate::{build_object_store_client, ObjectStoreResource}; + +/// The client for `w_id`'s storage `storage` (None = default). Every server-side access to a +/// workspace storage by logical key goes through this, so fork isolation holds on each path. +/// +/// It checks no authorization: the caller must already have checked that the requester may +/// use `w_id`'s storage, and its permission rules for each key it reads or writes. +pub async fn workspace_object_store( + db: &windmill_common::DB, + w_id: &str, + storage: Option<&str>, + resource: &ObjectStoreResource, +) -> windmill_common::error::Result> { + Ok(workspace_fork_store(db, w_id, storage, resource).await?) +} + +/// [`workspace_object_store`] as its concrete type, under the same authorization contract. +pub async fn workspace_fork_store( + db: &windmill_common::DB, + w_id: &str, + storage: Option<&str>, + resource: &ObjectStoreResource, +) -> windmill_common::error::Result> { + let inner = build_object_store_client(resource).await?; + let keys = fork_storage_keys(db, w_id, storage).await?; + Ok(Arc::new(ForkStore { inner, keys })) +} + +#[derive(Debug)] +pub struct ForkStore { + inner: Arc, + keys: Arc, +} + +impl ForkStore { + pub fn new(inner: Arc, keys: Arc) -> Self { + Self { inner, keys } + } + + pub fn keys(&self) -> &ForkStorageKeys { + &self.keys + } + + /// This store with reads confined to the workspace's own copies. + pub fn own_only(&self) -> Arc { + Arc::new(ForkStore { inner: self.inner.clone(), keys: Arc::new(self.keys.own_only()) }) + } +} + +impl std::fmt::Display for ForkStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "ForkStore({})", self.inner) + } +} + +fn denied(location: &Path, e: windmill_common::error::Error) -> object_store::Error { + object_store::Error::PermissionDenied { path: location.to_string(), source: Box::new(e) } +} + +fn parse(key: String) -> Result { + Path::parse(key).map_err(|source| object_store::Error::InvalidPath { source }) +} + +impl ForkStore { + fn write_path(&self, location: &Path) -> Result { + parse( + self.keys + .write_key(location.as_ref()) + .map_err(|e| denied(location, e))?, + ) + } + + fn read_paths(&self, location: &Path) -> Result> { + self.keys + .read_keys(location.as_ref()) + .map_err(|e| denied(location, e))? + .into_iter() + .map(parse) + .collect() + } + + /// The physical path of the first of `location`'s read paths that exists (the last one + /// when none does). + pub async fn resolve_read(&self, location: &Path) -> Result { + parse(self.resolve_read_key(location.as_ref()).await?) + } + + /// [`Self::resolve_read`] on a raw key, for callers that forward the key themselves. + pub async fn resolve_read_key(&self, key: &str) -> Result { + let location = Path::from(key); + let mut keys = self.keys.read_keys(key).map_err(|e| denied(&location, e))?; + let last = keys.pop().expect("read_keys returns at least one key"); + for candidate in keys { + match self.inner.head(&parse(candidate.clone())?).await { + Ok(_) => return Ok(candidate), + Err(object_store::Error::NotFound { .. }) => continue, + Err(e) => return Err(e), + } + } + Ok(last) + } +} + +#[async_trait::async_trait] +impl ObjectStore for ForkStore { + async fn put_opts( + &self, + location: &Path, + payload: PutPayload, + opts: PutOptions, + ) -> Result { + self.inner + .put_opts(&self.write_path(location)?, payload, opts) + .await + } + + async fn put_multipart_opts( + &self, + location: &Path, + opts: PutMultipartOpts, + ) -> Result> { + self.inner + .put_multipart_opts(&self.write_path(location)?, opts) + .await + } + + async fn get_opts(&self, location: &Path, options: GetOptions) -> Result { + let paths = self.read_paths(location)?; + let last = paths.len() - 1; + for (i, path) in paths.into_iter().enumerate() { + match self.inner.get_opts(&path, options.clone()).await { + Err(object_store::Error::NotFound { .. }) if i < last => continue, + Ok(mut result) => { + result.meta.location = location.clone(); + return Ok(result); + } + Err(e) => return Err(e), + } + } + unreachable!("read_keys returns at least one key") + } + + async fn head(&self, location: &Path) -> Result { + let paths = self.read_paths(location)?; + let last = paths.len() - 1; + for (i, path) in paths.into_iter().enumerate() { + match self.inner.head(&path).await { + Err(object_store::Error::NotFound { .. }) if i < last => continue, + Ok(meta) => return Ok(ObjectMeta { location: location.clone(), ..meta }), + Err(e) => return Err(e), + } + } + unreachable!("read_keys returns at least one key") + } + + /// Removes this workspace's copy only: an ancestor's object stays readable through it. + async fn delete(&self, location: &Path) -> Result<()> { + self.inner.delete(&self.write_path(location)?).await + } + + fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result> { + let prefix = prefix.map(|p| p.as_ref().to_string()).unwrap_or_default(); + let mapping = match self.keys.list(&prefix) { + Ok(m) => m, + Err(e) => { + let err = denied(&Path::from(prefix), e); + return futures::stream::once(async move { Err(err) }).boxed(); + } + }; + let physical = Path::from(mapping.physical_prefix.clone()); + self.inner + .list(Some(&physical)) + .try_filter_map(move |meta| { + let logical = mapping.logical_key(meta.location.as_ref()); + futures::future::ready(Ok(logical + .and_then(|l| Path::parse(l).ok()) + .map(|location| ObjectMeta { location, ..meta }))) + }) + .boxed() + } + + fn list_with_offset( + &self, + prefix: Option<&Path>, + offset: &Path, + ) -> BoxStream<'static, Result> { + let prefix = prefix.map(|p| p.as_ref().to_string()).unwrap_or_default(); + let mapping = match self.keys.list(&prefix) { + Ok(m) => m, + Err(e) => { + let err = denied(&Path::from(prefix), e); + return futures::stream::once(async move { Err(err) }).boxed(); + } + }; + let physical = Path::from(mapping.physical_prefix.clone()); + let physical_offset = match parse(mapping.physical_key(offset.as_ref())) { + Ok(p) => p, + Err(e) => return futures::stream::once(async move { Err(e) }).boxed(), + }; + self.inner + .list_with_offset(Some(&physical), &physical_offset) + .try_filter_map(move |meta| { + let logical = mapping.logical_key(meta.location.as_ref()); + futures::future::ready(Ok(logical + .and_then(|l| Path::parse(l).ok()) + .map(|location| ObjectMeta { location, ..meta }))) + }) + .boxed() + } + + async fn list_with_delimiter(&self, prefix: Option<&Path>) -> Result { + let prefix_str = prefix.map(|p| p.as_ref().to_string()).unwrap_or_default(); + let mapping = self + .keys + .list(&prefix_str) + .map_err(|e| denied(&Path::from(prefix_str.clone()), e))?; + let physical = Path::from(mapping.physical_prefix.clone()); + let listed = self.inner.list_with_delimiter(Some(&physical)).await?; + let logical = |p: &Path| { + mapping + .logical_key(p.as_ref()) + .and_then(|l| Path::parse(l).ok()) + }; + Ok(ListResult { + common_prefixes: listed.common_prefixes.iter().filter_map(logical).collect(), + objects: listed + .objects + .into_iter() + .filter_map(|meta| { + logical(&meta.location).map(|location| ObjectMeta { location, ..meta }) + }) + .collect(), + }) + } + + async fn copy(&self, from: &Path, to: &Path) -> Result<()> { + let from = self.resolve_read(from).await?; + self.inner.copy(&from, &self.write_path(to)?).await + } + + async fn copy_if_not_exists(&self, from: &Path, to: &Path) -> Result<()> { + let from = self.resolve_read(from).await?; + self.inner + .copy_if_not_exists(&from, &self.write_path(to)?) + .await + } +} diff --git a/backend/windmill-object-store/src/lib.rs b/backend/windmill-object-store/src/lib.rs index a9551ad835..4e40d6e313 100644 --- a/backend/windmill-object-store/src/lib.rs +++ b/backend/windmill-object-store/src/lib.rs @@ -59,6 +59,8 @@ use windmill_common::utils::rd_string; pub mod job_s3_helpers_ee; #[cfg(feature = "parquet")] pub mod job_s3_helpers_oss; +#[cfg(feature = "parquet")] +pub mod fork_store; // Re-export object_store types so consumers don't need a direct object_store dep #[cfg(feature = "parquet")] diff --git a/backend/windmill-operator/Cargo.toml b/backend/windmill-operator/Cargo.toml index f847e4ab25..97c6960a8a 100644 --- a/backend/windmill-operator/Cargo.toml +++ b/backend/windmill-operator/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_operator" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] enterprise = ["windmill-common/enterprise"] diff --git a/backend/windmill-queue/Cargo.toml b/backend/windmill-queue/Cargo.toml index 6dc5d8ba42..de788f9f25 100644 --- a/backend/windmill-queue/Cargo.toml +++ b/backend/windmill-queue/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_queue" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index 2ed6d034b2..eafb344870 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -4778,6 +4778,9 @@ pub async fn pull( } } }; + let tag = + crate::tags::apply_dev_workspace_suffix(tag, &job.workspace_id, db) + .await?; sqlx::query!( "UPDATE v2_job_queue SET tag = $1, running = false WHERE id = $2", tag, @@ -7372,7 +7375,8 @@ async fn push_inner<'c, 'd>( // A dedicated worker runs every job it serves with its own unscoped worker token, so a // job with a restricted token runs on the regular workers of its language instead. - let tag = if dedicated_worker.is_some_and(|x| x) && job_token_scopes.is_none() { + let on_dedicated_worker = dedicated_worker.is_some_and(|x| x) && job_token_scopes.is_none(); + let tag = if on_dedicated_worker { let flow_prefix = if job_kind == JobKind::Flow || job_kind == JobKind::FlowDependencies { "flow/" } else { @@ -7453,6 +7457,11 @@ async fn push_inner<'c, 'd>( } }) }; + let tag = if on_dedicated_worker { + tag + } else { + crate::tags::apply_dev_workspace_suffix(tag, workspace_id, db).await? + }; let mut tx = tx.into_tx().await?; diff --git a/backend/windmill-queue/src/tags.rs b/backend/windmill-queue/src/tags.rs index 5f076bd3b2..b31e3d99c3 100644 --- a/backend/windmill-queue/src/tags.rs +++ b/backend/windmill-queue/src/tags.rs @@ -1,6 +1,10 @@ use sqlx::{Pool, Postgres}; +use windmill_common::error::Error; use windmill_common::worker::{ - DEFAULT_TAGS_PER_WORKSPACE, DEFAULT_TAGS_WORKSPACES, FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX, + dedicated_worker_tag, dev_workspace_tag_suffix, is_hashed_dedicated_worker_tag, + is_isolated_workspace, with_dev_workspace_suffix, DEFAULT_TAGS_PER_WORKSPACE, + DEFAULT_TAGS_WORKSPACES, DEV_WORKSPACE_TAG_SUFFIX, FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX, + MAX_TAG_LEN, WORKER_SERVES_DEV_WORKSPACES, }; use windmill_common::workspaces::WM_FORK_PREFIX; @@ -13,6 +17,22 @@ struct TagWorkspace { /// Whether the `-fork` suffix may apply: the workspace shares an ancestor's id, or carries the /// generated prefix itself. is_fork: bool, + /// Whether the workspace's jobs run on the workers serving dev workspaces: it has a parent, + /// or carries the generated prefix (a fork orphaned by its parent's deletion stays a fork). + /// `None` when the lookup failed. + is_dev: Option, + /// Whether a dev workspace is on the ancestor chain, the workspace itself included. A fork + /// orphaned by its parent's deletion counts as one, and so does an archived ancestor with a + /// parent: archiving a dev workspace clears its flag, so neither shows what the lineage was. + in_dev_lineage: bool, +} + +impl TagWorkspace { + /// Whether its jobs go to the workers serving dev workspaces, `None` when the lookup failed. + fn is_isolated(&self) -> Option { + self.is_dev + .map(|is_dev| is_isolated_workspace(is_dev, self.in_dev_lineage)) + } } lazy_static::lazy_static! { @@ -21,7 +41,7 @@ lazy_static::lazy_static! { // invalidates the mutated workspace AND its descendants; a parentless result is still cached // briefly so non-forks (the common case) do not hammer the DB. static ref FORK_PARENT_CACHE: quick_cache::sync::Cache = - quick_cache::sync::Cache::new(500); + quick_cache::sync::Cache::new(5000); } /// Channel on which a lineage change is broadcast to every server and worker process. @@ -41,16 +61,20 @@ const CLEAR_ALL: &str = "*"; pub fn invalidate_fork_parent_cache(workspace_id: &str) { FORK_PARENT_CACHE.remove(workspace_id); windmill_common::workspaces::invalidate_root_workspace_cache(workspace_id); + windmill_common::fork_storage::invalidate_fork_storage_keys_cache(workspace_id); } -/// Apply a broadcast lineage change to this process's caches. +/// Apply a broadcast lineage change to this process's caches. The object storage key mapping is +/// among them: a replica keeping a recreated fork's old mapping would write the wrong keys. pub fn apply_fork_lineage_change(payload: &str) { if payload == CLEAR_ALL { FORK_PARENT_CACHE.clear(); windmill_common::workspaces::clear_root_workspace_cache(); + windmill_common::fork_storage::clear_fork_storage_keys_cache(); } else { FORK_PARENT_CACHE.remove(payload); windmill_common::workspaces::invalidate_root_workspace_cache(payload); + windmill_common::fork_storage::invalidate_fork_storage_keys_cache(payload); } } @@ -140,9 +164,154 @@ pub async fn per_workspace_tag(workspace_id: &str, db: &Pool) -> Optio }) } +/// `tag`, fully resolved, as a job of `workspace_id` is queued on it: suffixed with the dev +/// workspace tag suffix when isolation is on and the workspace is a dev workspace or a fork, so +/// only the worker groups serving dev workspaces pick it up. A tag no group serves leaves the job +/// queued; it never falls back to the unsuffixed tag. Dedicated worker tags are exempt: they +/// already name the workspace and an admin places each dedicated worker by hand. +pub async fn apply_dev_workspace_suffix( + tag: String, + workspace_id: &str, + db: &Pool, +) -> Result { + let Some(suffix) = dev_workspace_suffix_for(workspace_id, db).await? else { + return Ok(tag); + }; + if is_dedicated_worker_tag_of(workspace_id, &tag, db).await? { + return Ok(tag); + } + let suffixed = with_dev_workspace_suffix(&tag, &suffix); + if suffixed.len() > MAX_TAG_LEN { + return Err(Error::BadRequest(format!( + "tag {tag} of a dev workspace job would be {suffixed} once suffixed with {suffix}, \ + longer than the {MAX_TAG_LEN} characters a job tag holds" + ))); + } + Ok(suffixed) +} + +/// Whether `tag` is a dedicated worker tag of `workspace_id`. A hashed one keeps only a prefix of +/// the workspace id, which another workspace may share, so it counts only when a worker group's +/// dedicated config for this workspace produces it. +async fn is_dedicated_worker_tag_of( + workspace_id: &str, + tag: &str, + db: &Pool, +) -> Result { + if tag.starts_with(&format!("{workspace_id}:")) { + return Ok(true); + } + if !is_hashed_dedicated_worker_tag(tag) { + return Ok(false); + } + let configs = sqlx::query_scalar!("SELECT config FROM config WHERE name LIKE 'worker\\_\\_%'") + .fetch_all(db) + .await?; + Ok(configs.into_iter().flatten().any(|config| { + let single = config.get("dedicated_worker").cloned().into_iter(); + let many = config + .get("dedicated_workers") + .and_then(|v| v.as_array().cloned()) + .unwrap_or_default(); + single.chain(many).any(|entry| { + entry + .as_str() + .and_then(|e| e.split_once(':')) + .is_some_and(|(ws, path)| { + ws == workspace_id && dedicated_worker_tag(ws, path) == tag + }) + }) + })) +} + +/// Gives `new_id` the lineage of `old_id` before a rename commits: the rename re-pushes the +/// workspace's schedules in its own transaction, where the new row is not yet visible to the +/// lookup, and a job queued then would keep a tag resolved without its parent for good. +pub async fn carry_lineage_over_rename( + old_id: &str, + new_id: &str, + db: &Pool, +) -> Result<(), Error> { + let old = lookup_tag_workspace(old_id, db).await; + if old.is_dev.is_none() { + return Err(Error::internal_err(format!( + "could not resolve the lineage of {old_id}" + ))); + } + let new = TagWorkspace { + id: if old.id == old_id { + new_id.to_string() + } else { + old.id + }, + ..old + }; + FORK_PARENT_CACHE.insert(new_id.to_string(), (new, std::time::Instant::now())); + Ok(()) +} + +/// The suffix to strip from a flow job's tag to compare it with the generic flow tags: that of a +/// dev workspace's flow, isolation on or off, so a flow started before isolation was turned off +/// still routes its steps by their own tags. +pub async fn dev_flow_tag_suffix( + workspace_id: &str, + flow_tag: &str, + db: &Pool, +) -> Result, Error> { + let suffix = DEV_WORKSPACE_TAG_SUFFIX.load(); + if !flow_tag.ends_with(suffix.as_str()) { + return Ok(None); + } + match lookup_tag_workspace(workspace_id, db).await.is_dev { + Some(true) => Ok(Some(suffix.to_string())), + Some(false) => Ok(None), + None => Err(Error::internal_err(format!( + "could not resolve whether {workspace_id} is a dev workspace" + ))), + } +} + +/// The suffix the jobs of `workspace_id` are queued with: `Some` while isolation is on and the +/// workspace is a dev workspace or a fork, unless it is a fork of a non-dev workspace and the +/// instance does not isolate those. A lineage that cannot be read is an error rather than +/// a guess, as either guess queues a job on the wrong pool for good. +pub async fn dev_workspace_suffix_for( + workspace_id: &str, + db: &Pool, +) -> Result, Error> { + let Some(suffix) = dev_workspace_tag_suffix() else { + return Ok(None); + }; + match lookup_tag_workspace(workspace_id, db).await.is_isolated() { + Some(true) => Ok(Some(suffix)), + Some(false) => Ok(None), + None => Err(Error::internal_err(format!( + "could not resolve whether {workspace_id} is a dev workspace, which decides the \ + workers its jobs run on" + ))), + } +} + +/// Refuses running code of `workspace_id` in this process, as the inline routes do, when its +/// jobs are isolated on dev workers and this process's group does not serve dev workspaces. +pub async fn check_inline_run_allowed( + workspace_id: &str, + db: &Pool, +) -> Result<(), Error> { + if dev_workspace_suffix_for(workspace_id, db).await?.is_some() + && !WORKER_SERVES_DEV_WORKSPACES.load(std::sync::atomic::Ordering::Relaxed) + { + return Err(Error::BadRequest(format!( + "{workspace_id} is a dev workspace or a fork, whose code runs only on worker groups \ + serving dev workspaces, and this worker's group does not: run it as a job instead" + ))); + } + Ok(()) +} + /// Backed by a short-TTL cache to avoid a DB round-trip per job push. A transient DB error resolves /// to the workspace's own id for this call but is NOT cached, so the next push retries instead of -/// misrouting for the whole TTL. +/// misrouting for the whole TTL. Whether the workspace is dev is then unknown. async fn lookup_tag_workspace(workspace_id: &str, db: &Pool) -> TagWorkspace { if let Some((resolved, cached_at)) = FORK_PARENT_CACHE.get(workspace_id) { if cached_at.elapsed().as_secs() < FORK_PARENT_CACHE_TTL_SECS { @@ -154,46 +323,65 @@ async fn lookup_tag_workspace(workspace_id: &str, db: &Pool) -> TagWor // itself under a generated fork id. The depth bound mirrors the other chain walkers as a // cycle-safety backstop. A `wm-fork-` workspace orphaned by `ON DELETE SET NULL` has no parent // left to borrow from, so it ends the walk on itself. - let resolved = match sqlx::query_scalar!( + let resolved = match sqlx::query!( r#" WITH RECURSIVE chain AS ( - SELECT id, parent_workspace_id, is_dev_workspace, 0 AS depth + SELECT id, parent_workspace_id, is_dev_workspace, deleted, 0 AS depth FROM workspace WHERE id = $1 UNION ALL - SELECT w.id, w.parent_workspace_id, w.is_dev_workspace, chain.depth + 1 + SELECT w.id, w.parent_workspace_id, w.is_dev_workspace, w.deleted, chain.depth + 1 FROM workspace w JOIN chain ON w.id = chain.parent_workspace_id WHERE chain.depth < 20 ) - SELECT id AS "id!" FROM chain - WHERE parent_workspace_id IS NULL - OR (is_dev_workspace AND id NOT LIKE 'wm-fork-%') - ORDER BY depth LIMIT 1 + SELECT + (SELECT id FROM chain + WHERE parent_workspace_id IS NULL + OR (is_dev_workspace AND id NOT LIKE 'wm-fork-%') + ORDER BY depth LIMIT 1) AS id, + (SELECT parent_workspace_id IS NOT NULL FROM chain WHERE depth = 0) AS has_parent, + (SELECT bool_or(is_dev_workspace + OR (parent_workspace_id IS NULL AND id LIKE 'wm-fork-%') + OR (deleted AND parent_workspace_id IS NOT NULL)) + FROM chain) AS in_dev_lineage "#, workspace_id ) - .fetch_optional(db) + .fetch_one(db) .await { - // No row means the workspace does not exist yet, or its chain is broken: both are "we - // cannot resolve this", so fall back to its own id for this call WITHOUT caching. Caching - // it would pin a fork to its own unserved id for the whole TTL — a rename resolves the new - // id before the row lands, and every job pushed until the TTL expires would queue. - Ok(None) => { - return TagWorkspace { - id: workspace_id.to_string(), - is_fork: workspace_id.starts_with(WM_FORK_PREFIX), + Ok(row) => match row.id { + Some(id) => TagWorkspace { + is_fork: id != workspace_id || workspace_id.starts_with(WM_FORK_PREFIX), + is_dev: Some( + row.has_parent == Some(true) || workspace_id.starts_with(WM_FORK_PREFIX), + ), + in_dev_lineage: row.in_dev_lineage != Some(false), + id, + }, + // No id means the workspace does not exist yet, or its chain is broken: both are "we + // cannot resolve this", so fall back to its own id for this call WITHOUT caching. + // Caching it would pin a fork to its own unserved id for the whole TTL — a rename + // resolves the new id before the row lands, and every job pushed until the TTL + // expires would queue. + None => { + return TagWorkspace { + id: workspace_id.to_string(), + is_fork: workspace_id.starts_with(WM_FORK_PREFIX), + is_dev: Some( + row.has_parent == Some(true) || workspace_id.starts_with(WM_FORK_PREFIX), + ), + in_dev_lineage: true, + } } - } - Ok(Some(id)) => { - let is_fork = id != workspace_id || workspace_id.starts_with(WM_FORK_PREFIX); - TagWorkspace { id, is_fork } - } + }, Err(e) => { tracing::warn!("failed to resolve tag workspace for {workspace_id}: {e:#}"); return TagWorkspace { id: workspace_id.to_string(), is_fork: workspace_id.starts_with(WM_FORK_PREFIX), + is_dev: None, + in_dev_lineage: true, }; } }; diff --git a/backend/windmill-queue/tests/concurrency_counter_test.rs b/backend/windmill-queue/tests/concurrency_counter_test.rs index b341c317bb..9c55617516 100644 --- a/backend/windmill-queue/tests/concurrency_counter_test.rs +++ b/backend/windmill-queue/tests/concurrency_counter_test.rs @@ -349,8 +349,10 @@ mod concurrency { /// `limit` and spawns N workers; all must reject. Reports elapsed. /// Useful for comparing legacy FOR-UPDATE-on-every-pull vs the lockless /// precheck — same setup, just toggle the function under test by checking - /// out the legacy file before running. + /// out the legacy file before running. `bail_path_no_admits_when_full` pins the + /// zero-admit behavior in CI. #[sqlx::test(migrations = "../migrations")] + #[ignore = "manual benchmark: cargo test --test concurrency_counter_test -- --ignored"] async fn bench_over_limit_storm(db: Pool) { let key = "bench-over-limit-storm".to_string(); let limit: i32 = 5; @@ -408,8 +410,10 @@ mod concurrency { /// fail with the offending iteration index. /// /// This is a single test rather than 500 cargo invocations so the cost - /// is one DB setup, not 500. Total ~30s. + /// is one DB setup, not 500. Total ~30s, so it is a manual soak: in CI + /// `stress_never_over_admits` and `stress_matrix` run the same storm. #[sqlx::test(migrations = "../migrations")] + #[ignore = "manual soak: cargo test --test concurrency_counter_test -- --ignored"] async fn long_haul_stress(db: Pool) { let limit: i32 = 2; let workers: usize = 100; diff --git a/backend/windmill-runtime-nativets/Cargo.toml b/backend/windmill-runtime-nativets/Cargo.toml index 22da97ab1d..054505e886 100644 --- a/backend/windmill-runtime-nativets/Cargo.toml +++ b/backend/windmill-runtime-nativets/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_runtime_nativets" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-store/Cargo.toml b/backend/windmill-store/Cargo.toml index 31cd0fbe0f..fefb6467e5 100644 --- a/backend/windmill-store/Cargo.toml +++ b/backend/windmill-store/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_store" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-test-utils/Cargo.toml b/backend/windmill-test-utils/Cargo.toml index 3e409717bd..d8d938a1e8 100644 --- a/backend/windmill-test-utils/Cargo.toml +++ b/backend/windmill-test-utils/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_test_utils" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-amqp/Cargo.toml b/backend/windmill-trigger-amqp/Cargo.toml index 4c5ce41941..ac22b7bdf5 100644 --- a/backend/windmill-trigger-amqp/Cargo.toml +++ b/backend/windmill-trigger-amqp/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_trigger_amqp" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-azure/Cargo.toml b/backend/windmill-trigger-azure/Cargo.toml index 31fb9a9fc7..bac8c58841 100644 --- a/backend/windmill-trigger-azure/Cargo.toml +++ b/backend/windmill-trigger-azure/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_trigger_azure" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-email/Cargo.toml b/backend/windmill-trigger-email/Cargo.toml index 0ed00fa2dd..d4d477f509 100644 --- a/backend/windmill-trigger-email/Cargo.toml +++ b/backend/windmill-trigger-email/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_trigger_email" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-gcp/Cargo.toml b/backend/windmill-trigger-gcp/Cargo.toml index 1b106171c6..e649f970e1 100644 --- a/backend/windmill-trigger-gcp/Cargo.toml +++ b/backend/windmill-trigger-gcp/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_trigger_gcp" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-http/Cargo.toml b/backend/windmill-trigger-http/Cargo.toml index d776a34a00..378b07a61e 100644 --- a/backend/windmill-trigger-http/Cargo.toml +++ b/backend/windmill-trigger-http/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_trigger_http" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-kafka/Cargo.toml b/backend/windmill-trigger-kafka/Cargo.toml index 9887dfc04a..f449837031 100644 --- a/backend/windmill-trigger-kafka/Cargo.toml +++ b/backend/windmill-trigger-kafka/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_trigger_kafka" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-mqtt/Cargo.toml b/backend/windmill-trigger-mqtt/Cargo.toml index 305880b176..383e32a693 100644 --- a/backend/windmill-trigger-mqtt/Cargo.toml +++ b/backend/windmill-trigger-mqtt/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_trigger_mqtt" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-nats/Cargo.toml b/backend/windmill-trigger-nats/Cargo.toml index a0830097bb..1e75052eb7 100644 --- a/backend/windmill-trigger-nats/Cargo.toml +++ b/backend/windmill-trigger-nats/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_trigger_nats" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-postgres/Cargo.toml b/backend/windmill-trigger-postgres/Cargo.toml index d932274f8e..9abef142dd 100644 --- a/backend/windmill-trigger-postgres/Cargo.toml +++ b/backend/windmill-trigger-postgres/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_trigger_postgres" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-sqs/Cargo.toml b/backend/windmill-trigger-sqs/Cargo.toml index ac46dc5935..7896f5acd0 100644 --- a/backend/windmill-trigger-sqs/Cargo.toml +++ b/backend/windmill-trigger-sqs/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_trigger_sqs" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-websocket/Cargo.toml b/backend/windmill-trigger-websocket/Cargo.toml index ccf8d2b120..4005985cd3 100644 --- a/backend/windmill-trigger-websocket/Cargo.toml +++ b/backend/windmill-trigger-websocket/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_trigger_websocket" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-trigger-websocket/src/listener.rs b/backend/windmill-trigger-websocket/src/listener.rs index 91bbc4bf23..e28ed8903c 100644 --- a/backend/windmill-trigger-websocket/src/listener.rs +++ b/backend/windmill-trigger-websocket/src/listener.rs @@ -31,6 +31,12 @@ use windmill_trigger::Listener; const MAX_CONNECT_ATTEMPTS: u32 = 5; +/// Unit of the connect backoff: attempt `n` waits `2^n` of it. Tests shrink it to avoid +/// waiting out real seconds; nothing else writes it. +#[doc(hidden)] +pub static CONNECT_RETRY_BASE_DELAY_MS: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(1000); + /// Whether a failed WebSocket connect is worth retrying: network-level IO /// errors and HTTP 5xx/429 handshake responses are typically transient (edge /// proxies like Cloudflare return 502/520 sporadically), while other errors @@ -215,24 +221,27 @@ impl Listener for WebsocketTrigger { && attempt < MAX_CONNECT_ATTEMPTS && is_transient_connect_error(&err) => { - let delay_secs = 1u64 << attempt; + let delay = std::time::Duration::from_millis( + CONNECT_RETRY_BASE_DELAY_MS.load(std::sync::atomic::Ordering::Relaxed) + << attempt, + ); tracing::warn!( - "Transient error connecting to WebSocket for trigger {} (attempt {}/{}), retrying in {}s: {}", + "Transient error connecting to WebSocket for trigger {} (attempt {}/{}), retrying in {:?}: {}", listening_trigger.path, attempt, MAX_CONNECT_ATTEMPTS, - delay_secs, + delay, err ); update_rw_lock( err_message.clone(), Some(format!( - "Connection attempt {}/{} failed ({}), retrying in {}s...", - attempt, MAX_CONNECT_ATTEMPTS, err, delay_secs + "Connection attempt {}/{} failed ({}), retrying in {:?}...", + attempt, MAX_CONNECT_ATTEMPTS, err, delay )), ) .await; - tokio::time::sleep(std::time::Duration::from_secs(delay_secs)).await; + tokio::time::sleep(delay).await; } Err(err) => return Err(to_anyhow(err).into()), } diff --git a/backend/windmill-trigger-websocket/tests/connect_retry.rs b/backend/windmill-trigger-websocket/tests/connect_retry.rs index 2d21512692..f73ca9b953 100644 --- a/backend/windmill-trigger-websocket/tests/connect_retry.rs +++ b/backend/windmill-trigger-websocket/tests/connect_retry.rs @@ -20,7 +20,8 @@ use tokio::{ }; use windmill_trigger::{listener::ListeningTrigger, Listener}; use windmill_trigger_websocket::{ - WebsocketConfig, WebsocketTrigger, ALLOW_PRIVATE_WEBSOCKET_URLS_ENV, + listener::CONNECT_RETRY_BASE_DELAY_MS, WebsocketConfig, WebsocketTrigger, + ALLOW_PRIVATE_WEBSOCKET_URLS_ENV, }; /// Mock server: rejects the first `failures` upgrade requests with @@ -108,6 +109,7 @@ async fn get_consumer_result( #[tokio::test] async fn transient_502s_are_retried_until_the_upgrade_succeeds() { std::env::set_var(ALLOW_PRIVATE_WEBSOCKET_URLS_ENV, "true"); + CONNECT_RETRY_BASE_DELAY_MS.store(1, Ordering::Relaxed); let (addr, attempts) = mock_ws_server(2, "502 Bad Gateway").await; let lt = trigger(format!("ws://{addr}"), true); let err_message = Arc::new(RwLock::new(None)); diff --git a/backend/windmill-trigger/Cargo.toml b/backend/windmill-trigger/Cargo.toml index 8132f8b62a..cfa11084d3 100644 --- a/backend/windmill-trigger/Cargo.toml +++ b/backend/windmill-trigger/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_trigger" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-types/Cargo.toml b/backend/windmill-types/Cargo.toml index 2472d6bf02..84fa209ddd 100644 --- a/backend/windmill-types/Cargo.toml +++ b/backend/windmill-types/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_types" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/windmill-types/src/s3.rs b/backend/windmill-types/src/s3.rs index 3af4b7f99a..e6a219a370 100644 --- a/backend/windmill-types/src/s3.rs +++ b/backend/windmill-types/src/s3.rs @@ -9,6 +9,12 @@ use std::fmt; /// it as the primary one. pub const DEFAULT_STORAGE: &str = "_default_"; +/// The s3-proxy path segment under which a request names the storage's real bucket +/// (`s3_proxy/_wm_bucket_/{storage}/{bucket}/{key}`), for S3 clients that address +/// `s3:///`. Reserved like `DEFAULT_STORAGE`: a secondary storage of that name +/// would be shadowed by the bucket-addressed routes. +pub const BUCKET_ADDRESSED_SEGMENT: &str = "_wm_bucket_"; + #[derive(Debug, Deserialize, Serialize, Clone)] pub struct FilesystemSettings { pub root_path: String, diff --git a/backend/windmill-worker-volumes/Cargo.toml b/backend/windmill-worker-volumes/Cargo.toml index 08b9a554b2..d94764e7cd 100644 --- a/backend/windmill-worker-volumes/Cargo.toml +++ b/backend/windmill-worker-volumes/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_worker_volumes" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] enterprise = [] diff --git a/backend/windmill-worker/Cargo.toml b/backend/windmill-worker/Cargo.toml index 68728a9713..082166419e 100644 --- a/backend/windmill-worker/Cargo.toml +++ b/backend/windmill-worker/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_worker" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-worker/nsjail/install.bun.config.proto b/backend/windmill-worker/nsjail/install.bun.config.proto new file mode 100644 index 0000000000..86fc052102 --- /dev/null +++ b/backend/windmill-worker/nsjail/install.bun.config.proto @@ -0,0 +1,118 @@ +name: "bun install" + +mode: ONCE +hostname: "bun" +log_level: ERROR +time_limit: {TIMEOUT} + +# Bun/JavaScriptCore reserves large virtual ranges up front, and native builds +# size their pools to the host: an address-space cap breaks the install itself. +disable_rl: true + +cwd: "{INSTALL_DIR}" + +clone_newnet: false +clone_newuser: {CLONE_NEWUSER} + +skip_setsid: true +keep_caps: false +keep_env: true +mount_proc: true + +mount { + src: "/bin" + dst: "/bin" + is_bind: true +} + +mount { + src: "/lib" + dst: "/lib" + is_bind: true +} + +mount { + src: "/lib64" + dst: "/lib64" + is_bind: true + mandatory: false +} + +mount { + src: "/usr" + dst: "/usr" + is_bind: true +} + +mount { + src: "/etc" + dst: "/etc" + is_bind: true +} + +# Container runtimes bind exactly these 3 files as separate submounts over +# /etc; nsjail's ro remount of /etc is non-recursive so they stay writable. +# Load-bearing -- do not remove as redundant with the /etc bind above. +mount { + src: "/etc/resolv.conf" + dst: "/etc/resolv.conf" + is_bind: true + mandatory: false +} + +mount { + src: "/etc/hosts" + dst: "/etc/hosts" + is_bind: true + mandatory: false +} + +mount { + src: "/etc/hostname" + dst: "/etc/hostname" + is_bind: true + mandatory: false +} + +mount { + src: "/dev/null" + dst: "/dev/null" + is_bind: true + rw: true +} + +mount { + src: "/dev/urandom" + dst: "/dev/urandom" + is_bind: true +} + +mount { + src: "/dev/random" + dst: "/dev/random" + is_bind: true +} + +{TMP_MOUNT_BLOCK} + +# HOME keeps the worker's path, so the package manager finds the operator's +# ~/.npmrc / ~/.bunfig.toml, but is otherwise a private tmpfs. +{HOME_MOUNT_BLOCK} + +# The install dir (package.json, lockfile, registry config; node_modules is +# written there) and, for bun, the shared bun cache, writable like the other +# install jails' shared caches. A bun install dir inside the cache gets no bind +# of its own: that would be a second mount, and bun can only hardlink from its +# cache within one. +{INSTALL_MOUNTS} + +mount { + src: "{TRACING_PROXY_CA_CERT_PATH}" + dst: "{TRACING_PROXY_CA_CERT_PATH}" + is_bind: true + mandatory: false +} + +{CA_MOUNT} + +#{DEV} diff --git a/backend/windmill-worker/nsjail/probe.config.proto b/backend/windmill-worker/nsjail/probe.config.proto new file mode 100644 index 0000000000..2fdc5abdca --- /dev/null +++ b/backend/windmill-worker/nsjail/probe.config.proto @@ -0,0 +1,47 @@ +name: "nsjail startup probe" + +mode: ONCE +hostname: "probe" +log_level: WARNING +time_limit: 10 + +# Same namespaces and rlimit handling as the job profiles (nsjail's default rlimits, a cgroup +# namespace, the user namespace unless DISABLE_NUSER): a worker whose kernel or runtime refuses +# any of them cannot run jobs either. +clone_newnet: false +clone_newuser: {CLONE_NEWUSER} + +skip_setsid: true +keep_caps: false +mount_proc: true + +mount { + src: "/bin" + dst: "/bin" + is_bind: true +} +mount { + src: "/lib" + dst: "/lib" + is_bind: true +} +mount { + src: "/lib64" + dst: "/lib64" + is_bind: true + mandatory: false +} +mount { + src: "/usr" + dst: "/usr" + is_bind: true +} +mount { + dst: "/tmp" + fstype: "tmpfs" + rw: true +} + +exec_bin { + path: "/bin/true" +} diff --git a/backend/windmill-worker/nsjail/run.bash.config.proto b/backend/windmill-worker/nsjail/run.bash.config.proto index 899f7caa1e..b89d4a5d91 100644 --- a/backend/windmill-worker/nsjail/run.bash.config.proto +++ b/backend/windmill-worker/nsjail/run.bash.config.proto @@ -9,7 +9,7 @@ disable_rl: true cwd: "/tmp" -clone_newnet: false +clone_newnet: {CLONE_NEWNET} clone_newuser: {CLONE_NEWUSER} skip_setsid: true diff --git a/backend/windmill-worker/nsjail/run.bun.config.proto b/backend/windmill-worker/nsjail/run.bun.config.proto index cd1510adc6..98794a74bd 100644 --- a/backend/windmill-worker/nsjail/run.bun.config.proto +++ b/backend/windmill-worker/nsjail/run.bun.config.proto @@ -11,7 +11,7 @@ mount_proc: true cwd: "/tmp/{LANG}" -clone_newnet: false +clone_newnet: {CLONE_NEWNET} clone_newuser: {CLONE_NEWUSER} clone_newcgroup: false diff --git a/backend/windmill-worker/nsjail/run.docker.config.proto b/backend/windmill-worker/nsjail/run.docker.config.proto index a8e327927e..8ba41e947d 100644 --- a/backend/windmill-worker/nsjail/run.docker.config.proto +++ b/backend/windmill-worker/nsjail/run.docker.config.proto @@ -9,7 +9,7 @@ disable_rl: true cwd: {WORKDIR} -clone_newnet: false +clone_newnet: {CLONE_NEWNET} clone_newuser: {CLONE_NEWUSER} skip_setsid: true diff --git a/backend/windmill-worker/nsjail/run.python3.config.proto b/backend/windmill-worker/nsjail/run.python3.config.proto index 269ae1f0f8..6b18f6d7fa 100644 --- a/backend/windmill-worker/nsjail/run.python3.config.proto +++ b/backend/windmill-worker/nsjail/run.python3.config.proto @@ -12,7 +12,7 @@ rlimit_nofile: 10000 cwd: "/tmp" -clone_newnet: false +clone_newnet: {CLONE_NEWNET} clone_newuser: {CLONE_NEWUSER} skip_setsid: true @@ -62,6 +62,8 @@ mount { is_bind: true } +{MODULE_MOUNTS} + mount { src: "{JOB_DIR}/loader.py" dst: "/tmp/loader.py" diff --git a/backend/windmill-worker/nsjail/run.r.config.proto b/backend/windmill-worker/nsjail/run.r.config.proto index a0c4c51cf0..7384a4eb3b 100644 --- a/backend/windmill-worker/nsjail/run.r.config.proto +++ b/backend/windmill-worker/nsjail/run.r.config.proto @@ -8,7 +8,7 @@ disable_rl: true cwd: "/tmp" -clone_newnet: false +clone_newnet: {CLONE_NEWNET} clone_newuser: {CLONE_NEWUSER} skip_setsid: true diff --git a/backend/windmill-worker/src/ai/tools.rs b/backend/windmill-worker/src/ai/tools.rs index 1a478292cb..0bc7bf6777 100644 --- a/backend/windmill-worker/src/ai/tools.rs +++ b/backend/windmill-worker/src/ai/tools.rs @@ -577,6 +577,9 @@ async fn enqueue_windmill_tool( &ctx.job.workspace_id, ctx.preserve_step_tags, job_payload.tag.as_deref(), + windmill_queue::tags::dev_flow_tag_suffix(&ctx.job.workspace_id, &ctx.job.tag, ctx.db) + .await? + .as_deref(), ); if tool_tag.as_deref().is_some_and(tag_reads_flow_expr) { append_logs( diff --git a/backend/windmill-worker/src/bash_executor.rs b/backend/windmill-worker/src/bash_executor.rs index 2da8f8d73f..7ec2f4fd33 100644 --- a/backend/windmill-worker/src/bash_executor.rs +++ b/backend/windmill-worker/src/bash_executor.rs @@ -39,15 +39,16 @@ const NSJAIL_CONFIG_RUN_BASH_CONTENT: &str = include_str!("../nsjail/run.bash.co use crate::handle_child::run_future_with_polling_update_job_poller; use crate::{ + check_no_network_jailed, common::{ build_args_map, build_command_with_isolation, get_reserved_variables, raw_to_string, read_file, read_file_content, resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block, start_child_process, OccupancyMetrics, DEV_CONF_NSJAIL, }, - get_proxy_envs_for_lang, + get_proxy_envs_for_lang, get_run_proxy_envs, handle_child::handle_child, - is_sandboxing_enabled, DISABLE_NUSER, HOME_ENV, NSJAIL_AVAILABLE, NSJAIL_PATH, PATH_ENV, - TRACING_PROXY_CA_CERT_PATH, + is_sandboxing_enabled, nsjail_clone_newnet, DISABLE_NUSER, HOME_ENV, NSJAIL_AVAILABLE, + NSJAIL_PATH, PATH_ENV, TRACING_PROXY_CA_CERT_PATH, }; use windmill_common::client::AuthedClient; use windmill_common::scripts::ScriptLang; @@ -94,6 +95,7 @@ pub async fn handle_bash_job( if let Some(image) = windmill_common::worker::BashAnnotations::sandbox_image(content) { return crate::docker_v2::handle_docker_v2_job( &image, + annotation.no_network, mem_peak, canceled_by, job, @@ -115,6 +117,13 @@ pub async fn handle_bash_job( // `ssh_target` resource instead of on this worker. The OSS build returns a // clear "enterprise feature" error from the stub. if let Some(ssh_path) = windmill_common::worker::BashAnnotations::ssh_target(content) { + if annotation.no_network { + return Err(Error::ExecutionErr( + "Script has the `no_network` annotation, which a remote `#ssh` host cannot \ + honor. Refusing to run it with network." + .to_string(), + )); + } return crate::ssh_executor_oss::handle_ssh_bash_job( &ssh_path, mem_peak, @@ -139,6 +148,19 @@ pub async fn handle_bash_job( )); } + // Init/periodic scripts need full system access without isolation + let is_regular_job = job + .runnable_path + .as_ref() + .map(|x| { + !x.starts_with(INIT_SCRIPT_PATH_PREFIX) && !x.starts_with(PERIODIC_SCRIPT_PATH_PREFIX) + }) + .unwrap_or(true); + + // Use nsjail if globally enabled OR if script has #sandbox annotation + let nsjail = (is_sandboxing_enabled() || annotation.sandbox) && is_regular_job; + check_no_network_jailed(annotation.no_network, nsjail)?; + let mut logs1 = "\n\n--- BASH CODE EXECUTION ---\n".to_string(); if annotation.docker { logs1.push_str("docker mode\n"); @@ -146,6 +168,9 @@ pub async fn handle_bash_job( if annotation.sandbox { logs1.push_str("sandbox mode (nsjail)\n"); } + if annotation.no_network { + logs1.push_str("no network\n"); + } append_logs(&job.id, &job.workspace_id, logs1, &conn).await; write_file(job_dir, "main.sh", &format!("set -e\n{content}"))?; @@ -204,6 +229,7 @@ exit $exit_status let mut reserved_variables = get_reserved_variables(job, &client.token, conn, parent_runnable_path).await?; reserved_variables.insert("RUST_LOG".to_string(), "info".to_string()); + crate::strip_no_network_token(&mut reserved_variables, annotation.no_network); let args = build_args_map(job, client, conn).await?.map(Json); let job_args = if args.is_some() { @@ -237,18 +263,6 @@ exit $exit_status vec![] }; - // Check if this is a regular job (not init or periodic script) - // Init/periodic scripts need full system access without isolation - let is_regular_job = job - .runnable_path - .as_ref() - .map(|x| { - !x.starts_with(INIT_SCRIPT_PATH_PREFIX) && !x.starts_with(PERIODIC_SCRIPT_PATH_PREFIX) - }) - .unwrap_or(true); - - // Use nsjail if globally enabled OR if script has #sandbox annotation - let nsjail = (is_sandboxing_enabled() || annotation.sandbox) && is_regular_job; let child = if nsjail { let nsjail_timeout = resolve_nsjail_timeout(conn, &job.workspace_id, job.id, job.timeout).await; @@ -258,6 +272,7 @@ exit $exit_status &NSJAIL_CONFIG_RUN_BASH_CONTENT .replace("{JOB_DIR}", job_dir) .replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string()) + .replace("{CLONE_NEWNET}", nsjail_clone_newnet(annotation.no_network)) .replace("{SHARED_MOUNT}", shared_mount) .replace("{TRACING_PROXY_CA_CERT_PATH}", &*TRACING_PROXY_CA_CERT_PATH) .replace("#{DEV}", DEV_CONF_NSJAIL) @@ -281,12 +296,13 @@ exit $exit_status .env_clear() .envs(reserved_variables) .envs( - get_proxy_envs_for_lang( + get_run_proxy_envs( &ScriptLang::Bash, job.kind, &job.id, &job.workspace_id, conn, + annotation.no_network, ) .await?, ) diff --git a/backend/windmill-worker/src/bun_executor.rs b/backend/windmill-worker/src/bun_executor.rs index 201219b674..6da968e422 100644 --- a/backend/windmill-worker/src/bun_executor.rs +++ b/backend/windmill-worker/src/bun_executor.rs @@ -18,18 +18,21 @@ use windmill_parser_ts::{remove_pinned_import_specifiers, remove_pinned_imports} use windmill_queue::{append_logs, CanceledBy, MiniPulledJob, PrecomputedAgentInfo}; use crate::{ + check_no_network_jailed, common::{ build_command_with_isolation, create_args_and_out_file, get_reserved_variables, parse_npm_config, read_file, read_file_content, read_result, resolve_nsjail_timeout, - resolve_nsjail_tmp_mount_block, script_envars, start_child_process, write_file_binary, - MaybeLock, OccupancyMetrics, StreamNotifier, DEV_CONF_NSJAIL, + resolve_nsjail_tmp_mount_block, resolve_nsjail_tmpfs_size_bytes, script_envars, + start_child_process, write_file_binary, MaybeLock, OccupancyMetrics, StreamNotifier, + DEV_CONF_NSJAIL, }, - get_proxy_envs_for_lang, + get_proxy_envs_for_lang, get_run_proxy_envs, handle_child::handle_child, - is_sandboxing_enabled, read_ee_registry_with_workspace_override, BUNFIG_INSTALL_SCOPES, - BUN_BUNDLE_CACHE_DIR, BUN_CACHE_DIR, BUN_INSTALL_MIN_RELEASE_AGE, BUN_NO_CACHE, BUN_PATH, - DISABLE_NUSER, HOME_ENV, NODE_BIN_PATH, NODE_PATH, NPMRC, NPM_CONFIG_REGISTRY, NPM_PATH, - NSJAIL_AVAILABLE, NSJAIL_PATH, PATH_ENV, PROXY_ENVS, TRACING_PROXY_CA_CERT_PATH, TZ_ENV, + is_sandboxing_enabled, nsjail_clone_newnet, read_ee_registry_with_workspace_override, + BUNFIG_INSTALL_SCOPES, BUN_BUNDLE_CACHE_DIR, BUN_CACHE_DIR, BUN_INSTALL_MIN_RELEASE_AGE, + BUN_NO_CACHE, BUN_PATH, DISABLE_BUN_INSTALL_SANDBOX, DISABLE_NUSER, HOME_ENV, NODE_BIN_PATH, + NODE_PATH, NPMRC, NPM_CONFIG_REGISTRY, NPM_PATH, NSJAIL_AVAILABLE, NSJAIL_PATH, PATH_ENV, + PROXY_ENVS, TRACING_PROXY_CA_CERT_PATH, TZ_ENV, }; use windmill_common::{ cache, @@ -38,7 +41,7 @@ use windmill_common::{ min_version::MIN_VERSION_SUPPORTS_BUN_LOCKFILE_V2, scripts::{id_to_codebase_info, CodebaseInfo, ScriptHash, ScriptLang}, utils::WarnAfterExt, - workspace_dependencies::WorkspaceDependenciesPrefetched, + workspace_dependencies::{clean_lock_from_annotations, WorkspaceDependenciesPrefetched}, }; use windmill_types::s3::BundleFormat; @@ -73,6 +76,7 @@ pub const RELATIVE_BUN_LOADER: &str = include_str!("../loader.bun.windows.js"); pub const RELATIVE_BUN_BUILDER: &str = include_str!("../loader_builder.bun.js"); const NSJAIL_CONFIG_RUN_BUN_CONTENT: &str = include_str!("../nsjail/run.bun.config.proto"); +const NSJAIL_CONFIG_INSTALL_BUN_CONTENT: &str = include_str!("../nsjail/install.bun.config.proto"); pub const BUN_LOCK_SPLIT: &str = "\n//bun.lock\n"; pub const BUN_LOCKB_SPLIT: &str = "\n//bun.lockb\n"; @@ -731,6 +735,474 @@ registry = {} Ok(()) } +/// An nsjail bind mount of `path` onto itself, skipped when the host path is missing. +/// Empty for a path that is not absolute or that the proto string cannot carry verbatim. +fn optional_bind_mount(path: &str, rw: bool) -> String { + if !path.starts_with('/') || path.contains(['"', '\\', '\n', '\r']) { + return String::new(); + } + format!( + "mount {{\n src: \"{path}\"\n dst: \"{path}\"\n is_bind: true\n rw: {rw}\n mandatory: false\n}}\n" + ) +} + +/// node-gyp's header cache under HOME. Kept across jailed installs like the package +/// caches: without it every native build downloads the headers again, which a worker +/// with no internet access cannot. +const NODE_GYP_CACHE: &str = ".cache/node-gyp"; + +/// The install jail's HOME: a private tmpfs at the worker's HOME path, with the +/// package manager's user config read-only and the caches kept there writable (npm's +/// `~/.npm` in npm mode, node-gyp's headers in both). +fn install_home_mount_block(home: &str, npm_mode: bool, tmpfs_size_bytes: &str) -> String { + let home = home.trim_end_matches('/'); + let mut block = String::new(); + // A HOME under /tmp is already private: the jail's /tmp is. + if home.starts_with('/') + && home != "/tmp" + && !home.starts_with("/tmp/") + && !home.contains(['"', '\\', '\n', '\r']) + { + block.push_str(&format!( + "mount {{\n dst: \"{home}\"\n fstype: \"tmpfs\"\n rw: true\n options: \"size={tmpfs_size_bytes}\"\n}}\n" + )); + } + block.push_str(&optional_bind_mount(&format!("{home}/.npmrc"), false)); + block.push_str(&optional_bind_mount(&format!("{home}/.bunfig.toml"), false)); + block.push_str(&optional_bind_mount( + &format!("{home}/{NODE_GYP_CACHE}"), + true, + )); + if npm_mode { + block.push_str(&optional_bind_mount(&format!("{home}/.npm"), true)); + } + block +} + +/// An `.npmrc` value as npm reads it: `${VAR}` from the install env, and a leading `~/` +/// as HOME. Without it, a `cafile=~/…` or `${HOME}/…` is never mounted and the jail's +/// private HOME hides the certificate. +fn expand_npmrc_value(value: &str, home: &str, envs: &HashMap) -> String { + let mut out = String::new(); + let mut rest = value; + while let Some(start) = rest.find("${") { + let Some(len) = rest[start..].find('}') else { + break; + }; + out.push_str(&rest[..start]); + let name = rest[start + 2..start + len].trim_end_matches('?'); + out.push_str(envs.get(name).map(String::as_str).unwrap_or_default()); + rest = &rest[start + len + 1..]; + } + out.push_str(rest); + match out.strip_prefix("~/") { + Some(p) => format!("{}/{p}", home.trim_end_matches('/')), + None => out, + } +} + +/// TLS files the install is pointed at (CA bundles, registry client certificates) live +/// outside the jail's mounts: bind them in, read-only, so private registries keep working. +fn install_ca_mounts(job_dir: &str, home: &str, envs: &HashMap) -> String { + const CA_ENVS: [&str; 4] = [ + "NODE_EXTRA_CA_CERTS", + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "NPM_CONFIG_CAFILE", + ]; + // Also registry-scoped (`//host/:certfile=`), hence the match on the last segment. + const TLS_FILE_KEYS: [&str; 3] = ["cafile", "certfile", "keyfile"]; + let from_env = crate::worker::WHITELIST_ENVS + .iter() + .filter(|(k, _)| CA_ENVS.iter().any(|c| c.eq_ignore_ascii_case(k))) + .map(|(_, v)| v.trim().to_string()); + // `.npmrc` lines and bunfig's `[install] cafile = "…"` share the `key = value` shape. + let from_config = [ + format!("{job_dir}/{BUN_NPMRC_FILE}"), + format!("{home}/.npmrc"), + format!("{job_dir}/{BUN_CONFIG_FILE}"), + format!("{home}/.bunfig.toml"), + ] + .into_iter() + .filter_map(|f| fs::read_to_string(f).ok()) + .flat_map(|content| { + content + .lines() + .filter_map(|l| { + let (k, v) = l.split_once('=')?; + let key = k.trim().rsplit(':').next()?; + TLS_FILE_KEYS + .iter() + .any(|t| t.eq_ignore_ascii_case(key)) + .then(|| expand_npmrc_value(v.trim().trim_matches(['"', '\'']), home, envs)) + }) + .collect::>() + }); + from_env + .chain(from_config) + .filter(|p| !p.is_empty()) + .unique() + .map(|p| optional_bind_mount(&p, false)) + .collect() +} + +/// The files `bun install` reads from, and writes to, the directory it installs in. +#[cfg(unix)] +const BUN_INSTALL_INPUTS: [&str; 3] = ["package.json", "bun.lock", "bun.lockb"]; +const BUN_INSTALL_OUTPUTS: [&str; 3] = ["node_modules", "bun.lock", "bun.lockb"]; +/// What the worker reads or mounts from the job dir after an install that ran in it. +const BUN_JOB_DIR_OUTPUTS: [&str; 5] = [ + "node_modules", + "package.json", + "bun.lock", + "bun.lockb", + "package-lock.json", +]; + +/// Whether an install left `name` at `path`, refusing anything but a real directory +/// (node_modules) or regular file there: the install jail could write it, and the worker +/// follows what it then reads, renames or mounts. +fn check_install_output(path: &str, name: &str) -> Result { + let expect_dir = name == "node_modules"; + match fs::symlink_metadata(path) { + Ok(m) if (expect_dir && m.is_dir()) || (!expect_dir && m.is_file()) => Ok(true), + Ok(_) => Err(error::Error::ExecutionErr(format!( + "dependency install left an unexpected {name}: expected a regular {}", + if expect_dir { "directory" } else { "file" } + ))), + Err(_) => Ok(false), + } +} + +/// Registry configuration bun reads from the install dir. It can hold an auth token, so +/// a staged install gets it bind-mounted read-only from the job dir instead of a copy in +/// the cache, which every later install jail mounts. +const BUN_REGISTRY_FILES: [&str; 2] = [BUN_CONFIG_FILE, BUN_NPMRC_FILE]; + +/// Open a directory without following a symlink at `path`. +#[cfg(unix)] +fn open_dir_nofollow(path: &str) -> std::io::Result { + use std::os::unix::fs::OpenOptionsExt; + fs::OpenOptions::new() + .read(true) + .custom_flags(nix::libc::O_DIRECTORY | nix::libc::O_NOFOLLOW) + .open(path) +} + +/// Delete entry `name` of the directory open as `dir`, off the async worker thread: a +/// staging dir can hold a whole node_modules. A symlink there is removed, never followed. +#[cfg(unix)] +fn remove_entry_detached(dir: Arc, name: String) { + use std::os::fd::AsRawFd; + let remove = move || { + let path = format!("/proc/self/fd/{}/{name}", dir.as_raw_fd()); + let _ = match fs::symlink_metadata(&path) { + Ok(m) if m.is_dir() => fs::remove_dir_all(&path), + Ok(_) => fs::remove_file(&path), + Err(e) => Err(e), + }; + }; + match tokio::runtime::Handle::try_current() { + Ok(rt) => { + rt.spawn_blocking(remove); + } + Err(_) => remove(), + } +} + +/// A directory for one jailed bun install inside the bun cache, removed when dropped. +/// +/// The jail binds the job dir and the cache as two mounts, and link(2) fails across +/// mounts, so bun would copy every file out of the cache instead of hardlinking it. +/// Installing here and renaming node_modules into the job dir keeps the hardlinks. +/// +/// Every install jail can write the cache, so any path through it may since have become a +/// symlink. The worker reaches this dir only through descriptors opened without following +/// links before the jail runs ([`Self::entry`]); `path` is for the jail config alone. +struct BunStagingDir { + #[cfg(unix)] + root: Arc, + #[cfg(unix)] + dir: fs::File, + #[cfg(unix)] + name: String, + path: String, +} + +impl BunStagingDir { + /// Entry `f` of the staging dir, resolved through its descriptor. + fn entry(&self, f: &str) -> String { + #[cfg(unix)] + { + use std::os::fd::AsRawFd; + format!("/proc/self/fd/{}/{f}", self.dir.as_raw_fd()) + } + #[cfg(not(unix))] + format!("{}/{f}", self.path) + } +} + +#[cfg(unix)] +impl Drop for BunStagingDir { + fn drop(&mut self) { + remove_entry_detached(self.root.clone(), std::mem::take(&mut self.name)); + } +} + +/// How long a staging dir may outlive its install before the next one deletes it: a +/// worker killed mid-install leaves it behind. Well past the longest install. +#[cfg(unix)] +const BUN_STAGING_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(6 * 60 * 60); + +/// Whether a bun install needs nothing of the job dir beyond [`BUN_INSTALL_INPUTS`]: no +/// dependency by path, no workspaces or patches, and no root lifecycle script, which bun +/// runs next to the manifest and which may read the job's other files. +#[cfg(any(unix, test))] +fn bun_install_can_stage(package_json: &str, lock: Option<&str>) -> bool { + const DEP_SECTIONS: [&str; 6] = [ + "dependencies", + "devDependencies", + "optionalDependencies", + "peerDependencies", + "overrides", + "resolutions", + ]; + const ROOT_SCRIPTS: [&str; 6] = [ + "preinstall", + "install", + "postinstall", + "preprepare", + "prepare", + "postprepare", + ]; + const LOCAL_SPECS: [&str; 8] = [ + "file:", + "link:", + "workspace:", + "portal:", + "./", + "../", + "/", + "~/", + ]; + fn has_local_spec(v: &serde_json::Value) -> bool { + match v { + serde_json::Value::String(s) => LOCAL_SPECS.iter().any(|p| s.trim().starts_with(p)), + serde_json::Value::Object(m) => m.values().any(has_local_spec), + _ => false, + } + } + let Ok(serde_json::Value::Object(pkg)) = serde_json::from_str(package_json) else { + return false; + }; + let root_script = pkg + .get("scripts") + .and_then(|s| s.as_object()) + .is_some_and(|s| ROOT_SCRIPTS.iter().any(|k| s.contains_key(*k))); + if root_script + || pkg.contains_key("workspaces") + || pkg.contains_key("patchedDependencies") + || DEP_SECTIONS + .iter() + .any(|k| pkg.get(*k).is_some_and(has_local_spec)) + { + return false; + } + // Every text lockfile has a root `"workspaces"` entry, so only these mark local + // packages: as a spec (`"file:x"`) or in a resolution (`"x@file:x"`). + const LOCK_LOCAL_PROTOCOLS: [&str; 4] = ["file:", "link:", "workspace:", "portal:"]; + !lock.is_some_and(|l| { + l.contains("\"patchedDependencies\"") + || LOCK_LOCAL_PROTOCOLS + .iter() + .any(|p| l.contains(&format!("\"{p}")) || l.contains(&format!("@{p}"))) + }) +} + +/// None when node_modules could not be renamed from the cache into the job dir (another +/// filesystem, or another mount of the same one): moving it back would be a copy, which +/// is what installing in the job dir costs anyway. Also None when +/// [`bun_install_can_stage`] says the install needs the job dir. +fn bun_staging_dir(cache_dir: &str, job_dir: &str) -> Option { + #[cfg(unix)] + { + use std::os::fd::AsRawFd; + let package_json = fs::read_to_string(format!("{job_dir}/package.json")).ok()?; + let lock = fs::read_to_string(format!("{job_dir}/bun.lock")).ok(); + if !bun_install_can_stage(&package_json, lock.as_deref()) { + return None; + } + // `cache_dir` is the jail's mount point, which no jail can replace; what is under + // it can be anything. + let root_path = format!("{cache_dir}/.wm-staging"); + if fs::symlink_metadata(&root_path).is_ok_and(|m| !m.is_dir()) { + fs::remove_file(&root_path).ok()?; + } + let _ = fs::create_dir(&root_path); + let root = Arc::new(open_dir_nofollow(&root_path).ok()?); + let root_fd = format!("/proc/self/fd/{}", root.as_raw_fd()); + for e in fs::read_dir(&root_fd).ok()?.flatten() { + let stale = e + .metadata() + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.elapsed().ok()) + .is_some_and(|age| age > BUN_STAGING_MAX_AGE); + if stale { + remove_entry_detached(root.clone(), e.file_name().to_string_lossy().into_owned()); + } + } + let name = Uuid::new_v4().to_string(); + fs::create_dir(format!("{root_fd}/{name}")).ok()?; + let dir = open_dir_nofollow(&format!("{root_fd}/{name}")).ok()?; + let path = format!("{root_path}/{name}"); + let staging = BunStagingDir { root, dir, name, path }; + // A jail sharing the cache can list the new dir and plant a symlink in it before + // the worker writes there: every file is created new, never opened as found. + let create_new = |path: &str| { + fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + }; + // The move back is a rename, which is the only test that holds: two mounts of + // one filesystem share st_dev and still refuse it. + let probe = staging.entry(".rename-probe"); + let probe_dst = format!("{job_dir}/.wm-staging-probe-{}", Uuid::new_v4()); + create_new(&probe).ok()?; + let renamed = fs::rename(&probe, &probe_dst).is_ok(); + let _ = fs::remove_file(&probe_dst); + if !renamed { + return None; + } + for f in BUN_INSTALL_INPUTS { + let src = format!("{job_dir}/{f}"); + if fs::symlink_metadata(&src).is_ok_and(|m| m.is_file()) { + let mut out = create_new(&staging.entry(f)).ok()?; + std::io::copy(&mut fs::File::open(&src).ok()?, &mut out).ok()?; + } + } + Some(staging) + } + #[cfg(not(unix))] + { + let _ = (cache_dir, job_dir); + None + } +} + +/// A fetch npm 12 refuses by default but npm 11 made. Windmill still allows it, for now, when +/// the install's config does not set the key either way. +#[derive(Clone, Copy)] +enum NpmFetchFallback { + Git, + Remote, +} + +impl NpmFetchFallback { + fn key(self) -> &'static str { + match self { + Self::Git => "allow-git", + Self::Remote => "allow-remote", + } + } + + fn error_code(self) -> &'static str { + match self { + Self::Git => "EALLOWGIT", + Self::Remote => "EALLOWREMOTE", + } + } + + fn what(self) -> &'static str { + match self { + Self::Git => "git dependencies", + Self::Remote => "dependency tarballs hosted outside the configured registry", + } + } +} + +/// The job-dir folder npm writes its debug log to (`--logs-dir`). The fallback reads a refusal +/// from there, so the install's output keeps streaming to the job log instead of being held. +const NPM_LOGS_DIR: &str = ".wm-npm-logs"; +const NPM_LOG_READ_LIMIT: u64 = 16 * 1024 * 1024; +const NPM_REFUSED_SPECS_SHOWN: usize = 20; + +/// The fetch a failed `npm install` was refused, read from the debug log npm wrote to +/// `logs_dir`. Called once the install has exited, so no jailed process can still swap these +/// paths; a symlink is never followed. +fn npm_refused_fetch(logs_dir: &str) -> Option<(NpmFetchFallback, Vec)> { + use std::io::{BufRead, Read}; + if !fs::symlink_metadata(logs_dir).ok()?.is_dir() { + return None; + } + let log = fs::read_dir(logs_dir) + .ok()? + .filter_map(|e| e.ok()) + .filter(|e| e.file_type().is_ok_and(|t| t.is_file())) + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "log")) + .max()?; + let log = fs::File::open(log).ok()?.take(NPM_LOG_READ_LIMIT); + parse_npm_refused_fetch(std::io::BufReader::new(log).lines().map_while(|l| l.ok())) +} + +/// npm debug log lines read ` error `. +fn parse_npm_refused_fetch( + lines: impl Iterator, +) -> Option<(NpmFetchFallback, Vec)> { + let mut fallback = None; + let mut refused = vec![]; + for line in lines { + let Some(msg) = line + .split_once(' ') + .and_then(|(_, m)| m.strip_prefix("error ")) + else { + continue; + }; + if let Some(code) = msg.strip_prefix("code ") { + fallback = fallback.or([NpmFetchFallback::Git, NpmFetchFallback::Remote] + .into_iter() + .find(|f| f.error_code() == code.trim())); + } else if let Some(spec) = msg.strip_prefix("Refusing to fetch ") { + if refused.len() < NPM_REFUSED_SPECS_SHOWN { + refused.push(spec.trim().to_string()); + } + } + } + fallback.map(|f| (f, refused)) +} + +/// Whether npm config sets `key` explicitly, from any source npm reads (global, user, project, +/// env, including files redirected by `npm_config_userconfig` / `globalconfig`): `npm config +/// ls` lists only those. A check that fails counts as set, so it never relaxes the policy. +async fn npm_config_sets(key: &str, job_dir: &str, envs: &HashMap) -> bool { + let output = Command::new(&*NPM_PATH) + .current_dir(job_dir) + .env_clear() + .envs(envs) + // The config can set `json` or `long`: JSON output hides an explicit value from + // `npm_config_ls_sets`, and `long` also lists npm's defaults. + .args(["config", "ls", "--json=false", "--long=false"]) + .stdin(Stdio::null()) + .kill_on_drop(true) + .output(); + match tokio::time::timeout(std::time::Duration::from_secs(30), output).await { + Ok(Ok(o)) if o.status.success() => { + npm_config_ls_sets(&String::from_utf8_lossy(&o.stdout), key) + } + _ => true, + } +} + +/// An overridden value is listed commented out (`; key = "v" ; overridden by …`): still set. +fn npm_config_ls_sets(config_ls: &str, key: &str) -> bool { + let prefix = format!("{key} = "); + config_ls + .lines() + .any(|l| l.trim_start_matches("; ").starts_with(&prefix)) +} + pub async fn install_bun_lockfile( mem_peak: &mut i32, canceled_by: &mut Option, @@ -744,9 +1216,34 @@ pub async fn install_bun_lockfile( occupancy_metrics: &mut Option<&mut OccupancyMetrics>, quiet: bool, ) -> Result<()> { - let mut child_cmd = Command::new(if npm_mode { &*NPM_PATH } else { &*BUN_PATH }); - - let mut args = vec!["install", "--save-text-lockfile"]; + let package_manager = if npm_mode { &*NPM_PATH } else { &*BUN_PATH }; + // The install runs the lifecycle scripts of dependencies (npm >= 12: those its allowScripts + // policy covers; bun: its default trusted list and `trustedDependencies`), so when + // sandboxing is on it is confined under nsjail like the run step. The env is the same + // either way. + let sandboxed = is_sandboxing_enabled() && !*DISABLE_BUN_INSTALL_SANDBOX; + if is_sandboxing_enabled() && *DISABLE_BUN_INSTALL_SANDBOX { + static WARNED: std::sync::Once = std::sync::Once::new(); + WARNED.call_once(|| { + tracing::warn!( + "DISABLE_BUN_INSTALL_SANDBOX is set: Bun and npm dependency installs run \ + outside nsjail, with their lifecycle scripts unconfined" + ) + }); + } + let home = common_bun_proc_envs + .get("HOME") + .cloned() + .unwrap_or_else(|| HOME_ENV.clone()); + let npm_logs_dir = format!("{job_dir}/{NPM_LOGS_DIR}"); + let npm_logs_dir_flag = format!("--logs-dir={npm_logs_dir}"); + let mut args = vec!["install"]; + // A bun flag: npm 12 rejects unknown cli flags instead of warning. + if !npm_mode { + args.push("--save-text-lockfile"); + } else { + args.push(&npm_logs_dir_flag); + } let no_cache = !npm_mode && *BUN_NO_CACHE; @@ -754,19 +1251,7 @@ pub async fn install_bun_lockfile( args.push("--no-cache"); } - child_cmd - .current_dir(job_dir) - .env_clear() - .envs(PROXY_ENVS.clone()) - .envs(common_bun_proc_envs) - .envs(&*crate::worker::WHITELIST_ENVS) - .args(args) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - - #[cfg(windows)] - child_cmd.env("SystemRoot", SYSTEM_ROOT.as_str()); - + let mut registry_env = None; let mut npm_logs = if npm_mode { "NPM mode\n".to_string() } else if no_cache { @@ -828,7 +1313,7 @@ pub async fn install_bun_lockfile( } )); - child_cmd.env("NPM_CONFIG_REGISTRY", custom_registry); + registry_env = Some(custom_registry.to_string()); write_file(job_dir, ".npmrc", content)?; true } else { @@ -849,47 +1334,221 @@ pub async fn install_bun_lockfile( gen_bunfig(job_dir, job_id, w_id, db).await?; } - let child_process = start_child_process(child_cmd, &*BUN_PATH, false).await?; - if let Some(db) = db { - let mut quiet_buf = String::new(); - let result = handle_child( - job_id, - db, - mem_peak, - canceled_by, - child_process, - false, - worker_name, - w_id, - "bun install", - None, - false, - occupancy_metrics, - if quiet { Some(&mut quiet_buf) } else { None }, - None, - ) - .warn_after_seconds_for(10, "bun install") - .await; - if quiet && result.is_err() { - // On failure, flush suppressed install output so the user can diagnose - append_logs( - job_id, - w_id, - format!("\n--- BUN INSTALL (failed) ---\n{quiet_buf}"), - db, - ) - .await; + let make_cmd = |extra_args: &[String]| { + let mut cmd = if sandboxed { + let mut cmd = Command::new(NSJAIL_PATH.as_str()); + cmd.args(["--config", "install.config.proto", "--", package_manager]); + cmd + } else { + Command::new(package_manager) + }; + cmd.current_dir(job_dir) + .env_clear() + .envs(PROXY_ENVS.clone()) + .envs(&common_bun_proc_envs) + .envs(&*crate::worker::WHITELIST_ENVS); + if let Some(registry) = registry_env.as_ref() { + cmd.env("NPM_CONFIG_REGISTRY", registry); } - result?; + cmd.args(&args) + .args(extra_args) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(windows)] + cmd.env("SystemRoot", SYSTEM_ROOT.as_str()); + cmd + }; + let install_envs: HashMap = make_cmd(&[]) + .as_std() + .get_envs() + .filter_map(|(k, v)| Some((k.to_str()?.to_string(), v?.to_str()?.to_string()))) + .collect(); + + let mut staging = None; + if sandboxed { + // Bind-mounted into the jail, so they must exist before nsjail builds the mount + // tree. + let _ = std::fs::create_dir_all(format!("{home}/{NODE_GYP_CACHE}")); + if npm_mode { + let _ = std::fs::create_dir_all(format!("{home}/.npm")); + } else { + std::fs::create_dir_all(&*BUN_CACHE_DIR)?; + staging = bun_staging_dir(&BUN_CACHE_DIR, job_dir); + } + let install_dir = staging.as_ref().map_or(job_dir, |s| s.path.as_str()); + let bind = |src: &str, dst: &str, rw: bool| { + format!( + "mount {{\n src: \"{src}\"\n dst: \"{dst}\"\n is_bind: true\n rw: {rw}\n}}\n" + ) + }; + // npm never reads the bun cache, and its install scripts get no write to it. + let mut install_mounts = if npm_mode { + String::new() + } else { + bind(&BUN_CACHE_DIR, &BUN_CACHE_DIR, true) + }; + match staging.as_ref() { + // After the cache bind: these land inside it. + Some(s) => { + for f in BUN_REGISTRY_FILES { + let src = format!("{job_dir}/{f}"); + if fs::symlink_metadata(&src).is_ok_and(|m| m.is_file()) { + install_mounts.push_str(&bind(&src, &format!("{}/{f}", s.path), false)); + } + } + } + None => install_mounts.push_str(&bind(job_dir, job_dir, true)), + } + let nsjail_timeout = match db { + Some(conn) => resolve_nsjail_timeout(conn, w_id, *job_id, None).await, + // no job to bound it: the caller waits for the install unbounded too + None => "0".to_string(), + }; + write_file( + job_dir, + "install.config.proto", + &NSJAIL_CONFIG_INSTALL_BUN_CONTENT + .replace("{TIMEOUT}", &nsjail_timeout) + .replace("{INSTALL_MOUNTS}", &install_mounts) + .replace("{INSTALL_DIR}", install_dir) + .replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string()) + .replace( + "{HOME_MOUNT_BLOCK}", + &install_home_mount_block( + &home, + npm_mode, + &resolve_nsjail_tmpfs_size_bytes().await, + ), + ) + .replace("{TRACING_PROXY_CA_CERT_PATH}", &*TRACING_PROXY_CA_CERT_PATH) + .replace( + "{CA_MOUNT}", + &install_ca_mounts(job_dir, &home, &install_envs), + ) + .replace("#{DEV}", DEV_CONF_NSJAIL) + .replace( + "{TMP_MOUNT_BLOCK}", + &resolve_nsjail_tmp_mount_block(job_dir).await, + ), + )?; + } + + let child_executable = if sandboxed { + NSJAIL_PATH.as_str() } else { - let output = Box::into_pin(child_process.wait_with_output()).await?; - if !output.status.success() { - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - return Err(error::Error::ExecutionErr(format!( - "bun install exited with non-zero status: {:?}\nstdout:\n{stdout}\nstderr:\n{stderr}", - output.status - ))); + package_manager.as_str() + }; + let mut fallback_flags: Vec = vec![]; + let result = loop { + if npm_mode { + // Only this attempt's debug log may decide the fallback. + let _ = tokio::fs::remove_dir_all(&npm_logs_dir).await; + } + let child_process = + start_child_process(make_cmd(&fallback_flags), child_executable, false).await?; + let result = if let Some(db) = db { + let mut quiet_buf = String::new(); + let result = handle_child( + job_id, + db, + mem_peak, + canceled_by, + child_process, + // jailed when sandboxing is on, so mem sampling finds the real process + sandboxed, + worker_name, + w_id, + "bun install", + None, + false, + occupancy_metrics, + if quiet { Some(&mut quiet_buf) } else { None }, + None, + ) + .warn_after_seconds_for(10, "bun install") + .await; + if quiet && result.is_err() { + // On failure, flush suppressed install output so the user can diagnose + append_logs( + job_id, + w_id, + format!("\n--- BUN INSTALL (failed) ---\n{quiet_buf}"), + db, + ) + .await; + } + result.map(|_| ()) + } else { + let output = Box::into_pin(child_process.wait_with_output()).await?; + if output.status.success() { + Ok(()) + } else { + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + Err(error::Error::ExecutionErr(format!( + "bun install exited with non-zero status: {:?}\nstdout:\n{stdout}\nstderr:\n{stderr}", + output.status + ))) + } + }; + + if npm_mode && result.is_err() { + if let Some((fallback, refused)) = npm_refused_fetch(&npm_logs_dir) { + let flag = format!("--{}=all", fallback.key()); + if !fallback_flags.contains(&flag) + && !npm_config_sets(fallback.key(), job_dir, &install_envs).await + { + let key = fallback.key(); + let msg = format!( + "\nWARNING: npm refused {}:\n {}\nRetrying with {key}=all, which Windmill \ + sets by default for now. This default will be removed in a future \ + release: to keep fetching them, set `{key}=all` in the npm config (the \ + npmrc instance or workspace setting on Enterprise Edition, or the \ + worker's ~/.npmrc); set `{key}=none` to stop now.\n", + fallback.what(), + refused.join("\n ") + ); + tracing::warn!(%job_id, w_id, "{}", msg.trim()); + if let Some(db) = db { + append_logs(job_id, w_id, msg, db).await; + } + fallback_flags.push(flag); + continue; + } + } + } + break result; + }; + if npm_mode { + let _ = tokio::fs::remove_dir_all(&npm_logs_dir).await; + } + result?; + + if let Some(staging) = staging { + // Leave the job dir as an install in place would have: what bun wrote or kept + // replaces the job dir's copy, what it removed is removed there too. + for f in BUN_INSTALL_OUTPUTS { + let src = staging.entry(f); + let dst = format!("{job_dir}/{f}"); + match fs::symlink_metadata(&dst) { + Ok(m) if m.is_dir() => tokio::fs::remove_dir_all(&dst).await?, + Ok(_) => tokio::fs::remove_file(&dst).await?, + Err(_) => {} + } + if fs::symlink_metadata(&src).is_ok() { + fs::rename(&src, &dst)?; + // Checked once out of the cache, where no other jail can swap it. + if let Err(e) = check_install_output(&dst, f) { + let _ = fs::remove_file(&dst); + return Err(e); + } + } + } + } else if sandboxed { + // The jail could write the job dir: what the worker reads or mounts from it next + // must still be what an install leaves there. + for f in BUN_JOB_DIR_OUTPUTS { + check_install_output(&format!("{job_dir}/{f}"), f)?; } } @@ -1666,6 +2325,36 @@ pub async fn handle_bun_job( .to_string(), )); } + let jailed = is_sandboxing_enabled() || annotation.sandbox; + // Native scripts take their network away inside the isolate instead. + let jail_no_network = annotation.no_network && !annotation.native; + check_no_network_jailed(jail_no_network, jailed)?; + // Unbundled, Bun's run-time loader fetches workspace imports; Node's are bundled on the host. + if jail_no_network + && codebase.is_none() + && !annotation.nodejs + && (annotation.nobundling || *DISABLE_BUNDLING) + { + let script_path = crate::common::use_flow_root_path(job.runnable_path()); + let script_dir = script_path + .rsplit_once('/') + .map(|(dir, _)| dir) + .unwrap_or(""); + let imports = std::iter::once((script_path.clone(), inner_content.as_str())) + .chain(modules.iter().flatten().map(|(key, module)| { + let stem = key.rsplit_once('.').map(|(stem, _)| stem).unwrap_or(key); + (format!("{script_dir}/{stem}"), module.content.as_str()) + })) + .flat_map(|(path, code)| { + windmill_parser_ts::parse_runtime_relative_imports(code, &path).unwrap_or_default() + }); + crate::check_no_network_imports( + imports, + &script_path, + modules.as_ref(), + "Bun without bundling (`//nobundling` or `DISABLE_BUNDLING`)", + )?; + } let (mut has_bundle_cache, cache_logs, local_path, remote_path) = if let (Some(lock), true) = ( maybe_lock.get_lock(), @@ -1792,7 +2481,17 @@ pub async fn handle_bun_job( )); } - write_file(job_dir, "package.json", package_json)?; + if annotation.npm { + // The stored lock leads with `// workspace-dependencies` header lines: bun + // reads package.json leniently, npm refuses it as invalid JSON. + write_file( + job_dir, + "package.json", + &clean_lock_from_annotations(package_json, ScriptLang::Bun), + )?; + } else { + write_file(job_dir, "package.json", package_json)?; + } let bun_lock = if annotation.npm { "" @@ -1916,6 +2615,9 @@ pub async fn handle_bun_job( if annotation.sandbox { init_logs.push_str("sandbox mode (nsjail)\n"); } + if jail_no_network { + init_logs.push_str("no network\n"); + } let write_wrapper_f = async { if !has_bundle_cache && annotation.native { @@ -2232,7 +2934,8 @@ try {{ && !annotation.nobundling && !*DISABLE_BUNDLING && !codebase.is_some() - && (maybe_lock.get_lock().is_some() || annotation.native); + // A `no_network` run step cannot fetch relative imports, so they resolve while bundling. + && (maybe_lock.get_lock().is_some() || annotation.native || jail_no_network); let write_loader_f = async { if build_cache { @@ -2258,7 +2961,13 @@ try {{ build_loader( job_dir, base_internal_url, - &client.token, + // Bun's run step reads this loader (Node's builds on the host), and could hand + // the token out through its result. + if jail_no_network && !annotation.nodejs { + "" + } else { + &client.token + }, &job.workspace_id, job.runnable_path(), if annotation.nodejs { @@ -2274,11 +2983,12 @@ try {{ } }; - let (reserved_variables, _, _) = tokio::try_join!( + let (mut reserved_variables, _, _) = tokio::try_join!( reserved_variables_args_out_f, write_wrapper_f, write_loader_f )?; + crate::strip_no_network_token(&mut reserved_variables, jail_no_network); // For WAC v2, write checkpoint.json before bun runs if is_wac_v2 { @@ -2491,7 +3201,7 @@ try {{ append_logs(&job.id, &job.workspace_id, init_logs, conn).await; //do not cache local dependencies - let child = if is_sandboxing_enabled() || annotation.sandbox { + let child = if jailed { let nsjail_timeout = resolve_nsjail_timeout(conn, &job.workspace_id, job.id, job.timeout).await; @@ -2534,12 +3244,13 @@ try {{ .env_clear() .envs(reserved_variables) .envs( - get_proxy_envs_for_lang( + get_run_proxy_envs( &ScriptLang::Bun, job.kind, &job.id, &job.workspace_id, conn, + jail_no_network, ) .await?, ) @@ -2555,6 +3266,7 @@ try {{ .replace("{LANG}", if annotation.nodejs { "nodejs" } else { "bun" }) .replace("{JOB_DIR}", job_dir) .replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string()) + .replace("{CLONE_NEWNET}", nsjail_clone_newnet(jail_no_network)) .replace("{UIDGIDMAP}", if *DISABLE_NUSER { "" } else { "uidmap {\n inside_id: \"1000\"\n outside_id: \"\"\n count: 1\n}\n\ngidmap {\n inside_id: \"1000\"\n outside_id: \"\"\n count: 1\n}" }) @@ -4460,6 +5172,69 @@ pub async fn start_worker( mod tests { use super::*; + #[test] + fn bun_install_stages_only_self_contained_manifests() { + let lock = r#"{"lockfileVersion": 1, "workspaces": {"": {"dependencies": {"zod": "^4"}}}}"#; + assert!(bun_install_can_stage( + r#"{"dependencies": {"zod": "^4"}}"#, + Some(lock) + )); + for manifest in [ + r#"{"dependencies": {"x": "file:./x"}}"#, + r#"{"dependencies": {"x": "../x"}}"#, + r#"{"overrides": {"y": {"x": "link:x"}}}"#, + r#"{"workspaces": ["packages/*"]}"#, + r#"{"patchedDependencies": {"zod@4.0.0": "patches/zod.patch"}}"#, + r#"{"scripts": {"postinstall": "test -f main.ts"}}"#, + "not json", + ] { + assert!(!bun_install_can_stage(manifest, None), "{manifest}"); + } + let local_lock = r#"{"packages": {"x": ["x@file:x", {}]}}"#; + assert!(!bun_install_can_stage( + r#"{"dependencies": {}}"#, + Some(local_lock) + )); + } + + // Install jails can write the bun cache, so the worker must never follow a path + // through it: neither a staging root nor a staging dir swapped for a symlink may + // lead its cleanup outside the cache. + #[cfg(target_os = "linux")] + #[test] + fn bun_staging_cleanup_does_not_follow_symlinks_out_of_the_cache() { + let tmp = tempfile::tempdir().unwrap(); + let (cache, job, outside) = ( + tmp.path().join("cache"), + tmp.path().join("job"), + tmp.path().join("outside"), + ); + for d in [&cache, &job, &outside.join("victim")] { + fs::create_dir_all(d).unwrap(); + } + fs::write(job.join("package.json"), r#"{"dependencies": {}}"#).unwrap(); + // Old enough for the stale sweep if it were reached through the symlink. + fs::File::open(outside.join("victim")) + .unwrap() + .set_modified(std::time::SystemTime::UNIX_EPOCH) + .unwrap(); + std::os::unix::fs::symlink(&outside, cache.join(".wm-staging")).unwrap(); + + let staging = + bun_staging_dir(cache.to_str().unwrap(), job.to_str().unwrap()).expect("staging dir"); + assert!(outside.join("victim").exists()); + assert!(fs::symlink_metadata(cache.join(".wm-staging")) + .unwrap() + .is_dir()); + + let staged = cache.join(".wm-staging").join(&staging.name); + fs::remove_dir_all(&staged).unwrap(); + std::os::unix::fs::symlink(&outside, &staged).unwrap(); + drop(staging); + assert!(outside.join("victim").exists()); + assert!(fs::symlink_metadata(&staged).is_err()); + } + #[test] fn test_bun_lockfile_version() { assert_eq!(bun_lockfile_version(EMPTY_V1_BUN_LOCK), Some(1)); @@ -4554,6 +5329,37 @@ YmluYXJ5LWNvbnRlbnQ="#; // base64 encoded "binary-content" assert!(!is_binary); } + // Samples are npm 12.2.0 output: a format change there silently turns the fetch fallback + // off, or makes it override an explicit `none`. + #[test] + fn npm_fetch_fallback_reads_npm_output() { + let log = r#"22 verbose exit 1 +23 error code EALLOWGIT +24 error Fetching packages of type "git" have been disabled +25 error Refusing to fetch "wm-git-test@git+file:///work/git/wm-git-test.git" +26 verbose exit 1"#; + let (fallback, refused) = parse_npm_refused_fetch(log.lines().map(str::to_string)) + .expect("EALLOWGIT is a fetch refusal"); + assert_eq!(fallback.key(), "allow-git"); + assert_eq!( + refused, + [r#""wm-git-test@git+file:///work/git/wm-git-test.git""#] + ); + assert!( + parse_npm_refused_fetch(["23 error code EJSONPARSE".to_string()].into_iter()).is_none() + ); + + let config_ls = r#"; "global" config from /usr/etc/npmrc +; allow-git = "none" ; overridden by project +; "project" config from /work/j/.npmrc +allow-remote = "all" +registry = "http://127.0.0.1:4999/" +; npm version = 12.2.0"#; + assert!(npm_config_ls_sets(config_ls, "allow-git")); + assert!(npm_config_ls_sets(config_ls, "allow-remote")); + assert!(!npm_config_ls_sets(config_ls, "allow-scripts")); + } + #[test] fn test_split_lockfile_multiline_package_json() { let lockfile = r#"{ diff --git a/backend/windmill-worker/src/common.rs b/backend/windmill-worker/src/common.rs index 63c5d8d647..c0ae372e38 100644 --- a/backend/windmill-worker/src/common.rs +++ b/backend/windmill-worker/src/common.rs @@ -92,6 +92,16 @@ pub(crate) fn raw_to_string(x: &str) -> String { } } +/// Narrow a JSON integer to the Rust type bound for a SQL argument, erroring the way the +/// database would rather than letting an `as` cast wrap it into a different value. +pub(crate) fn narrow_sql_int(n: N, sql_type: &str) -> anyhow::Result +where + T: TryFrom, + N: std::fmt::Display + Copy, +{ + T::try_from(n).map_err(|_| anyhow!("value \"{n}\" is out of range for type {sql_type}")) +} + pub async fn build_args_map<'a>( job: &'a MiniPulledJob, client: &AuthedClient, @@ -976,12 +986,26 @@ pub fn build_command_with_isolation(program: &str, args: &[&str]) -> Command { } } +/// Under `NSJAIL_GVISOR_COMPAT`, rewrites the config of an nsjail `cmd` for gVisor. A spawn of +/// nsjail that bypasses `start_child_process` must call this itself. +pub fn apply_nsjail_gvisor_compat(cmd: &Command) -> Result<(), Error> { + if *crate::NSJAIL_GVISOR_COMPAT && cmd.as_std().get_program() == crate::NSJAIL_PATH.as_str() { + crate::nsjail_compat::apply(cmd.as_std()).map_err(|e| { + Error::ExecutionErr(format!( + "NSJAIL_GVISOR_COMPAT could not prepare nsjail: {e}" + )) + })?; + } + Ok(()) +} + pub async fn start_child_process( cmd: Command, executable: &str, disable_process_group: bool, ) -> Result, Error> { use process_wrap::tokio::*; + apply_nsjail_gvisor_compat(&cmd)?; let mut cmd = TokioCommandWrap::from(cmd); // On Windows, put the child in its own console process group so a CTRL_BREAK_EVENT @@ -2771,11 +2795,14 @@ mod tests { include_str!("../nsjail/download.ruby.config.proto"), ), ] { - let at = profile - .find("\n{ENVARS}\n") + // Line by line: a Windows checkout gives the profiles CRLF endings. + let lines = profile.lines().collect::>(); + let at = lines + .iter() + .position(|l| *l == "{ENVARS}") .unwrap_or_else(|| panic!("{name}: no {{ENVARS}}")); assert!( - !profile[..at].contains("\nenvar:"), + !lines[..at].iter().any(|l| l.starts_with("envar:")), "{name}: a fixed envar precedes {{ENVARS}}" ); } diff --git a/backend/windmill-worker/src/dbt_executor.rs b/backend/windmill-worker/src/dbt_executor.rs index dbef02bec3..28db2753e1 100644 --- a/backend/windmill-worker/src/dbt_executor.rs +++ b/backend/windmill-worker/src/dbt_executor.rs @@ -4053,6 +4053,7 @@ pub(crate) async fn run_captured( ) -> error::Result { use tokio::io::AsyncReadExt; + crate::common::apply_nsjail_gvisor_compat(&cmd)?; let mut child = cmd .stdout(Stdio::piped()) .stderr(Stdio::piped()) diff --git a/backend/windmill-worker/src/docker_v2.rs b/backend/windmill-worker/src/docker_v2.rs index 3f47ab6efc..1b02129696 100644 --- a/backend/windmill-worker/src/docker_v2.rs +++ b/backend/windmill-worker/src/docker_v2.rs @@ -36,9 +36,9 @@ use crate::{ render_envars, resolve_nsjail_timeout, resolve_nsjail_tmp_mount_block, start_child_process, OccupancyMetrics, DEV_CONF_NSJAIL, }, - get_proxy_envs_for_lang, + get_run_proxy_envs, handle_child::handle_child, - DISABLE_NUSER, NSJAIL_AVAILABLE, NSJAIL_PATH, SANDBOX_IMAGE_CACHE_MAX_MB, + nsjail_clone_newnet, DISABLE_NUSER, NSJAIL_AVAILABLE, NSJAIL_PATH, SANDBOX_IMAGE_CACHE_MAX_MB, SANDBOX_IMAGE_DEFAULT_REGISTRY, SANDBOX_IMAGE_MAX_SIZE_MB, SANDBOX_IMAGE_PULL_POLICY, SANDBOX_REGISTRY_AUTH, }; @@ -642,6 +642,7 @@ async fn generate_rootfs_mounts(rootfs: &str) -> Result { #[tracing::instrument(level = "trace", skip_all)] pub async fn handle_docker_v2_job( image: &str, + no_network: bool, mem_peak: &mut i32, canceled_by: &mut Option, job: &MiniPulledJob, @@ -671,7 +672,10 @@ pub async fn handle_docker_v2_job( append_logs( &job.id, &job.workspace_id, - format!("\n\n--- SANDBOXED CONTAINER (nsjail) ---\nextracting image {image}...\n"), + format!( + "\n\n--- SANDBOXED CONTAINER (nsjail) ---\n{}extracting image {image}...\n", + if no_network { "no network\n" } else { "" } + ), conn, ) .await; @@ -781,6 +785,7 @@ pub async fn handle_docker_v2_job( &NSJAIL_CONFIG_RUN_DOCKER_CONTENT .replace("{TIMEOUT}", &nsjail_timeout) .replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string()) + .replace("{CLONE_NEWNET}", nsjail_clone_newnet(no_network)) // proto_str-quoted: WorkingDir is image-controlled, must not break out // of the `cwd:` string and inject nsjail directives. .replace("{WORKDIR}", &proto_str(working_dir)) @@ -814,13 +819,15 @@ pub async fn handle_docker_v2_job( "BASE_INTERNAL_URL".to_string(), base_internal_url.to_string(), ); + crate::strip_no_network_token(&mut reserved_variables, no_network); - let proxy_envs = get_proxy_envs_for_lang( + let proxy_envs = get_run_proxy_envs( &ScriptLang::Bash, job.kind, &job.id, &job.workspace_id, conn, + no_network, ) .await?; diff --git a/backend/windmill-worker/src/duckdb_runner.rs b/backend/windmill-worker/src/duckdb_runner.rs index 46f5c5cbde..b7c0bc6321 100644 --- a/backend/windmill-worker/src/duckdb_runner.rs +++ b/backend/windmill-worker/src/duckdb_runner.rs @@ -23,8 +23,7 @@ use windmill_common::error::{Error, Result}; use crate::{ common::{build_command_with_isolation, resolve_nsjail_tmp_mount_block, DEV_CONF_NSJAIL}, - is_sandboxing_enabled, is_unshare_enabled, DISABLE_NUSER, HOME_ENV, NSJAIL_AVAILABLE, - NSJAIL_PATH, PATH_ENV, + is_sandboxing_enabled, is_unshare_enabled, DISABLE_NUSER, HOME_ENV, NSJAIL_PATH, PATH_ENV, }; const NSJAIL_CONFIG_RUN_DUCKDB_CONTENT: &str = include_str!("../nsjail/run.duckdb.config.proto"); @@ -42,7 +41,9 @@ pub(crate) enum RunnerMode { /// Decided once per job, so every connection a job opens runs the same way. pub(crate) fn runner_mode() -> RunnerMode { - if cfg!(unix) && is_sandboxing_enabled() && NSJAIL_AVAILABLE.is_some() { + // Not gated on `NSJAIL_AVAILABLE`: a sandboxed worker whose nsjail cannot jail must fail + // the job, as every other jailed executor does, not run it outside the jail. + if cfg!(unix) && is_sandboxing_enabled() { RunnerMode::Jailed } else if is_unshare_enabled() { // `build_command_with_isolation` logs and runs unisolated when `unshare` is missing, @@ -475,6 +476,7 @@ async fn spawn_runner( }); } } + crate::common::apply_nsjail_gvisor_compat(&cmd)?; let mut child = cmd.spawn().map_err(|e| { Error::InternalErr(format!("Could not start the DuckDB runner ({mode:?}): {e}")) })?; diff --git a/backend/windmill-worker/src/lib.rs b/backend/windmill-worker/src/lib.rs index e56334df67..1945d16346 100644 --- a/backend/windmill-worker/src/lib.rs +++ b/backend/windmill-worker/src/lib.rs @@ -62,6 +62,7 @@ pub mod memory_ee; pub mod memory_oss; #[cfg(feature = "mysql")] mod mysql_executor; +mod nsjail_compat; #[cfg(feature = "nu")] mod nu_executor; #[cfg(feature = "oracledb")] diff --git a/backend/windmill-worker/src/mssql_executor.rs b/backend/windmill-worker/src/mssql_executor.rs index 02d0da1164..1d3a323e34 100644 --- a/backend/windmill-worker/src/mssql_executor.rs +++ b/backend/windmill-worker/src/mssql_executor.rs @@ -26,7 +26,7 @@ use windmill_queue::MiniPulledJob; use windmill_queue::{append_logs, CanceledBy}; use crate::common::{ - build_args_values, get_reserved_variables, s3_mode_args_to_worker_data, + build_args_values, get_reserved_variables, narrow_sql_int, s3_mode_args_to_worker_data, s3_stream_and_upload_with_logs, OccupancyMetrics, }; use crate::handle_child::run_future_with_polling_update_job_poller; @@ -398,13 +398,13 @@ fn json_value_to_sql<'a>( query.bind(b.to_owned()); } Value::Number(n) if n.is_u64() && arg_t == "tinyint" => { - query.bind(n.as_u64().unwrap().to_owned() as u8) + query.bind(narrow_sql_int::(n.as_u64().unwrap(), "tinyint")?) } Value::Number(n) if n.is_i64() && arg_t == "smallint" => { - query.bind(n.as_i64().unwrap().to_owned() as i16) + query.bind(narrow_sql_int::(n.as_i64().unwrap(), "smallint")?) } Value::Number(n) if n.is_i64() && arg_t == "int" => { - query.bind(n.as_i64().unwrap().to_owned() as i32) + query.bind(narrow_sql_int::(n.as_i64().unwrap(), "int")?) } Value::Number(n) if n.is_i64() && arg_t == "bigint" => { query.bind(n.as_i64().unwrap().to_owned() as i64) diff --git a/backend/windmill-worker/src/nsjail_compat.rs b/backend/windmill-worker/src/nsjail_compat.rs new file mode 100644 index 0000000000..3069dcee52 --- /dev/null +++ b/backend/windmill-worker/src/nsjail_compat.rs @@ -0,0 +1,49 @@ +//! `NSJAIL_GVISOR_COMPAT=true`: run nsjail inside gVisor (runsc). Each config is rewritten +//! right before nsjail starts, with `gvisor_compat: true` (an option of the nsjail the images +//! build, from `docker/nsjail-patches/`) and no cgroup namespace, which gVisor refuses. + +use std::ffi::OsStr; +use std::io; +use std::path::PathBuf; +use std::process::Command; + +pub(crate) fn compat_config(config: &str) -> String { + let mut out = config + .lines() + .filter(|l| { + let l = l.trim_start(); + !l.starts_with("clone_newcgroup") && !l.starts_with("gvisor_compat") + }) + .collect::>() + .join("\n"); + out.push_str("\nclone_newcgroup: false\ngvisor_compat: true\n"); + out +} + +/// Rewrites the config `cmd` (an nsjail command line) passes with `--config`. +pub(crate) fn apply(cmd: &Command) -> io::Result<()> { + let args = cmd.get_args().collect::>(); + let Some(config) = args.windows(2).find(|w| w[0] == "--config").map(|w| w[1]) else { + return Ok(()); + }; + let path = match cmd.get_current_dir() { + Some(dir) => dir.join(config), + None => PathBuf::from(config), + }; + let rewritten = compat_config(&std::fs::read_to_string(&path)?); + std::fs::write(&path, rewritten) +} + +#[cfg(test)] +mod tests { + // nsjail rejects a config that sets a scalar field twice, which would fail every jailed job. + #[test] + fn compat_config_sets_each_field_once() { + let bun = include_str!("../nsjail/run.bun.config.proto"); + assert!(bun.contains("clone_newcgroup: false")); + let twice = super::compat_config(&super::compat_config(bun)); + assert_eq!(twice.matches("clone_newcgroup").count(), 1); + assert_eq!(twice.matches("gvisor_compat").count(), 1); + assert!(twice.ends_with("\nclone_newcgroup: false\ngvisor_compat: true\n")); + } +} diff --git a/backend/windmill-worker/src/pg_executor.rs b/backend/windmill-worker/src/pg_executor.rs index 12a3665c27..f70e3dd0ca 100644 --- a/backend/windmill-worker/src/pg_executor.rs +++ b/backend/windmill-worker/src/pg_executor.rs @@ -38,7 +38,7 @@ use windmill_queue::{CanceledBy, MiniPulledJob}; use crate::agent_workers::get_datatable_resource_from_agent_http; use crate::common::{ - build_args_values, get_reserved_variables, s3_mode_args_to_worker_data, + build_args_values, get_reserved_variables, narrow_sql_int, s3_mode_args_to_worker_data, s3_stream_and_upload_with_logs, sizeof_val, OccupancyMetrics, S3ModeWorkerData, }; use crate::handle_child::run_future_with_polling_update_job_poller; @@ -1768,23 +1768,30 @@ fn parse_datetime_utc(s: &str) -> Result, chrono::ParseErr fn map_as_single_type( vec: Option<&Vec>, f: impl Fn(&Value) -> Option, +) -> anyhow::Result>>> { + try_map_as_single_type(vec, |v| Ok(f(v))) +} + +/// Like `map_as_single_type`, but `f` can reject an element of the right type +/// (e.g. an out-of-range integer) with its own error. +fn try_map_as_single_type( + vec: Option<&Vec>, + f: impl Fn(&Value) -> anyhow::Result>, ) -> anyhow::Result>>> { if let Some(vec) = vec { - Ok(Some( - vec.into_iter() - .map(|v| { - // first option is if the value is of the right type (if none, will stop the collection and throw error) - // second option is if the value is null - // allow nulls in arrays - if matches!(v, Value::Null) { - Some(None) - } else { - f(v).map(Some) - } - }) - .collect::>>>() - .ok_or_else(|| anyhow::anyhow!("Mixed types in array"))?, - )) + let mut out = Vec::with_capacity(vec.len()); + for v in vec { + // allow nulls in arrays + if matches!(v, Value::Null) { + out.push(None); + } else { + match f(v)? { + Some(x) => out.push(Some(x)), + None => return Err(anyhow::anyhow!("Mixed types in array")), + } + } + } + Ok(Some(out)) } else { Ok(None) } @@ -1819,26 +1826,23 @@ fn convert_vec_val( Type::BOOL_ARRAY, )), "char" | "character" => Ok(( - Box::new(map_as_single_type(vec, |v| { - v.as_i64() - .map(|x| x as i8) - .or_else(|| v.as_str().and_then(|s| s.parse::().ok())) + Box::new(try_map_as_single_type(vec, |v| match v.as_i64() { + Some(x) => narrow_sql_int::(x, "\"char\"").map(Some), + None => Ok(v.as_str().and_then(|s| s.parse::().ok())), })?), Type::CHAR_ARRAY, )), "smallint" | "smallserial" | "int2" | "serial2" => Ok(( - Box::new(map_as_single_type(vec, |v| { - v.as_i64() - .map(|x| x as i16) - .or_else(|| v.as_str().and_then(|s| s.parse::().ok())) + Box::new(try_map_as_single_type(vec, |v| match v.as_i64() { + Some(x) => narrow_sql_int::(x, "smallint").map(Some), + None => Ok(v.as_str().and_then(|s| s.parse::().ok())), })?), Type::INT2_ARRAY, )), "int" | "integer" | "int4" | "serial" => Ok(( - Box::new(map_as_single_type(vec, |v| { - v.as_i64() - .map(|x| x as i32) - .or_else(|| v.as_str().and_then(|s| s.parse::().ok())) + Box::new(try_map_as_single_type(vec, |v| match v.as_i64() { + Some(x) => narrow_sql_int::(x, "integer").map(Some), + None => Ok(v.as_str().and_then(|s| s.parse::().ok())), })?), Type::INT4_ARRAY, )), @@ -1859,18 +1863,18 @@ fn convert_vec_val( Type::NUMERIC_ARRAY, )), "oid" => Ok(( - Box::new(map_as_single_type(vec, |v| { - v.as_u64() - .map(|x| x as u32) - .or_else(|| v.as_str().and_then(|s| s.parse::().ok())) + Box::new(try_map_as_single_type(vec, |v| match v.as_u64() { + Some(x) => narrow_sql_int::(x, "oid").map(Some), + None => Ok(v.as_str().and_then(|s| s.parse::().ok())), })?), Type::OID_ARRAY, )), "bigint" | "bigserial" | "int8" | "serial8" => Ok(( - Box::new(map_as_single_type(vec, |v| { - v.as_i64() - .or_else(|| v.as_u64().map(|x| x as i64)) - .or_else(|| v.as_str().and_then(|s| s.parse::().ok())) + Box::new(try_map_as_single_type(vec, |v| match v.as_u64() { + Some(x) => narrow_sql_int::(x, "bigint").map(Some), + None => Ok(v + .as_i64() + .or_else(|| v.as_str().and_then(|s| s.parse::().ok()))), })?), Type::INT8_ARRAY, )), @@ -2074,7 +2078,8 @@ fn convert_val( Ok((Box::new(n.to_string()), t)) } Value::Number(n) if arg_t == "char" && n.is_i64() => { - Ok((Box::new(n.as_i64().unwrap() as i8), Type::CHAR)) + let n = narrow_sql_int::(n.as_i64().unwrap(), "\"char\"")?; + Ok((Box::new(n), Type::CHAR)) } Value::Number(n) if (arg_t == "smallint" @@ -2083,13 +2088,15 @@ fn convert_val( || arg_t == "serial2") && n.is_i64() => { - Ok((Box::new(n.as_i64().unwrap() as i16), Type::INT2)) + let n = narrow_sql_int::(n.as_i64().unwrap(), "smallint")?; + Ok((Box::new(n), Type::INT2)) } Value::Number(n) if (arg_t == "int" || arg_t == "integer" || arg_t == "int4" || arg_t == "serial") && n.is_i64() => { - Ok((Box::new(n.as_i64().unwrap() as i32), Type::INT4)) + let n = narrow_sql_int::(n.as_i64().unwrap(), "integer")?; + Ok((Box::new(n), Type::INT4)) } Value::Number(n) if (arg_t == "real" || arg_t == "float4") && n.as_f64().is_some() => { Ok((Box::new(n.as_f64().unwrap() as f32), Type::FLOAT4)) @@ -2109,7 +2116,8 @@ fn convert_val( Type::NUMERIC, )), Value::Number(n) if arg_t == "oid" && n.is_u64() => { - Ok((Box::new(n.as_u64().unwrap() as u32), Type::OID)) + let n = narrow_sql_int::(n.as_u64().unwrap(), "oid")?; + Ok((Box::new(n), Type::OID)) } Value::Number(n) if (arg_t == "bigint" @@ -2118,7 +2126,8 @@ fn convert_val( || arg_t == "serial8") && n.is_u64() => { - Ok((Box::new(n.as_u64().unwrap() as i64), Type::INT8)) + let n = narrow_sql_int::(n.as_u64().unwrap(), "bigint")?; + Ok((Box::new(n), Type::INT8)) } Value::Number(n) if n.is_i64() => Ok((Box::new(n.as_i64().unwrap()), Type::INT8)), Value::Number(n) => Ok((Box::new(n.as_f64().unwrap()), Type::FLOAT8)), @@ -3313,6 +3322,47 @@ mod tests { assert_convert_val_consistent("Number(0)/oid", json!(0), "oid", typ_for("oid"), Type::OID); } + #[test] + fn convert_val_rejects_out_of_range_integers() { + let convert = |value: Value, arg_t: &str| { + convert_val(&value, &arg_t.to_string(), &typ_for(arg_t), false) + .map(|_| ()) + .map_err(|e| e.to_string()) + }; + for (value, arg_t, sql_type) in [ + (json!(200), "char", "\"char\""), + (json!(70000), "smallint", "smallint"), + (json!(-40000), "int2", "smallint"), + (json!(4294967297u64), "int4", "integer"), + (json!(4294967296u64), "oid", "oid"), + (json!(u64::MAX), "bigint", "bigint"), + (json!([1, 70000]), "smallint[]", "smallint"), + (json!([u64::MAX]), "int8[]", "bigint"), + ] { + let err = convert(value.clone(), arg_t).expect_err(&format!("{value}/{arg_t}")); + let n = value.as_array().map_or(&value, |a| a.last().unwrap()); + assert!( + err.contains(&format!( + "value \"{n}\" is out of range for type {sql_type}" + )), + "{value}/{arg_t}: {err}" + ); + } + for (value, arg_t) in [ + (json!(127), "char"), + (json!(-128), "char"), + (json!(32767), "smallint"), + (json!(-32768), "smallint"), + (json!(2147483647), "int"), + (json!(-2147483648i64), "int"), + (json!(4294967295u64), "oid"), + (json!(i64::MAX), "bigint"), + (json!([null, -32768, 32767]), "smallint[]"), + ] { + convert(value.clone(), arg_t).unwrap_or_else(|e| panic!("{value}/{arg_t}: {e}")); + } + } + #[test] fn convert_val_float_number_against_every_arg_t() { let cases: &[(&str, Type)] = &[ diff --git a/backend/windmill-worker/src/python_executor.rs b/backend/windmill-worker/src/python_executor.rs index e7ddd91531..430d6e82ef 100644 --- a/backend/windmill-worker/src/python_executor.rs +++ b/backend/windmill-worker/src/python_executor.rs @@ -149,15 +149,16 @@ use crate::global_cache::pull_from_tar; use windmill_object_store::get_cache_object_store; use crate::{ + check_no_network_jailed, common::{ build_command_with_isolation, create_args_and_out_file, get_reserved_variables, read_file, read_result, render_nsjail_rlimit_as, resolve_nsjail_timeout, - resolve_nsjail_tmp_mount_block, start_child_process, OccupancyMetrics, StreamNotifier, - DEV_CONF_NSJAIL, + proto_str, resolve_nsjail_tmp_mount_block, start_child_process, OccupancyMetrics, + StreamNotifier, DEV_CONF_NSJAIL, }, - get_proxy_envs_for_lang, + get_proxy_envs_for_lang, get_run_proxy_envs, handle_child::handle_child, - is_sandboxing_enabled, read_ee_registry, + is_sandboxing_enabled, nsjail_clone_newnet, read_ee_registry, worker_utils::ping_job_status, PyV, DISABLE_NUSER, HOME_ENV, INDEX_CERT, NATIVE_CERT, NSJAIL_AVAILABLE, NSJAIL_PATH, NSJAIL_PY_RLIMIT_AS_MB, PATH_ENV, PIP_EXTRA_INDEX_URL, PIP_INDEX_URL, PROXY_ENVS, @@ -775,6 +776,8 @@ pub async fn handle_python_job( .to_string(), )); } + let jailed = is_sandboxing_enabled() || annotations.sandbox; + check_no_network_jailed(annotations.no_network, jailed)?; // Preview jobs may carry _TEMP_SCRIPT_REFS so relative imports resolve from // not-yet-deployed local content uploaded to raw_script_temp. Gated on @@ -792,6 +795,19 @@ pub async fn handle_python_job( }; let module_sources = windmill_parser_py_imports::module_sources(&script_path, modules.as_ref()); + if annotations.no_network { + let imports = std::iter::once((script_path.as_str(), inner_content.as_str())) + .chain( + module_sources + .iter() + .flatten() + .map(|(path, code)| (path.as_str(), code.as_str())), + ) + .flat_map(|(path, code)| { + windmill_parser_py_imports::parse_relative_imports(code, path).unwrap_or_default() + }); + crate::check_no_network_imports(imports, &script_path, modules.as_ref(), "Python")?; + } let (py_version, mut additional_python_paths) = handle_python_deps_with_modules( job_dir, requirements_o, @@ -839,6 +855,9 @@ pub async fn handle_python_job( if annotations.sandbox { logs.push_str("sandbox mode (nsjail)\n"); } + if annotations.no_network { + logs.push_str("no network\n"); + } append_logs(&job.id, &job.workspace_id, logs, conn).await; } let ( @@ -1080,6 +1099,7 @@ except BaseException as e: let mut reserved_variables = get_reserved_variables(job, &client.token, conn, parent_runnable_path).await?; + crate::strip_no_network_token(&mut reserved_variables, annotations.no_network); // Add /tmp/windmill/cache/python_x_y_z/global-site-packages to PYTHONPATH. // Usefull if certain wheels needs to be preinstalled before execution. @@ -1112,7 +1132,7 @@ except BaseException as e: #[cfg(windows)] let additional_python_paths_folders = additional_python_paths_folders.replace(":", ";"); - if is_sandboxing_enabled() || annotations.sandbox { + if jailed { let shared_deps = additional_python_paths .into_iter() .map(|pp| { @@ -1128,6 +1148,7 @@ mount {{ ) }) .join("\n"); + let module_mounts = python_module_mounts(job_dir, &dirs, modules.as_ref()); let nsjail_timeout = resolve_nsjail_timeout(conn, &job.workspace_id, job.id, job.timeout).await; let _ = write_file( @@ -1141,8 +1162,13 @@ mount {{ .replace("{JOB_DIR}", job_dir) .replace("{PY_INSTALL_DIR}", &*PY_INSTALL_DIR) .replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string()) + .replace( + "{CLONE_NEWNET}", + nsjail_clone_newnet(annotations.no_network), + ) .replace("{SHARED_MOUNT}", shared_mount) .replace("{SHARED_DEPENDENCIES}", shared_deps.as_str()) + .replace("{MODULE_MOUNTS}", &module_mounts) .replace("{GLOBAL_SITE_PACKAGES}", &global_site_packages_path) .replace("{MAIN}", format!("{dirs}/{last}").as_str()) .replace( @@ -1167,7 +1193,7 @@ mount {{ job.id ); - let child = if is_sandboxing_enabled() || annotations.sandbox { + let child = if jailed { let mut nsjail_cmd = Command::new(NSJAIL_PATH.as_str()); nsjail_cmd .current_dir(job_dir) @@ -1175,12 +1201,13 @@ mount {{ // inject PYTHONPATH here - for some reason I had to do it in nsjail conf .envs(reserved_variables) .envs( - get_proxy_envs_for_lang( + get_run_proxy_envs( &ScriptLang::Python3, job.kind, &job.id, &job.workspace_id, conn, + annotations.no_network, ) .await?, ) @@ -1302,6 +1329,28 @@ mount {{ Ok(result) } +/// nsjail mounts for a job's module files. They are written next to the main script, and the +/// jail sees only what it mounts: without these, a module import falls through to the +/// loader's API fetch. Keys come from the request, hence the containment check and quoting. +fn python_module_mounts( + job_dir: &str, + dirs: &str, + modules: Option<&HashMap>, +) -> String { + modules + .into_iter() + .flat_map(|m| m.keys()) + .filter(|rel| crate::worker::is_contained_relative_path(rel)) + .map(|rel| { + format!( + "mount {{\n src: {}\n dst: {}\n is_bind: true\n mandatory: false\n}}\n", + proto_str(&format!("{job_dir}/{dirs}/{rel}")), + proto_str(&format!("/tmp/{dirs}/{rel}")), + ) + }) + .join("\n") +} + /// Generate Python code to spread preprocessor args from `kwargs` into `pre_args`. /// The `indent` parameter controls the join separator for multi-arg spreads. fn python_preprocessor_spread(sig: &windmill_parser::MainArgSignature, indent: &str) -> String { @@ -3716,6 +3765,25 @@ pub async fn start_worker( #[cfg(test)] mod tests { + #[test] + fn module_files_are_mounted_next_to_the_main_script() { + let module = |content: &str| windmill_common::scripts::ScriptModule { + content: content.to_string(), + language: windmill_common::scripts::ScriptLang::Python3, + lock: None, + }; + let modules = HashMap::from([ + ("lib/util.py".to_string(), module("")), + ("../escape.py".to_string(), module("")), + ("q\"uote.py".to_string(), module("")), + ]); + let mounts = super::python_module_mounts("/jobs/1", "u/admin", Some(&modules)); + assert!(mounts.contains("src: \"/jobs/1/u/admin/lib/util.py\""), "{mounts}"); + assert!(mounts.contains("dst: \"/tmp/u/admin/lib/util.py\""), "{mounts}"); + assert!(!mounts.contains("escape"), "{mounts}"); + assert!(mounts.contains("q\\\"uote.py"), "{mounts}"); + } + use super::*; #[test] diff --git a/backend/windmill-worker/src/r_executor.rs b/backend/windmill-worker/src/r_executor.rs index d273d08785..214cf35525 100644 --- a/backend/windmill-worker/src/r_executor.rs +++ b/backend/windmill-worker/src/r_executor.rs @@ -18,14 +18,15 @@ use windmill_parser_r::{parse_r_requirements, parse_r_signature}; use windmill_queue::{append_logs, CanceledBy, MiniPulledJob}; use crate::{ + check_no_network_jailed, common::{ build_command_with_isolation, create_args_and_out_file, get_reserved_variables, - read_result, resolve_nsjail_tmp_mount_block, script_envars, script_overrides, start_child_process, - OccupancyMetrics, DEV_CONF_NSJAIL, + read_result, resolve_nsjail_tmp_mount_block, script_envars, script_overrides, + start_child_process, OccupancyMetrics, DEV_CONF_NSJAIL, }, - get_proxy_envs_for_lang, + get_proxy_envs_for_lang, get_run_proxy_envs, handle_child::{self}, - is_sandboxing_enabled, + is_sandboxing_enabled, nsjail_clone_newnet, universal_pkg_installer::{ par_install_language_dependencies_seq, DependencyGraph, InstallDeps, RequiredDependency, }, @@ -86,6 +87,8 @@ pub async fn handle_r_job<'a>( .to_string(), )); } + let jailed = !cfg!(windows) && (is_sandboxing_enabled() || annotation.sandbox); + check_no_network_jailed(annotation.no_network, jailed)?; // --- Prepare --- { @@ -120,7 +123,13 @@ pub async fn handle_r_job<'a>( }; // --- Execute --- { - run(&mut args, lib_path.as_deref(), annotation.sandbox).await?; + run( + &mut args, + lib_path.as_deref(), + jailed, + annotation.no_network, + ) + .await?; } // --- Retrieve results --- { @@ -593,17 +602,21 @@ async fn run<'a>( .. }: &mut JobHandlerInput<'a>, lib_path: Option<&str>, - sandbox: bool, + nsjail: bool, + no_network: bool, ) -> Result<(), Error> { - let reserved_variables = + let mut reserved_variables = get_reserved_variables(job, &client.token, conn, parent_runnable_path.clone()).await?; + crate::strip_no_network_token(&mut reserved_variables, no_network); - let nsjail = !cfg!(windows) && (is_sandboxing_enabled() || sandbox); let child = if nsjail { append_logs( &job.id, &job.workspace_id, - "\n--- R CODE EXECUTION (nsjail) ---\n".to_string(), + format!( + "\n--- R CODE EXECUTION (nsjail) ---\n{}", + if no_network { "no network\n" } else { "" } + ), conn, ) .await; @@ -614,14 +627,19 @@ async fn run<'a>( .env("PATH", PATH_ENV.as_str()) .env("BASE_INTERNAL_URL", base_internal_url) .envs(&reserved_variables) - .envs(R_PROXY_ENVS.clone()) + .envs(if no_network { + vec![] + } else { + R_PROXY_ENVS.clone() + }) .envs( - get_proxy_envs_for_lang( + get_run_proxy_envs( &ScriptLang::Rlang, job.kind, &job.id, &job.workspace_id, conn, + no_network, ) .await?, ); @@ -651,9 +669,14 @@ async fn run<'a>( &resolve_nsjail_tmp_mount_block(job_dir).await, ) .replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string()) + .replace("{CLONE_NEWNET}", nsjail_clone_newnet(no_network)) .replace( "{ENVARS}", - &script_envars(&envs, &cmd, &script_overrides(&["PATH", "BASE_INTERNAL_URL"], &reserved_variables)), + &script_envars( + &envs, + &cmd, + &script_overrides(&["PATH", "BASE_INTERNAL_URL"], &reserved_variables), + ), ), )?; start_child_process(cmd, NSJAIL_PATH.as_str(), false).await? diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs index 7ad7558c98..4048a3603c 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -261,6 +261,7 @@ const NUM_SECS_PING: u64 = 5; const NUM_SECS_READINGS: u64 = 60; const INCLUDE_DEPS_PY_SH_CONTENT: &str = include_str!("../nsjail/download_deps.py.sh"); +const NSJAIL_CONFIG_PROBE_CONTENT: &str = include_str!("../nsjail/probe.config.proto"); const WORKER_SHELL_NAP_TIME_DURATION: u64 = 15; const WORKER_SHELL_INITIAL_NAP_TIME_DURATION: u64 = 5; @@ -335,6 +336,14 @@ pub struct PowershellRepo { pub pat: String, } +/// Runs nsjail in a form gVisor (runsc) accepts, see `nsjail_compat`. +pub static NSJAIL_GVISOR_COMPAT: std::sync::LazyLock = std::sync::LazyLock::new(|| { + std::env::var("NSJAIL_GVISOR_COMPAT") + .ok() + .and_then(|x| x.parse::().ok()) + .unwrap_or(false) +}); + lazy_static::lazy_static! { static ref SLEEP_QUEUE_BASE: u64 = std::env::var("SLEEP_QUEUE") @@ -358,6 +367,15 @@ lazy_static::lazy_static! { .and_then(|x| x.parse::().ok()) .unwrap_or(false); + /// Runs Bun scripts' dependency installs (bun and `//npm`) outside nsjail even when + /// sandboxing is on, for a worker whose installs need host files the install jail + /// does not mount (keys for private git dependencies, a package cache outside HOME). + /// The run step stays jailed; the installs' lifecycle scripts see the worker again. + pub static ref DISABLE_BUN_INSTALL_SANDBOX: bool = std::env::var("DISABLE_BUN_INSTALL_SANDBOX") + .ok() + .and_then(|x| x.parse::().ok()) + .unwrap_or(false); + /// Per-language override for the nsjail `rlimit_as` (virtual address space) cap. /// Value is in MiB, or `unlimited`/`none`/`inf`/`0` to uncap. Unset keeps the /// historical default baked into the proto. See `render_nsjail_rlimit_as`. @@ -537,29 +555,41 @@ lazy_static::lazy_static! { pub static ref NSJAIL_AVAILABLE: Option = { let nsjail_path = NSJAIL_PATH.as_str(); - let test_result = std::process::Command::new(nsjail_path) - .arg("--help") - .output(); - - match test_result { + match probe_nsjail(nsjail_path) { Ok(output) if output.status.success() => { - tracing::info!("nsjail available at: {}", nsjail_path); + tracing::info!( + "nsjail available at: {}{}", + nsjail_path, + if *NSJAIL_GVISOR_COMPAT { " (NSJAIL_GVISOR_COMPAT)" } else { "" } + ); Some(nsjail_path.to_string()) }, Ok(output) => { - let stderr = String::from_utf8_lossy(&output.stderr); - tracing::error!( - "nsjail test failed (exit code: {}). stderr: '{}'. path: '{}'. \ - Nsjail sandboxing will NOT be available. \ - nsjail should be included in all standard windmill images. \ - If job_isolation is set to 'nsjail_sandboxing' in Instance Settings, jobs will fail.", + let msg = format!( + "nsjail could not run a test jail (exit code: {}). stderr: '{}'. path: '{}'. \ + Nsjail sandboxing will NOT be available: the worker reports its job isolation \ + without nsjail, and jobs that require nsjail fail. Under gVisor (runsc), see \ + NSJAIL_GVISOR_COMPAT.", output.status, - stderr.trim(), + String::from_utf8_lossy(&output.stderr).trim(), nsjail_path ); + // Most workers never jail anything, and most containers cannot. + if *DISABLE_NSJAIL { + tracing::info!("{msg}"); + } else { + tracing::error!("{msg}"); + } + None + }, + Err(NsjailProbeError::Setup(e)) => { + tracing::error!( + "Could not prepare the nsjail test jail: {}. Nsjail sandboxing will NOT be available.", + e + ); None }, - Err(e) => { + Err(NsjailProbeError::Start(e)) => { if e.kind() == std::io::ErrorKind::NotFound { tracing::error!( "nsjail not found at '{}'. Nsjail sandboxing will NOT be available. \ @@ -1012,6 +1042,43 @@ pub(crate) fn artifact_cache_name( format!("mod-{}", windmill_common::utils::calculate_hash(&keyed)) } +/// Runs `/bin/true` in a jail built like a job's, through the same spawn path, so a worker +/// whose runtime lets nsjail start but not jail (a container without the privileges, gVisor) +/// does not report nsjail isolation. +enum NsjailProbeError { + /// The probe could not be prepared: nothing is known about nsjail. + Setup(std::io::Error), + /// nsjail itself could not be executed. + Start(std::io::Error), +} + +fn probe_nsjail(nsjail_path: &str) -> Result { + // A fresh private directory: the worker runs what this config says, as itself. + let dir = std::env::temp_dir().join(format!("windmill-nsjail-probe-{}", uuid::Uuid::new_v4())); + let mut builder = std::fs::DirBuilder::new(); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder.create(&dir).map_err(NsjailProbeError::Setup)?; + let output = (|| { + std::fs::write( + dir.join("probe.config.proto"), + NSJAIL_CONFIG_PROBE_CONTENT.replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string()), + ) + .map_err(NsjailProbeError::Setup)?; + let mut cmd = std::process::Command::new(nsjail_path); + cmd.current_dir(&dir) + .env_clear() + .env("PATH", PATH_ENV.as_str()) + .args(["--config", "probe.config.proto"]); + if *NSJAIL_GVISOR_COMPAT { + crate::nsjail_compat::apply(&cmd).map_err(NsjailProbeError::Setup)?; + } + cmd.output().map_err(NsjailProbeError::Start) + })(); + let _ = std::fs::remove_dir_all(&dir); + output +} + pub fn is_sandboxing_enabled() -> bool { if !*DISABLE_NSJAIL { return true; @@ -1022,6 +1089,189 @@ pub fn is_sandboxing_enabled() -> bool { } } +/// A `no_network` job loses its network only through the fresh network namespace its +/// nsjail run step is given, so a run step that would not be jailed is refused rather +/// than run with the worker's network. `jailed` is the executor's own decision to jail. +pub fn check_no_network_jailed( + no_network: bool, + jailed: bool, +) -> windmill_common::error::Result<()> { + no_network_refusal(no_network, jailed, NSJAIL_AVAILABLE.is_some()) +} + +fn no_network_refusal( + no_network: bool, + jailed: bool, + nsjail_available: bool, +) -> windmill_common::error::Result<()> { + if !no_network || (jailed && nsjail_available) { + return Ok(()); + } + let reason = if jailed { + "nsjail is not available on this worker" + } else { + "this job would not run in an nsjail sandbox: add the `sandbox` annotation, or enable \ + nsjail sandboxing for the instance" + }; + Err(windmill_common::error::Error::ExecutionErr(format!( + "Script has the `no_network` annotation, which removes the network from its nsjail \ + sandbox, but {reason}. Refusing to run it with network." + ))) +} + +/// Whether a script asks for a run step without network, which only nsjail provides. A +/// dedicated worker runs its script outside nsjail, so it leaves such a script to the +/// regular executor. +pub fn runs_no_network_in_jail(language: Option, content: &str) -> bool { + match language { + Some(ScriptLang::Python3) => { + windmill_common::worker::PythonAnnotations::parse(content).no_network + } + Some(ScriptLang::Bun) | Some(ScriptLang::Bunnative) => { + let annotation = windmill_common::worker::TypeScriptAnnotations::parse(content); + annotation.no_network && !annotation.native + } + _ => false, + } +} + +/// Refuses a `no_network` job that imports another workspace script its run step would fetch +/// from the API, which it cannot reach. Without this the fetch fails inside the script, where +/// Python's loader falls back to an empty namespace module and the error names something else. +/// `imports` are workspace paths; the job's own module files (keyed relative to +/// `script_path`'s folder) are on disk and need no fetch. +pub fn check_no_network_imports( + imports: impl IntoIterator, + script_path: &str, + modules: Option<&HashMap>, + fetched_by: &str, +) -> windmill_common::error::Result<()> { + let dir = script_path + .rsplit_once('/') + .map(|(dir, _)| dir) + .unwrap_or(""); + let local: Vec = modules + .into_iter() + .flat_map(|m| m.keys()) + .map(|key| { + let stem = key.rsplit_once('.').map(|(stem, _)| stem).unwrap_or(key); + if dir.is_empty() { + stem.to_string() + } else { + format!("{dir}/{stem}") + } + }) + .collect(); + let fetched = imports.into_iter().find(|import| { + !local + .iter() + .any(|l| l == import || l.starts_with(&format!("{import}/"))) + }); + match fetched { + None => Ok(()), + Some(import) => Err(windmill_common::error::Error::ExecutionErr(format!( + "Script has the `no_network` annotation but imports the workspace script \ + `{import}`, which {fetched_by} fetches from the Windmill API while the script runs, \ + and the script has no network. Remove `no_network`, or copy that code into the \ + script." + ))), + } +} + +/// Drops `WM_TOKEN` from a `no_network` run step's env: it is useless without network, and +/// the script could still hand it out through its result. +pub fn strip_no_network_token( + reserved_variables: &mut std::collections::HashMap, + no_network: bool, +) { + if no_network { + reserved_variables.remove("WM_TOKEN"); + } +} + +/// `clone_newnet` for a run step's nsjail profile. +pub fn nsjail_clone_newnet(no_network: bool) -> &'static str { + if no_network { + "true" + } else { + "false" + } +} + +/// [`get_proxy_envs_for_lang`] for a run step. A `no_network` one reaches no proxy, the +/// OTel tracing proxy included, so it gets only the trace context. +pub async fn get_run_proxy_envs( + lang: &ScriptLang, + job_kind: JobKind, + job_id: &uuid::Uuid, + w_id: &str, + conn: &Connection, + no_network: bool, +) -> anyhow::Result> { + if no_network { + return Ok(get_otel_context_envs(job_id)); + } + get_proxy_envs_for_lang(lang, job_kind, job_id, w_id, conn).await +} + +#[cfg(test)] +mod no_network_tests { + use super::{check_no_network_imports, no_network_refusal, runs_no_network_in_jail}; + use windmill_common::scripts::ScriptLang; + + #[test] + fn no_network_runs_only_in_an_available_jail() { + assert!(no_network_refusal(false, false, false).is_ok()); + assert!(no_network_refusal(true, true, true).is_ok()); + assert!(no_network_refusal(true, false, true).is_err()); + assert!(no_network_refusal(true, true, false).is_err()); + assert!(no_network_refusal(true, false, false).is_err()); + } + + #[test] + fn no_network_refuses_only_imports_it_would_fetch() { + let modules = std::collections::HashMap::from([( + "lib/util.py".to_string(), + windmill_common::scripts::ScriptModule { + content: String::new(), + lock: None, + language: ScriptLang::Python3, + }, + )]); + let check = |imports: &[&str]| { + check_no_network_imports( + imports.iter().map(|s| s.to_string()), + "u/admin/main", + Some(&modules), + "Python", + ) + }; + assert!(check(&["u/admin/lib/util", "u/admin/lib"]).is_ok()); + let err = check(&["u/admin/lib/util", "u/admin/helper"]).unwrap_err(); + assert!(err.to_string().contains("`u/admin/helper`"), "{err}"); + } + + #[test] + fn dedicated_workers_leave_jailed_no_network_scripts() { + let py = Some(ScriptLang::Python3); + let bun = Some(ScriptLang::Bun); + assert!(runs_no_network_in_jail( + py, + "# no_network\ndef main(): pass" + )); + assert!(!runs_no_network_in_jail(py, "def main(): pass")); + assert!(runs_no_network_in_jail( + bun, + "// no_network\nexport function main() {}" + )); + // Native scripts take their network away inside the isolate. + assert!(!runs_no_network_in_jail( + bun, + "//native\n//no_network\nexport function main() {}" + )); + } +} + /// Returns true if unshare PID isolation should be used (when not using nsjail). /// ENABLE_UNSHARE_PID forces unshare regardless of the global setting. /// FAVOR_UNSHARE_PID uses unshare only when the global setting is not set. @@ -5779,7 +6029,7 @@ async fn record_declared_warehouse_write( /// True when `path` contains only `Normal`/`CurDir` components, i.e. it cannot /// escape the directory it is joined onto (no `..`, no absolute root, no Windows /// drive prefix). -fn is_contained_relative_path(path: &str) -> bool { +pub(crate) fn is_contained_relative_path(path: &str) -> bool { use std::path::Component; std::path::Path::new(path) .components() diff --git a/backend/windmill-worker/src/worker_flow.rs b/backend/windmill-worker/src/worker_flow.rs index a257ca51fa..c188f8de58 100644 --- a/backend/windmill-worker/src/worker_flow.rs +++ b/backend/windmill-worker/src/worker_flow.rs @@ -1631,7 +1631,17 @@ pub async fn update_flow_status_after_job_completion_internal( Some(t) => { let no_args = HashMap::new(); let args = PushArgs::from(fetched_args.as_ref().unwrap_or(&no_args)); - resolve_push_tag(t, &args, &flow_job.workspace_id, db).await + match resolve_push_tag(t, &args, &flow_job.workspace_id, db).await { + Some(t) => Some( + windmill_queue::tags::apply_dev_workspace_suffix( + t, + &flow_job.workspace_id, + db, + ) + .await?, + ), + None => None, + } } None => None, }; @@ -2210,7 +2220,8 @@ pub async fn update_flow_status_after_job_completion_internal( None }, has_triggered_error_handler: has_triggered_error_handler || is_failure_step, - recovered_by_child: failure_step_recovers || (recovered_by_child && !success), + recovered_by_child: failure_step_recovers + || (recovered_by_child && !success), }, )); } @@ -3284,8 +3295,17 @@ pub(crate) fn resolve_flow_step_tag( workspace_id: &str, preserve_step_tags: bool, step_tag: Option<&str>, + // The suffix of a dev workspace's flow tag, if any: its flows run on the generic tag suffixed, + // and their steps are suffixed when pushed. + dev_suffix: Option<&str>, ) -> Option { - if is_preprocessor_step || flow_tag == "flow" || flow_tag == format!("flow-{}", workspace_id) { + let generic_flow_tag = dev_suffix + .and_then(|s| flow_tag.strip_suffix(s)) + .unwrap_or(flow_tag); + if is_preprocessor_step + || generic_flow_tag == "flow" + || generic_flow_tag == format!("flow-{}", workspace_id) + { step_tag.map(str::to_string) } else if preserve_step_tags && step_tag.is_some_and(|t| !t.is_empty()) { step_tag.map(str::to_string) @@ -3363,7 +3383,14 @@ mod tag_resolution_tests { // Parent flow on a custom tag, step declares its own tag, preserve disabled: // the step inherits the flow tag (historical behavior). assert_eq!( - resolve_flow_step_tag(false, "worker-group-A", "w1", false, Some("worker-group-B")), + resolve_flow_step_tag( + false, + "worker-group-A", + "w1", + false, + Some("worker-group-B"), + None + ), Some("worker-group-A".to_string()) ); } @@ -3373,7 +3400,14 @@ mod tag_resolution_tests { // The exact customer scenario: a sub-flow tagged worker-group-B run as a step of a // flow tagged worker-group-A now runs on worker-group-B when preserve_step_tags is on. assert_eq!( - resolve_flow_step_tag(false, "worker-group-A", "w1", true, Some("worker-group-B")), + resolve_flow_step_tag( + false, + "worker-group-A", + "w1", + true, + Some("worker-group-B"), + None + ), Some("worker-group-B".to_string()) ); } @@ -3381,12 +3415,12 @@ mod tag_resolution_tests { #[test] fn untagged_step_inherits_flow_tag_even_when_preserve_enabled() { assert_eq!( - resolve_flow_step_tag(false, "worker-group-A", "w1", true, None), + resolve_flow_step_tag(false, "worker-group-A", "w1", true, None, None), Some("worker-group-A".to_string()) ); // An empty tag counts as "no tag" and still inherits. assert_eq!( - resolve_flow_step_tag(false, "worker-group-A", "w1", true, Some("")), + resolve_flow_step_tag(false, "worker-group-A", "w1", true, Some(""), None), Some("worker-group-A".to_string()) ); } @@ -3395,16 +3429,38 @@ mod tag_resolution_tests { fn generic_flow_tag_always_uses_step_tag() { for flow_tag in ["flow", "flow-w1"] { assert_eq!( - resolve_flow_step_tag(false, flow_tag, "w1", false, Some("worker-group-B")), + resolve_flow_step_tag(false, flow_tag, "w1", false, Some("worker-group-B"), None), Some("worker-group-B".to_string()) ); } } + #[test] + fn dev_workspace_flow_on_suffixed_generic_tag_uses_step_tag() { + for flow_tag in ["flow-dev", "flow-w1-dev"] { + assert_eq!( + resolve_flow_step_tag(false, flow_tag, "w1", false, Some("gpu"), Some("-dev")), + Some("gpu".to_string()) + ); + } + // In a root workspace `flow-dev` is a custom tag the steps inherit. + assert_eq!( + resolve_flow_step_tag(false, "flow-dev", "w1", false, Some("gpu"), None), + Some("flow-dev".to_string()) + ); + } + #[test] fn preprocessor_step_uses_step_tag() { assert_eq!( - resolve_flow_step_tag(true, "worker-group-A", "w1", false, Some("worker-group-B")), + resolve_flow_step_tag( + true, + "worker-group-A", + "w1", + false, + Some("worker-group-B"), + None + ), Some("worker-group-B".to_string()) ); } @@ -4654,6 +4710,9 @@ async fn push_next_flow_job( &flow_job.workspace_id, flow.preserve_step_tags, payload_tag.tag.as_deref(), + windmill_queue::tags::dev_flow_tag_suffix(&flow_job.workspace_id, &flow_job.tag, db) + .await? + .as_deref(), ); // A step whose inputs failed to evaluate, or whose `$flow_expr[...]` tag failed to resolve, @@ -4794,10 +4853,8 @@ async fn push_next_flow_job( // narrows that further. windmill_common::scopes::intersect_job_token_scopes( flow_job.job_token_scopes.as_deref(), - windmill_common::scopes::step_job_token_scopes( - module.job_token_scopes.as_deref(), - ) - .as_deref(), + windmill_common::scopes::step_job_token_scopes(module.job_token_scopes.as_deref()) + .as_deref(), ) .as_deref(), ) diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 6cd5afc3c2..61315e1683 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.837.0"; +export const VERSION = "v1.841.0"; 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 58b042307a..93d3e00348 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.837.0", + "version": "1.841.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.837.0", + "version": "1.841.0", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index f2e146b4de..ca4b73df45 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.837.0", + "version": "1.841.0", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index 481c71af1b..d65b343bfe 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.837.0"; +export const VERSION = "1.841.0"; diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index bcef0d5d3e..7d0cf5c1cc 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -1419,7 +1419,7 @@ export async function main(url: string) { ## Pure computation: \`//no_network\` -A native script that only transforms its inputs can declare \`//no_network\` in its leading comment block (right after \`//native\`). The runtime then refuses every connection the script attempts: \`fetch\` to any host, the Windmill API (so \`windmill-client\` calls fail too), raw sockets and unix sockets, and \`WM_TOKEN\` is not set. It only takes effect on native scripts: without \`//native\` it is ignored. Use it only when the script needs no external data beyond its arguments: +A native script that only transforms its inputs can declare \`//no_network\` in its leading comment block (right after \`//native\`). The runtime then refuses every connection the script attempts: \`fetch\` to any host, the Windmill API (so \`windmill-client\` calls fail too), raw sockets and unix sockets, and \`WM_TOKEN\` is not set. Without \`//native\` it means something else: the script must run in an nsjail sandbox (\`//sandbox\`, or instance-wide sandboxing), which then loses its network, and it fails to run otherwise. Use it only when the script needs no external data beyond its arguments: \`\`\`typescript //native @@ -4731,15 +4731,31 @@ def get_flow_user_state(key: str) -> Any def version() # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from DuckDB +# initiate an S3 connection from DuckDB. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as \`\`s3:///\`\` with the +# storage's own bucket, returned as \`\`s3_bucket\`\`. Pass the resource path to connect with +# the storage's own credentials instead. def get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from Polars +# initiate an S3 connection from Polars. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as \`\`s3:///\`\` with the +# storage's own bucket, returned as \`\`s3_bucket\`\`. Pass the resource path to connect with +# the storage's own credentials instead. def get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection using boto3 +# initiate an S3 connection using boto3. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: pass the storage's own bucket as \`\`Bucket\`\`. The proxy +# serves object reads, writes, deletes, listing and multipart uploads of that bucket only; +# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials, +# which passing the resource path returns. def get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings # Load a file from the workspace s3 bucket and returns its content as bytes. @@ -8327,7 +8343,7 @@ write a secret you were not given: keep the placeholder. | \`git_sync\` | \`{ repositories: [...] }\`, each with \`git_repo_resource_path\`, \`script_path\` and \`settings\` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | | \`datatable\` | \`{ datatables: { : { database: { resource_type, resource_path? } } } }\`. Role permissions are \`datatable_permissions\`. | | \`datatable_permissions\` | \`{ : { default_role, roles: { : [tenants] } } }\`: who may connect to each data table as which role. Tenants are \`u/\`, \`g/\`, \`f/\` or \`*\`; \`admin\` is always a role, and \`default_role: null\` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | -| \`protection_rules\` | \`{ : { rules: [...], bypass_groups: [...], bypass_users: [...] } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | +| \`protection_rules\` | \`{ : { rules: [...], bypass_groups: [...], bypass_users: [...] } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | \`ducklake\` | \`{ ducklakes: { : { catalog, storage, ... } } }\`. | | \`dbt_warehouses\` | dbt warehouse connections. | | \`default_app\` | Path of the app shown as the workspace home. | diff --git a/docker/DockerfileSlim b/docker/DockerfileSlim index ef976f83d3..630f454f01 100644 --- a/docker/DockerfileSlim +++ b/docker/DockerfileSlim @@ -23,7 +23,9 @@ RUN apt-get -y update \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* -RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 +COPY docker/nsjail-patches/ /nsjail-patches/ +RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 \ + && git apply /nsjail-patches/*.patch RUN make FROM ${DEBIAN_IMAGE} diff --git a/docker/DockerfileSlimEe b/docker/DockerfileSlimEe index 67de36eac7..8189e74bf9 100644 --- a/docker/DockerfileSlimEe +++ b/docker/DockerfileSlimEe @@ -23,7 +23,9 @@ RUN apt-get -y update \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* -RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 +COPY docker/nsjail-patches/ /nsjail-patches/ +RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 \ + && git apply /nsjail-patches/*.patch RUN make FROM ${DEBIAN_IMAGE} diff --git a/docker/nsjail-patches/gvisor-compat.patch b/docker/nsjail-patches/gvisor-compat.patch new file mode 100644 index 0000000000..70176b7272 --- /dev/null +++ b/docker/nsjail-patches/gvisor-compat.patch @@ -0,0 +1,153 @@ +gvisor_compat: an opt-in nsjail option (config field and --gvisor_compat) for running inside +gVisor (runsc). With it false, nsjail behaves as upstream. With it true: +- no rtnetlink link cache when no interface is moved into the jail: gVisor acks NLM_F_DUMP + requests before NLMSG_DONE and libnl rejects that (google/gvisor#15945); +- an EPERM from setrlimit(RLIMIT_MSGQUEUE) is a warning: gVisor refuses that limit for any + value (google/gvisor#15944); +- an EPERM from PR_SET_SECUREBITS is tolerated when the UID does not change, where the bits + have no effect (SECBIT_NO_SETUID_FIXUP lands in gVisor with google/gvisor#15130). +Applied to google/nsjail dccf911fd2659e7b08ce9507c25b2b38ec2c5800 by the Dockerfiles. + +diff --git a/cmdline.cc b/cmdline.cc +index 1b52b33..b49ce16 100644 +--- a/cmdline.cc ++++ b/cmdline.cc +@@ -115,6 +115,7 @@ struct custom_option custom_opts[] = { + { { "rlimit_rtprio", required_argument, NULL, 0x0210 }, "RLIMIT_RTPRIO, 'max' or 'hard' for the current hard limit, 'def' or 'soft' for the current soft limit, 'inf' for RLIM64_INFINITY (default: 'soft')" }, + { { "rlimit_msgqueue", required_argument, NULL, 0x0211 }, "RLIMIT_MSGQUEUE in bytes, 'max' or 'hard' for the current hard limit, 'def' or 'soft' for the current soft limit, 'inf' for RLIM64_INFINITY (default: 'soft')" }, + { { "disable_rlimits", no_argument, NULL, 0x0208 }, "Disable all rlimits, default to limits set by parent" }, ++ { { "gvisor_compat", no_argument, NULL, 0x0510 }, "Tolerate what gVisor (runsc) does not implement (see config.proto)" }, + { { "persona_addr_compat_layout", no_argument, NULL, 0x0301 }, "personality(ADDR_COMPAT_LAYOUT)" }, + { { "persona_mmap_page_zero", no_argument, NULL, 0x0302 }, "personality(MMAP_PAGE_ZERO)" }, + { { "persona_read_implies_exec", no_argument, NULL, 0x0303 }, "personality(READ_IMPLIES_EXEC)" }, +@@ -437,6 +438,7 @@ std::unique_ptr parseArgs(int argc, char* argv[]) { + nsjconf->rl_rtpr = parseRLimit(RLIMIT_RTPRIO, "soft", 1); + nsjconf->rl_msgq = parseRLimit(RLIMIT_MSGQUEUE, "soft", 1); + nsjconf->disable_rl = false; ++ nsjconf->gvisor_compat = false; + nsjconf->personality = 0; + nsjconf->clone_newnet = true; + nsjconf->clone_newuser = true; +@@ -603,6 +605,9 @@ std::unique_ptr parseArgs(int argc, char* argv[]) { + case 0x0208: + nsjconf->disable_rl = true; + break; ++ case 0x0510: ++ nsjconf->gvisor_compat = true; ++ break; + case 0x0301: + nsjconf->personality |= ADDR_COMPAT_LAYOUT; + break; +diff --git a/config.cc b/config.cc +index 620d08e..9427069 100644 +--- a/config.cc ++++ b/config.cc +@@ -166,6 +166,7 @@ static bool configParseInternal(nsjconf_t* nsjconf, const nsjail::NsJailConfig& + configRLimit(RLIMIT_MSGQUEUE, njc.rlimit_msgqueue_type(), njc.rlimit_msgqueue()); + + nsjconf->disable_rl = njc.disable_rl(); ++ nsjconf->gvisor_compat = njc.gvisor_compat(); + + if (njc.persona_addr_compat_layout()) { + nsjconf->personality |= ADDR_COMPAT_LAYOUT; +diff --git a/config.proto b/config.proto +index cd297ae..96b477c 100644 +--- a/config.proto ++++ b/config.proto +@@ -266,4 +266,10 @@ message NsJailConfig { + /* Binary path (with arguments) to be executed. If not specified here, it + can be specified with cmd-line as "-- /path/to/command arg1 arg2" */ + optional Exe exec_bin = 90; ++ ++ /* Tolerate what gVisor (runsc) does not implement: an EPERM from ++ setrlimit(RLIMIT_MSGQUEUE) or from PR_SET_SECUREBITS when the UID does ++ not change, and no rtnetlink link cache when no interface is moved ++ into the jail */ ++ optional bool gvisor_compat = 93 [default = false]; + } +diff --git a/contain.cc b/contain.cc +index b5120cc..41e69f8 100644 +--- a/contain.cc ++++ b/contain.cc +@@ -172,8 +172,12 @@ static bool containSetLimits(nsjconf_t* nsjconf) { + } + rl.rlim_cur = rl.rlim_max = nsjconf->rl_msgq; + if (setrlimit64(RLIMIT_MSGQUEUE, &rl) == -1) { +- PLOG_E("setrlimit64(0, RLIMIT_MSGQUEUE , %" PRIu64 ")", nsjconf->rl_msgq); +- return false; ++ if (!nsjconf->gvisor_compat || errno != EPERM) { ++ PLOG_E("setrlimit64(0, RLIMIT_MSGQUEUE , %" PRIu64 ")", nsjconf->rl_msgq); ++ return false; ++ } ++ PLOG_W("setrlimit64(0, RLIMIT_MSGQUEUE , %" PRIu64 "), ignored (gvisor_compat)", ++ nsjconf->rl_msgq); + } + return true; + } +diff --git a/net.cc b/net.cc +index 87c3df9..b4c64f4 100644 +--- a/net.cc ++++ b/net.cc +@@ -138,6 +138,10 @@ bool initNsFromParent(nsjconf_t* nsjconf, int pid) { + if (!nsjconf->clone_newnet) { + return true; + } ++ /* gVisor's rtnetlink replies are rejected by libnl's link cache, which is unused here */ ++ if (nsjconf->gvisor_compat && nsjconf->ifaces.empty() && nsjconf->iface_vs.empty()) { ++ return true; ++ } + struct nl_sock* sk = nl_socket_alloc(); + if (!sk) { + LOG_E("Could not allocate socket with nl_socket_alloc()"); +diff --git a/nsjail.h b/nsjail.h +index 5687ca7..fa2b9fa 100644 +--- a/nsjail.h ++++ b/nsjail.h +@@ -119,6 +119,7 @@ struct nsjconf_t { + uint64_t rl_rtpr; + uint64_t rl_msgq; + bool disable_rl; ++ bool gvisor_compat; + unsigned long personality; + bool clone_newnet; + bool clone_newuser; +diff --git a/user.cc b/user.cc +index a335e2d..f3e578b 100644 +--- a/user.cc ++++ b/user.cc +@@ -260,10 +260,24 @@ bool initNsFromChild(nsjconf_t* nsjconf) { + * Make sure all capabilities are retained after the subsequent setuid/setgid, as they will + * be needed for privileged operations: mounts, uts change etc. + */ ++ bool securebits_set = true; + if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NO_SETUID_FIXUP, 0UL, 0UL, 0UL) == + -1) { +- PLOG_E("prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NO_SETUID_FIXUP)"); +- return false; ++ /* ++ * The bits only matter when setresuid() below changes the UID: without them, ++ * leaving UID 0 clears the capabilities still needed by the jail setup. ++ */ ++ uid_t ruid, euid, suid; ++ const uid_t uid = nsjconf->uids[0].inside_id; ++ if (!nsjconf->gvisor_compat || errno != EPERM || ++ getresuid(&ruid, &euid, &suid) == -1 || ruid != uid || euid != uid || ++ suid != uid) { ++ PLOG_E("prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NO_SETUID_FIXUP)"); ++ return false; ++ } ++ PLOG_W("prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NO_SETUID_FIXUP), " ++ "ignored (gvisor_compat, UID unchanged)"); ++ securebits_set = false; + } + + /* +@@ -306,7 +320,7 @@ bool initNsFromChild(nsjconf_t* nsjconf) { + * unexpectedly retaining capabilities after a UID/GID + * change. + */ +- if (prctl(PR_SET_SECUREBITS, 0UL, 0UL, 0UL, 0UL) == -1) { ++ if (securebits_set && prctl(PR_SET_SECUREBITS, 0UL, 0UL, 0UL, 0UL) == -1) { + PLOG_E("prctl(PR_SET_SECUREBITS, 0)"); + return false; + } diff --git a/docs/fork-object-storage.md b/docs/fork-object-storage.md new file mode 100644 index 0000000000..7428119f97 --- /dev/null +++ b/docs/fork-object-storage.md @@ -0,0 +1,68 @@ +# Fork-isolated workspace object storage + +A fork clones its parent's `large_file_storage` settings, so without isolation it reads and +writes the parent's objects: a script iterating in a fork overwrites production's files. Each +storage the fork isolates (a `fork_storage_namespace` row, chosen at fork creation, default +isolated) instead maps logical keys: + +- **Writes** (put, multipart, delete, copy destination) go to `__wm_forks//`, + the same one-component segment DuckLake's fork namespaces use (`fork_data_dir_segment`). +- **Reads** try the fork's own key, then each ancestor's mapping, nearest first, then the root's + raw key. They stop at the first ancestor whose storage is a different one + (`lfs_entry_storage_ref`): its keys are not in this bucket. A shared fork maps like its parent. +- **Listings** show the workspace's own objects only, as logical keys. +- **Deletes** remove the fork's copy; an ancestor's object stays readable through it. + +The mapping (`windmill_common::fork_storage::ForkStorageKeys`) is applied wherever Windmill +turns a workspace-storage key into a storage operation: the `ForkStore` object-store wrapper +(`windmill_object_store::fork_store::workspace_object_store`) for every server-side helper, and +key rewriting in the S3 proxy's raw S3 forwarding (URI key, list `prefix`/`start-after`/`marker` +and response keys, `x-amz-copy-source`). A named resource (`s3_resource_path`) is not workspace +storage and is never mapped. A workspace whose keys are mapped is refused its workspace +storage's own credentials (`s3_resource_info`, the duckdb/polars settings endpoints): a client +holding them would write past the mapping. + +Not mapped, on purpose: AI sessions and volumes (their keys already carry the workspace id), +SMTP attachments (job-id keys), the storage usage count (it counts the whole bucket). Known +gaps: the worker's result-cache hash HEADs the logical key unmapped, and a read of an object +the fork does not own costs one HEAD per chain level before the GET. + +## Invariants + +- **`__wm_forks/` is reachable only through the workspace's own chain.** A key under it maps to + itself when it is in the workspace's own area (writes) or an area of the chain (reads), and is + refused otherwise; listings hide it. This is also what keeps DuckLake working: its fork data + paths arrive already prefixed, and its defer attaches read ancestors' raw keys through the + read chain. Every workspace gets the rule, isolating or not, so pre-existing forks' lakes keep + working. +- **No `.` or `..` key segments**, in any workspace: the proxy forwards mapped keys in a URL, + where they collapse and would climb out of the fork's prefix. +- **The prefix derives from the workspace id**, so an isolating fork's id cannot be changed + (`change_workspace_id` refuses): under a new id it would see none of its objects. Nor can an + isolated storage be repointed, since the purge targets the storage recorded at creation. +- **A shared lake needs its storage shared**: its files must land at the parent's keys, where the + parent's catalog looks for them. Fork creation refuses the other combination. +- **Children before parents**: deleting a fork that has forks of its own is refused when anything + in its chain isolates a storage, shared forks included. A child reads through, or writes into, + the isolating prefix via that link, and without it the child's chain would map like the root's. +- **Deletion and same-id creation are serialized** on the `fork:` advisory lock, and a purge + skips an id that exists again: the rows are then the new fork's. The proxy caches only the raw + client, never a mapping, so fork creation and deletion invalidate the one mapping cache. +- **Deletion always purges** the fork's area of each isolated storage, post-commit, from the + storage identity recorded at creation: nothing can reach it once the fork is gone. Rows have + no FK and outlive the workspace when the purge fails; creating a fork with the same id retries + them and refuses while they cannot be purged, since a same-id fork would read them. +- Isolation is a per-fork-creation choice (`shared_storages` on create-fork), never inherited. + Forks created before the registry existed have no rows and keep sharing. + +## Requiring isolation + +The `RequireIsolatedForks` protection rule on a workspace makes its forks leave nothing shared +with it, for every user the ruleset does not exempt (admins always are): no `shared_storages`, +no `shared_ducklakes`, and every data table whose database it owns cloned rather than kept as a +pointer. A data table whose database another workspace owns is left alone: that is not its data. +A clone governed from another workspace still has its own database, so it is not exempt. It is +checked against the workspace being forked, in +`create_workspace_fork` and in the git-branch pre-check (so a refused fork leaves no branch +behind), and the data table part again under the parent's `lock_fork_datatables`, which data table +edits also take: a table added between the two would otherwise reach the fork as a pointer. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 337525a347..30ac859fce 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.837.0", + "version": "1.841.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.837.0", + "version": "1.841.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index 42f1bdc9b0..7320d9c5f6 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.837.0", + "version": "1.841.0", "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", diff --git a/frontend/src/lib/components/AuthSettings.svelte b/frontend/src/lib/components/AuthSettings.svelte index d1dd5fa08b..cdf847e8fb 100644 --- a/frontend/src/lib/components/AuthSettings.svelte +++ b/frontend/src/lib/components/AuthSettings.svelte @@ -90,7 +90,6 @@ 'visma', 'sage_intacct', 'spotify', - 'teams', 'zoho', 'xero', 'apify', @@ -98,7 +97,8 @@ 'salesforce', 'outreach', 'notion', - 'hubspot' + 'hubspot', + 'asana' ] // Providers whose registry entry (`backend/oauth_connect.json`) carries a // `sandbox` URL block. Each one gets a sibling `_sandbox` dropdown @@ -120,6 +120,8 @@ const connectConfigTemplates: Record = Object.fromEntries( Object.entries(oauthConnectRegistry) .filter(([, cfg]) => cfg && typeof cfg === 'object' && 'connect_config_template' in cfg) + // ms_teams has the pinned Teams tile instead: its tenant field fills the template. + .filter(([name]) => name !== 'ms_teams') .map(([name, cfg]) => [name, (cfg as any).connect_config_template]) ) const windmillBuiltinsTemplated = Object.keys(connectConfigTemplates) @@ -490,12 +492,13 @@
- +
{#each Object.keys(oauths) as k} {#if oauths[k] && !(oauths[k] && 'login_config' in oauths[k])} - {#if !['slack', 'teams'].includes(k) && oauths[k]} + + {#if !['slack', 'ms_teams', 'teams'].includes(k) && oauths[k]} {@const IconComponent = getOAuthProviderIcon(k) as any} {@const headerLabel = k.endsWith('_sandbox') ? `${k.slice(0, -'_sandbox'.length)} (sandbox)` diff --git a/frontend/src/lib/components/AutoscalingConfigEditor.svelte b/frontend/src/lib/components/AutoscalingConfigEditor.svelte index 3ebbb5d41c..885b6dd55c 100644 --- a/frontend/src/lib/components/AutoscalingConfigEditor.svelte +++ b/frontend/src/lib/components/AutoscalingConfigEditor.svelte @@ -15,15 +15,27 @@ import Select from './select/Select.svelte' import ScriptPicker from './ScriptPicker.svelte' import { sendUserToast } from '$lib/toast' + import { untrack } from 'svelte' interface Props { config: AutoscalingConfig | undefined worker_tags: string[] | undefined + /** Whether the draft config gives the group any tags (worker_tags or dedicated workers). */ + group_has_tags: boolean + /** Tags reported by the group's live workers, which for agent workers come from their token. */ + reported_tags: string[] disabled: boolean eeOnly?: boolean } - let { config = $bindable(), worker_tags, disabled, eeOnly = false }: Props = $props() + let { + config = $bindable(), + worker_tags, + group_has_tags, + reported_tags, + disabled, + eeOnly = false + }: Props = $props() let test_input: number = $state(3) let healthCheckLoading: boolean = $state(false) let healthCheckResult: { success: boolean; error?: string } | null = $state(null) @@ -54,7 +66,9 @@ } } - let collapsed: boolean = $state(true) + let noTagsToCount = $derived(!!config?.enabled && !group_has_tags && !config.custom_tags?.length) + + let collapsed: boolean = $state(untrack(() => !noTagsToCount))
{/snippet} + {#if noTagsToCount} + { + if (config) config.custom_tags = [...reported_tags] + } + } + ] + : []} + > + Autoscaling counts waiting jobs on this group's worker tags, or on the custom tags under + Advanced, and this group has neither. Agent workers don't need either to run, since their tags + come from their token, but to scale on their queue set worker tags or custom tags to the tags + their token was issued with. + + {/if} +
+ import { Alert, Button, Section } from './common' + import ConfirmationModal from './common/confirmationModal/ConfirmationModal.svelte' + import Toggle from './Toggle.svelte' + import TextInput from './text_input/TextInput.svelte' + import Select from './select/Select.svelte' + import Tooltip from './meltComponents/Tooltip.svelte' + import { ArrowRight, ChevronDown, ChevronRight, Save, Settings } from 'lucide-svelte' + import { + SettingService, + WorkerService, + WorkspaceService, + type GetQueueStatusResponse, + type Workspace + } from '$lib/gen' + import { + DEV_WORKSPACE_ISOLATION_SETTING, + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING, + DEV_WORKSPACE_TAG_SUFFIX_SETTING + } from '$lib/consts' + import { + DEFAULT_DEV_WORKSPACE_TAG_SUFFIX, + DEV_WORKSPACE_TAG_SUFFIX_PATTERN, + devWorkspaceIsolation, + devWorkspaceListenSuffix, + devWorkspaceSkipNonDevForks, + devWorkspaceTagSuffix, + isDevOrForkWorkspace, + isIsolatedWorkspace, + loadDevWorkspaceTagSuffix, + withDevSuffix + } from '$lib/devWorkspaceTags' + import { enterpriseLicense } from '$lib/stores' + import { sendUserToast } from '$lib/toast' + import { pluralize } from '$lib/utils' + import { onMount } from 'svelte' + + interface Props { + /** Worker group configs, by group name. */ + workerGroups: Record | undefined + /** Workers of each group that pinged in the last 15 seconds. */ + liveWorkers: Record + canEdit: boolean + onConfigureGroup: (name: string) => void + } + + let { workerGroups, liveWorkers, canEdit, onConfigureGroup }: Props = $props() + + let suffix = $derived($devWorkspaceTagSuffix) + let enabled = $derived(suffix != null) + let effectiveSuffix = $derived($devWorkspaceListenSuffix) + + // Overridden while a confirmation is pending, reset to the saved state otherwise. + let toggleChecked = $derived(enabled) + let suffixDraft = $derived(effectiveSuffix) + let suffixError = $derived( + DEV_WORKSPACE_TAG_SUFFIX_PATTERN.test(suffixDraft.trim()) + ? undefined + : "Use 1 to 32 letters, digits, '-', '_' or '.'" + ) + + let skipNonDevForks = $derived($devWorkspaceSkipNonDevForks) + // Overridden while saving, reset to the saved state otherwise. + let skipChecked = $derived(skipNonDevForks) + let workspaces = $state(undefined) + let devWorkspaces = $derived( + (workspaces ?? []).filter( + (w) => !w.deleted && isIsolatedWorkspace(w, workspaces ?? [], skipNonDevForks) + ) + ) + // Workspaces whose new forks skip isolation while non-dev forks are not isolated: the roots and + // their non-dev forks. A forking rule does not cascade to forks, so each needs its own. + let forkSources = $derived( + (workspaces ?? []).filter((w) => !w.deleted && !isIsolatedWorkspace(w, workspaces ?? [], true)) + ) + let nonDevForkCount = $derived( + (workspaces ?? []).filter( + (w) => + !w.deleted && isDevOrForkWorkspace(w) && !isIsolatedWorkspace(w, workspaces ?? [], true) + ).length + ) + // Roots anyone may fork: no rule withholds forking, or their rules could not be read, which + // must not hide the warning. `undefined` until checked. + let forkableRoots = $state(undefined) + let forkableRootsRun = 0 + async function loadForkableRoots(roots: string[]) { + const run = ++forkableRootsRun + const unprotected: string[] = [] + for (let i = 0; i < roots.length; i += 8) { + const batch = await Promise.all( + roots.slice(i, i + 8).map(async (id) => { + try { + const rules = await WorkspaceService.listProtectionRules({ workspace: id }) + return !rules.some((r) => r.rules.includes('DisableWorkspaceForking')) + } catch { + return true + } + }) + ) + if (run !== forkableRootsRun) return + unprotected.push(...roots.slice(i, i + 8).filter((_, j) => batch[j])) + } + forkableRoots = unprotected + } + $effect(() => { + if (skipNonDevForks && workspaces !== undefined) { + loadForkableRoots(forkSources.map((w) => w.id)) + } + }) + let workspaceNames = $derived(Object.fromEntries((workspaces ?? []).map((w) => [w.id, w.name]))) + + async function loadWorkspaces() { + const all: Workspace[] = [] + for (let page = 1; ; page++) { + const batch = await WorkspaceService.listWorkspacesAsSuperAdmin({ page, perPage: 100 }) + all.push(...batch) + if (batch.length < 100) break + } + workspaces = all + } + + let queueStatus = $state(undefined) + async function loadQueueStatus() { + try { + queueStatus = await WorkerService.getQueueStatus() + } catch { + queueStatus = undefined + } + } + + onMount(() => { + loadDevWorkspaceTagSuffix(true) + loadWorkspaces().catch((e) => console.error('Could not list workspaces', e)) + loadQueueStatus() + const interval = setInterval(loadQueueStatus, 15_000) + return () => clearInterval(interval) + }) + + type GroupEntry = { name: string; live: number; tags: string[] } + + function isDedicated(config: any): boolean { + return config?.dedicated_worker != undefined || (config?.dedicated_workers?.length ?? 0) > 0 + } + + let flaggedGroups: GroupEntry[] = $derived( + Object.entries(workerGroups ?? {}) + .filter(([_, c]) => c?.serves_dev_workspaces === true && !isDedicated(c)) + .map(([name, c]) => ({ name, live: liveWorkers[name] ?? 0, tags: c?.worker_tags ?? [] })) + ) + let liveFlaggedWorkers = $derived(flaggedGroups.reduce((acc, g) => acc + g.live, 0)) + let unflaggedGroupNames = $derived( + Object.entries(workerGroups ?? {}) + .filter(([_, c]) => c?.serves_dev_workspaces !== true && !isDedicated(c)) + .map(([name]) => name) + ) + // The only way to break isolation: an unflagged group listing a suffixed tag takes dev jobs. + let leakingGroups = $derived( + Object.entries(workerGroups ?? {}) + .filter(([_, c]) => c?.serves_dev_workspaces !== true) + .map(([name, c]) => ({ + name, + tags: ((c?.worker_tags ?? []) as string[]).filter((t) => t.endsWith(effectiveSuffix)) + })) + .filter((g) => g.tags.length > 0) + ) + let unservedDevTags = $derived( + enabled + ? (queueStatus ?? []).filter( + (s) => s.tag.endsWith(effectiveSuffix) && s.waiting > 0 && s.workers === 0 + ) + : [] + ) + + let groupToFlag = $state(undefined) + let collapsed = $state(true) + let showWorkspaces = $state(false) + let showAdvanced = $state(false) + + let confirmEnable = $state(false) + let confirmDisable = $state(false) + let saving = $state(false) + + async function setIsolation(on: boolean) { + saving = true + try { + await SettingService.setGlobal({ + key: DEV_WORKSPACE_ISOLATION_SETTING, + requestBody: { value: on } + }) + devWorkspaceIsolation.update((i) => ({ + suffix: i?.suffix ?? effectiveSuffix, + skip_non_dev_forks: i?.skip_non_dev_forks ?? false, + enabled: on + })) + sendUserToast( + on + ? `Dev workspace and fork jobs now run on tags suffixed with ${effectiveSuffix}` + : 'Dev workspace isolation turned off' + ) + } catch (e) { + sendUserToast(`Could not save dev workspace isolation: ${e}`, true) + toggleChecked = enabled + } finally { + saving = false + } + } + + async function saveSuffix(value: string) { + saving = true + try { + await SettingService.setGlobal({ + key: DEV_WORKSPACE_TAG_SUFFIX_SETTING, + requestBody: { value } + }) + devWorkspaceIsolation.update((i) => ({ + enabled: i?.enabled ?? false, + skip_non_dev_forks: i?.skip_non_dev_forks ?? false, + suffix: value + })) + sendUserToast(`Dev workspace tag suffix set to ${value}`) + } catch (e) { + sendUserToast(`Could not save the dev workspace tag suffix: ${e}`, true) + } finally { + saving = false + } + } + + async function setSkipNonDevForks(skip: boolean) { + saving = true + try { + await SettingService.setGlobal({ + key: DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING, + requestBody: { value: skip } + }) + devWorkspaceIsolation.update((i) => ({ + enabled: i?.enabled ?? false, + suffix: i?.suffix ?? effectiveSuffix, + skip_non_dev_forks: skip + })) + sendUserToast( + skip + ? 'Forks of non-dev workspaces now run on the workers of the workspace they fork' + : 'Forks of non-dev workspaces now run on dev workers' + ) + } catch (e) { + sendUserToast(`Could not save dev workspace isolation: ${e}`, true) + skipChecked = skipNonDevForks + } finally { + saving = false + } + } + + function onToggle(checked: boolean) { + if (checked === enabled) return + collapsed = false + if (checked) { + if (liveFlaggedWorkers === 0) { + confirmEnable = true + } else { + setIsolation(true) + } + } else { + confirmDisable = true + } + } + + function workspaceKind(w: Workspace): string { + if (w.parent_workspace_id) { + const parent = workspaceNames[w.parent_workspace_id] ?? w.parent_workspace_id + return w.is_dev_workspace ? `dev workspace of ${parent}` : `fork of ${parent}` + } + return 'fork whose parent was deleted' + } + + + { + confirmEnable = false + toggleChecked = enabled + }} + onConfirmed={async () => { + confirmEnable = false + await setIsolation(true) + }} +> +
+

+ {#if workspaces === undefined} + Every dev workspace and fork + {:else} + {pluralize(devWorkspaces.length, 'dev workspace or fork', 'dev workspaces and forks')} + {/if} + will have their jobs queued until a worker group serves them. +

+

+ {#if flaggedGroups.length === 0} + No worker group is flagged as serving dev workspaces yet. + {:else} + The worker groups serving dev workspaces ({flaggedGroups.map((g) => g.name).join(', ')}) + have no live worker. + {/if} + Jobs never fall back to the other worker groups: they wait in the queue and run as soon as a serving + worker is up. +

+ {#if unflaggedGroupNames.length > 0 && flaggedGroups.length === 0} +
+ +
+ {/if} +
+
+ + { + confirmDisable = false + toggleChecked = enabled + }} + onConfirmed={async () => { + confirmDisable = false + await setIsolation(false) + }} +> +

+ New jobs of dev workspaces and forks will run on the same worker groups as root workspaces + again. Jobs already queued on a {effectiveSuffix} tag keep it, and the worker groups + serving dev workspaces still run them. +

+
+ +{#snippet isolationToggle()} + onToggle(e.detail)} + disabled={!canEdit || !$enterpriseLicense || saving || suffix === undefined} + options={{ right: 'Run dev workspaces and forks on separate workers' }} + size="xs" + /> +{/snippet} + +
+ {#snippet action()} + {@render isolationToggle()} + {/snippet} + {#snippet badge()} + {@render isolationToggle()} + {/snippet} + +
+
+ Root workspaces + + + Worker groups not serving dev workspaces, on their usual tags: + python3, gpu + + Dev workspaces and forks + + + {#if enabled} + Worker groups serving dev workspaces, on tags suffixed with + {effectiveSuffix}: + {:else} + Once on, worker groups serving dev workspaces, on suffixed tags: + {/if} + {withDevSuffix('python3', effectiveSuffix)}, + {withDevSuffix('gpu', effectiveSuffix)} + +
+

+ A workspace with a parent, and every fork (including a fork whose parent was deleted), counts + as a dev workspace, unless forks of non-dev workspaces are left out below. Every job is + covered: runs, previews, schedules, triggers, flow steps, AI agent tools and dependency jobs, + and inline runs are refused on workers not serving dev workspaces. A job whose tag no serving + worker listens to stays queued: it never falls back to the other worker groups. Dedicated + workers keep their own tags. +

+ +
+ setSkipNonDevForks(e.detail)} + disabled={!canEdit || !$enterpriseLicense || saving || suffix === undefined} + options={{ right: "Don't isolate forks of non-dev workspaces" }} + size="xs" + /> + + A fork with no dev workspace above it, like a fork of a production workspace or a fork of + that fork, runs on the same workers as that production workspace. Dev workspaces and their + forks stay isolated. Restrict who can create such forks with the Disable workspace forking + protection rule of each such workspace and fork. + {#if skipNonDevForks && workspaces !== undefined} + {pluralize(nonDevForkCount, 'fork')} currently {nonDevForkCount === 1 ? 'runs' : 'run'} + outside isolation. + {/if} + + {#if skipNonDevForks && forkableRoots && forkableRoots.length > 0} + + Anyone who can fork + {#each forkableRoots.slice(0, 5) as id, i (id)} + {i > 0 ? ', ' : ''}{workspaceNames[id] ?? id} + {/each}{forkableRoots.length > 5 ? ` and ${forkableRoots.length - 5} more` : ''} + can run jobs on {forkableRoots.length === 1 ? 'its' : 'their'} workers. Add a + Disable workspace forking protection rule to {forkableRoots.length === 1 + ? 'it' + : 'them'}, bypassed by the people allowed to fork, or isolate these forks again. + + {/if} +
+ + +
+ Worker groups serving dev workspaces + {#if flaggedGroups.length > 0} +
+ {#each flaggedGroups as g (g.name)} + + {/each} +
+ {:else} + None yet. + {/if} + {#if canEdit && unflaggedGroupNames.length > 0} +
+ + + + Jobs in this workspace run on dev workers (tags suffixed with + {$devWorkspaceTagSuffix}, e.g. + {withDevSuffix('python3', $devWorkspaceTagSuffix)}), set by the instance's dev + workspace isolation. + +

+ {/if} +{/snippet} + {#if isThrowawayFork}

Dev workspace pairing is not available on a throwaway fork. This workspace is a fork of {parentId}.

+
{@render devWorkersNotice()}
{@render deployTarget?.()} {:else if isDev && parentId}
@@ -563,6 +595,7 @@ {currentLabel} branch.
+ {@render devWorkersNotice()}
{@render deployTarget?.()}
diff --git a/frontend/src/lib/components/GroupEditor.svelte b/frontend/src/lib/components/GroupEditor.svelte index b4229cf9f6..2c256207e1 100644 --- a/frontend/src/lib/components/GroupEditor.svelte +++ b/frontend/src/lib/components/GroupEditor.svelte @@ -330,10 +330,10 @@ } catch (e) { sendUserToast(e.body ?? String(e), true) // A failed create is not proof the group is absent: `create_group` commits before a - // git-sync step that can still fail the request, including with a 4xx. Only the name - // conflict says it was never written. Report rather than resolve — a group found by + // git-sync step that can still fail the request, including with a 4xx. Only a name + // conflict or reservation proves absence. Report rather than resolve — a group found by // name may be someone else's, and adopting it would send this draft's writes there. - const nameTaken = String(e?.body ?? '').includes('already exists') + const nameTaken = /already exists|is reserved/.test(String(e?.body ?? '')) if (created && !alreadyCreated && !nameTaken) { sendUserToast(`Group ${name} may have been created anyway — reopen it to check`, true) } diff --git a/frontend/src/lib/components/InstanceSetting.svelte b/frontend/src/lib/components/InstanceSetting.svelte index d6740c6c9b..a3a2d19fd6 100644 --- a/frontend/src/lib/components/InstanceSetting.svelte +++ b/frontend/src/lib/components/InstanceSetting.svelte @@ -21,6 +21,7 @@ import SimpleEditor from './SimpleEditor.svelte' import CriticalAlertChannels from './instanceSettings/CriticalAlertChannels.svelte' import RetentionPeriodOverrides from './instanceSettings/RetentionPeriodOverrides.svelte' + import AgentWorkloadIdentityIssuers from './instanceSettings/AgentWorkloadIdentityIssuers.svelte' import SmtpSettings from './instanceSettings/SmtpSettings.svelte' import SecretBackendConfig from './instanceSettings/SecretBackendConfig.svelte' import ExternalInstancePgSettings from './instanceSettings/ExternalInstancePgSettings.svelte' @@ -629,6 +630,8 @@
+ {:else if setting.fieldType == 'agent_workload_identity_issuers'} + {:else if setting.fieldType == 'critical_error_channels'} {:else if setting.fieldType == 'otel'} diff --git a/frontend/src/lib/components/InstanceSettings.svelte b/frontend/src/lib/components/InstanceSettings.svelte index a1a0f214d3..0883d9fb5e 100644 --- a/frontend/src/lib/components/InstanceSettings.svelte +++ b/frontend/src/lib/components/InstanceSettings.svelte @@ -307,6 +307,8 @@ const connectConfigTemplates: Record = Object.fromEntries( Object.entries(oauthConnectRegistry) .filter(([, cfg]) => cfg && typeof cfg === 'object' && 'connect_config_template' in cfg) + // ms_teams takes its tenant from the pinned Teams tile; the backend fills the URLs. + .filter(([name]) => name !== 'ms_teams') .map(([name, cfg]) => [name, (cfg as any).connect_config_template]) ) @@ -326,6 +328,12 @@ // instance name + its registry template (substituting {instance} into the // URLs). Replaces the old per-provider setup functions. function setupTemplatedOauthUrls() { + // The backend falls back to the pre-rename `teams` key when `ms_teams` is absent, so + // turning the Teams tile off (ms_teams saved before, gone now) has to drop both. + // TODO: remove with the backend fallback. + if (oauths && initialOauths?.['ms_teams'] && !oauths['ms_teams'] && oauths['teams']) { + delete oauths['teams'] + } for (const [name, tmpl] of Object.entries(connectConfigTemplates)) { if (!oauths?.[name]) continue const key = tmpl.extra_params_key ?? 'instance' @@ -1196,6 +1204,12 @@ {#if $enterpriseLicense} {/if} + {:else if category == 'Agent workers'} + {:else if category == 'Auth/OAuth/SAML'} { if (e.detail) { - if (name === 'teams') { + if (name === 'ms_teams') { value = { id: '', secret: '', tenant: '' } } else { value = { id: '', secret: '' } @@ -106,7 +106,7 @@ {#if enabled} - {#if name != 'slack' && name != 'teams'} + {#if name != 'slack' && name != 'ms_teams'} - {#if name == 'microsoft' || name == 'teams'} + {#if name == 'microsoft' || name == 'ms_teams'}
- {:else if name == 'teams'} + {:else if name == 'ms_teams'}
Follow this guide on Windmill Docs to create a new Microsoft Teams App. Then paste Client ID, Tenant ID, and Client Secret - here. + here. The same app serves the Teams bot (Enterprise Edition) and the Microsoft Teams + OAuth resource: to connect that resource, also add the redirect URI + BASE_URL/oauth/callback/ms_teams and the delegated Microsoft Graph + permissions you need to the app.
{/if} diff --git a/frontend/src/lib/components/WorkerGroup.svelte b/frontend/src/lib/components/WorkerGroup.svelte index 5e8957c31a..1f6b271602 100644 --- a/frontend/src/lib/components/WorkerGroup.svelte +++ b/frontend/src/lib/components/WorkerGroup.svelte @@ -56,6 +56,12 @@ import DedicatedWorkersSelector from './DedicatedWorkersSelector.svelte' import { computeHashedTag } from './dedicated_worker' import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' + import { + devWorkspaceListenSuffix, + devWorkspaceTagSuffix, + loadDevWorkspaceTagSuffix, + withDevSuffix + } from '$lib/devWorkspaceTags' import ObjectStoreConfigSettings, { type ObjectStoreConfig } from './ObjectStoreConfigSettings.svelte' @@ -106,6 +112,7 @@ native_mode?: boolean object_store_cache_config?: ObjectStoreConfig paused?: boolean + serves_dev_workspaces?: boolean } = $state({}) function loadNConfig() { @@ -214,6 +221,7 @@ native_mode?: boolean object_store_cache_config?: ObjectStoreConfig paused?: boolean + serves_dev_workspaces?: boolean } activeWorkers: number customTags: string[] | undefined @@ -319,7 +327,8 @@ 'priority_tags', 'additional_python_paths', 'pip_local_dependencies', - 'object_store_cache_config' + 'object_store_cache_config', + 'serves_dev_workspaces' ] as const function restartsWorkers(body: typeof nconfig): boolean { if (activeWorkers === 0) return false @@ -362,6 +371,15 @@ let drawer: Drawer | undefined = $state() let vcpus_memory = $derived(computeVCpuAndMemory(workers)) + let reportedTags = $derived( + [ + ...new Set( + workers.flatMap(([_, pings]) => + pings.filter((p) => (p.last_ping ?? Infinity) < 60).flatMap((p) => p.custom_tags ?? []) + ) + ) + ].sort() + ) let selected = $derived( nconfig?.dedicated_worker != undefined || nconfig?.dedicated_workers != undefined ? 'dedicated' @@ -381,6 +399,13 @@ !t.startsWith('flow-') ) ) + loadDevWorkspaceTagSuffix() + let devSuffix = $derived($devWorkspaceListenSuffix) + let servesDev = $derived( + config?.serves_dev_workspaces === true && + config?.dedicated_worker == undefined && + !config?.dedicated_workers?.length + ) let isAutoNativeMode = $derived(name === 'native') let isNativeModeEnabled = $derived(nconfig?.native_mode === true || isAutoNativeMode) $effect(() => { @@ -647,6 +672,63 @@ {/if} + {#if nconfig !== undefined} + {@const flagged = nconfig.serves_dev_workspaces === true} + {@const draftTags = nconfig.worker_tags ?? []} + {@const handSuffixed = draftTags.filter((t) => t.endsWith(devSuffix))} +
+ + {/if} + {#if nconfig?.worker_tags !== undefined && nconfig?.worker_tags.length > 0}