diff --git a/.github/workflows/git-sync-test.yml b/.github/workflows/git-sync-test.yml index b19f899a20..dd29837926 100644 --- a/.github/workflows/git-sync-test.yml +++ b/.github/workflows/git-sync-test.yml @@ -206,14 +206,21 @@ jobs: curl -sf http://localhost:8000/api/version > /dev/null || { echo "Windmill failed to start"; exit 1; } - name: Run git sync E2E tests - timeout-minutes: 10 + timeout-minutes: 75 env: GITEA_DOCKER_URL: http://localhost:3000 LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} run: | python3 -m venv .venv .venv/bin/pip install -r integration_tests/requirements.txt - cd integration_tests && ../.venv/bin/python -m unittest -v test.git_sync_test + cd integration_tests + fails=0 + for i in $(seq 1 8); do + echo "TEMP-LOOP iteration $i" + ../.venv/bin/python -m unittest -v test.git_sync_test || fails=$((fails+1)) + done + echo "TEMP-LOOP failed iterations: $fails" + [ "$fails" = 0 ] - name: Archive logs uses: actions/upload-artifact@v4 diff --git a/.release-please-manifest.json b/.release-please-manifest.json index a8dbca4d21..98dbdc3deb 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.839.0" + ".": "1.840.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 097a52223f..15223268e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## [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) diff --git a/Dockerfile b/Dockerfile index 80de6d4d16..e078c1bfef 100644 --- a/Dockerfile +++ b/Dockerfile @@ -254,6 +254,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-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-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-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-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-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-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-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-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-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-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 2b553c9396..6e13f00760 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -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", ] @@ -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.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-nats", @@ -15576,7 +15576,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.839.0" +version = "1.840.0" dependencies = [ "async-stream", "async-trait", @@ -15611,7 +15611,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -15624,7 +15624,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "argon2", @@ -15767,7 +15767,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -15790,7 +15790,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -15807,7 +15807,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "axum", @@ -15833,7 +15833,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.839.0" +version = "1.840.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -15843,7 +15843,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -15860,7 +15860,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "base64 0.22.1", @@ -15882,7 +15882,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "axum", @@ -15905,7 +15905,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -15921,7 +15921,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -15943,7 +15943,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -15965,7 +15965,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -15979,7 +15979,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-nats", @@ -16015,7 +16015,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "axum", @@ -16041,7 +16041,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -16069,7 +16069,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "axum", @@ -16091,7 +16091,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -16111,7 +16111,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "axum", @@ -16153,7 +16153,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "axum", @@ -16183,7 +16183,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.839.0" +version = "1.840.0" dependencies = [ "lazy_static", "serde", @@ -16195,7 +16195,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.839.0" +version = "1.840.0" dependencies = [ "argon2", "axum", @@ -16219,7 +16219,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -16234,7 +16234,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.839.0" +version = "1.840.0" dependencies = [ "axum", "chrono", @@ -16273,7 +16273,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.839.0" +version = "1.840.0" dependencies = [ "chrono", "lazy_static", @@ -16288,7 +16288,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "axum", @@ -16307,7 +16307,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.839.0" +version = "1.840.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16424,7 +16424,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.839.0" +version = "1.840.0" dependencies = [ "chrono", "futures", @@ -16444,7 +16444,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.839.0" +version = "1.840.0" dependencies = [ "regex", "serde", @@ -16461,7 +16461,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16488,7 +16488,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "futures", @@ -16505,7 +16505,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.839.0" +version = "1.840.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16521,7 +16521,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -16543,7 +16543,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -16574,7 +16574,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "arc-swap", @@ -16599,7 +16599,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-stream", @@ -16635,7 +16635,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "futures", @@ -16654,7 +16654,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.839.0" +version = "1.840.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16663,7 +16663,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -16675,7 +16675,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "serde_json", @@ -16687,7 +16687,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "gosyn", @@ -16699,7 +16699,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -16711,7 +16711,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "serde_json", @@ -16723,7 +16723,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "nu-parser", @@ -16734,7 +16734,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16745,7 +16745,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16757,7 +16757,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16768,7 +16768,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-recursion", @@ -16791,7 +16791,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "serde_json", @@ -16803,7 +16803,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -16817,7 +16817,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16834,7 +16834,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -16847,7 +16847,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "serde", @@ -16859,7 +16859,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -16877,7 +16877,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16893,7 +16893,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16910,7 +16910,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -16924,7 +16924,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-recursion", @@ -16963,7 +16963,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "const_format", @@ -17001,7 +17001,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.839.0" +version = "1.840.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17012,7 +17012,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-recursion", @@ -17047,7 +17047,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17071,7 +17071,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17104,7 +17104,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17131,7 +17131,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17164,7 +17164,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17184,7 +17184,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17218,7 +17218,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17255,7 +17255,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17278,7 +17278,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17302,7 +17302,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-nats", @@ -17326,7 +17326,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17361,7 +17361,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17389,7 +17389,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-trait", @@ -17414,7 +17414,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17433,7 +17433,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-once-cell", @@ -17551,7 +17551,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.839.0" +version = "1.840.0" dependencies = [ "bytes", "futures", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 070ea1ce5f..049ae66063 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.839.0" +version = "1.840.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.839.0" +version = "1.840.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" } diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 11beefbb27..cf65ae952f 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -1b6423df126e00aab58cf9e2943ee367d6ef2771 +30eb5229e76e7e1dee442265cd719c7865db1ed2 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 935bb9ebb6..ff51e06c6c 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.839.0" +version = "1.840.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.839.0" +version = "1.840.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.839.0" +version = "1.840.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.839.0" +version = "1.840.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 8b7d30f85c..5926c4dd7d 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.839.0" +version = "1.840.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/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/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/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-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..e160067dc9 100644 --- a/backend/windmill-api-agent-workers/Cargo.toml +++ b/backend/windmill-api-agent-workers/Cargo.toml @@ -7,6 +7,8 @@ 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 = [] 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-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-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-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-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/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/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-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-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-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 24f2bc5649..fd87b8f4be 100644 --- a/backend/windmill-api-workers/Cargo.toml +++ b/backend/windmill-api-workers/Cargo.toml @@ -7,6 +7,9 @@ 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 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/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 9ce356c47a..ffcd13e3ff 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.839.0 + version: 1.840.0 title: Windmill API contact: 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/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index ac6f6bd9e5..d9e9849252 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -640,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/worker.rs b/backend/windmill-common/src/worker.rs index c7199d96d0..1006238f4a 100644 --- a/backend/windmill-common/src/worker.rs +++ b/backend/windmill-common/src/worker.rs @@ -1207,6 +1207,7 @@ pub struct RlangAnnotations { pub renv_verbose: bool, pub renv_install_verbose: bool, pub sandbox: bool, + pub no_network: bool, } #[annotations("#")] @@ -1222,6 +1223,7 @@ pub struct PythonAnnotations { pub py314: bool, pub py315: bool, pub sandbox: bool, + pub no_network: bool, } #[annotations("//")] @@ -1332,6 +1334,7 @@ impl SqlAnnotations { pub struct BashAnnotations { pub docker: bool, pub sandbox: bool, + pub no_network: bool, } impl BashAnnotations { @@ -3855,6 +3858,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/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-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-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/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-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/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/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/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/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 63cb52d715..3e97802318 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -359,6 +359,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`. @@ -1023,6 +1032,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. @@ -5798,7 +5990,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/benchmarks/lib.ts b/benchmarks/lib.ts index 6586a0dda7..3c4e13839b 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.839.0"; +export const VERSION = "v1.840.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 3ec2e64abb..85647c34a6 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.839.0", + "version": "1.840.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.839.0", + "version": "1.840.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 65c515337c..089b41a1ee 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.839.0", + "version": "1.840.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 6bb4700b03..7ab4151f59 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.839.0"; +export const VERSION = "1.840.0"; diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index 5cf07a243b..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 diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 875df70ab0..220d9e2d33 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.839.0", + "version": "1.840.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.839.0", + "version": "1.840.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index c7d589aa97..cbab8b4faa 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.839.0", + "version": "1.840.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/integration_tests/test/git_sync_test.py b/integration_tests/test/git_sync_test.py index 3f761e36f5..13032f070d 100644 --- a/integration_tests/test/git_sync_test.py +++ b/integration_tests/test/git_sync_test.py @@ -215,17 +215,58 @@ class GitSyncTestBase(unittest.TestCase): return repo return None + def _new_sync_jobs(self, seen: set, path: str) -> list: + """Completed deploy callbacks not in `seen` whose items include `path`. + A callback debounced into another completes as skipped with its items + still in its args, so skipped ones are left out: only the survivor, + whose args carry the accumulated items, ran the push.""" + jobs = [] + for listed in self._client.get_completed_jobs(job_kinds="deploymentcallback"): + if listed["id"] in seen: + continue + job = self._client._client.get( + f"/api/w/{self._client._workspace}/jobs_u/get/{listed['id']}" + ).json() + if job.get("is_skipped"): + continue + items = (job.get("args") or {}).get("items") or [] + if any(item.get("path") == path for item in items): + jobs.append(job) + return jobs + def _deploy_seed_script(self, name_prefix: str) -> str: - """Deploy a script and wait for its push to git. Returns the script path.""" - initial_count = self._client.count_deployment_callback_jobs() + """Deploy a script and wait for its push to git. Returns the script path. + + Waits on the callback that carries this script, not on the workspace's + callback count: a callback still finishing from an earlier test raises + the count before this push lands.""" + seen = {j["id"] for j in self._client.get_completed_jobs(job_kinds="deploymentcallback")} script_path = f"u/admin/{unique_name(name_prefix)}" self._client.create_script( path=script_path, content=ts_script("return 'seed'"), language="bun", ) - self._client.wait_for_sync_jobs(initial_count, min_new=1) - time.sleep(3) + self._wait_until( + lambda: self._new_sync_jobs(seen, script_path), + timeout=90, + interval=2, + message=f"no push job for {script_path}", + ) + # TEMP-DIAG: would the old count-based wait have returned before our push? + ours = self._new_sync_jobs(seen, script_path) + ours_ids = {j["id"] for j in ours} + ours_done = min(j.get("completed_at") or "" for j in ours) + others = [ + (j["id"], j.get("completed_at"), (j.get("args") or {}).get("repo_url_resource_path")) + for j in self._client.get_completed_jobs(job_kinds="deploymentcallback") + if j["id"] not in seen and j["id"] not in ours_ids + and (j.get("completed_at") or "") < ours_done + ] + print(f"TEMP-DIAG seed={script_path} ours_done={ours_done} earlier_others={others}" + + (" RACE-HIT" if others else ""), flush=True) + failed = [j for j in self._new_sync_jobs(seen, script_path) if not j.get("success")] + self.assertEqual(failed, [], f"the push of {script_path} failed") return script_path def _repo_script_file(self, repo_name: str, script_path: str, branch: str = None) -> str: @@ -773,17 +814,7 @@ class TestGitSync(GitSyncTestBase): def _new_sync_job_results(self, seen: set, path: str) -> list: """Results of the deploy callbacks not in `seen` that pushed `path`.""" - results = [] - for listed in self._client.get_completed_jobs(job_kinds="deploymentcallback"): - if listed["id"] in seen: - continue - job = self._client._client.get( - f"/api/w/{self._client._workspace}/jobs_u/get/{listed['id']}" - ).json() - items = (job.get("args") or {}).get("items") or [] - if any(item.get("path") == path for item in items): - results.append(job.get("result")) - return results + return [job.get("result") for job in self._new_sync_jobs(seen, path)] def test_promotion_push_reports_whether_it_pushed(self): """The push job's result says whether a commit was pushed, and the diff --git a/lsp/Pipfile b/lsp/Pipfile index 07ee6af81d..ea0f102c49 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.839.0" +wmill = ">=1.840.0" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index 22935a127b..4fd1d4a5a6 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.839.0 + version: 1.840.0 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index 82ddf44583..29259c8a01 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.839.0' + ModuleVersion = '1.840.0' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index 0eb5369cd2..812b98244b 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.839.0" +version = "1.840.0" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index 5363053bd2..5b8c3cbe8c 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -4963,7 +4963,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 diff --git a/system_prompts/auto-generated/script.md b/system_prompts/auto-generated/script.md index 096cabab93..509e34d502 100644 --- a/system_prompts/auto-generated/script.md +++ b/system_prompts/auto-generated/script.md @@ -379,7 +379,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 diff --git a/system_prompts/auto-generated/skills/write-script-bunnative/SKILL.md b/system_prompts/auto-generated/skills/write-script-bunnative/SKILL.md index cc93c352c4..1c7c1294a6 100644 --- a/system_prompts/auto-generated/skills/write-script-bunnative/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-bunnative/SKILL.md @@ -124,7 +124,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 diff --git a/system_prompts/languages/bunnative.md b/system_prompts/languages/bunnative.md index af9055f01d..3d5e7bccbc 100644 --- a/system_prompts/languages/bunnative.md +++ b/system_prompts/languages/bunnative.md @@ -49,7 +49,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 diff --git a/typescript-client/client.ts b/typescript-client/client.ts index da957239cf..dbb667a3aa 100644 --- a/typescript-client/client.ts +++ b/typescript-client/client.ts @@ -137,7 +137,9 @@ export async function getResource( return undefined; } else { throw Error( - `Resource not found at ${path} or not visible to you: ${e.body}` + e.status === undefined + ? `Could not reach the Windmill API to get resource ${path}: ${e.message ?? e}` + : `Resource not found at ${path} or not visible to you: ${e.body}` ); } } @@ -831,7 +833,9 @@ export async function getVariable(path: string): Promise { return await VariableService.getVariableValue({ workspace, path }); } catch (e: any) { throw Error( - `Variable not found at ${path} or not visible to you: ${e.body}` + e.status === undefined + ? `Could not reach the Windmill API to get variable ${path}: ${e.message ?? e}` + : `Variable not found at ${path} or not visible to you: ${e.body}` ); } } diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 7cc0d733cb..8319cc8c7e 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.839.0", + "version": "1.840.0", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index 8c19be3caa..579a9d6f93 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.839.0", + "version": "1.840.0", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/version.txt b/version.txt index bb681c83bb..0b6baeaae9 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.839.0 +1.840.0 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index dbd79e917b..32d3eaf688 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.839.0", + "version": "1.840.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.839.0", + "version": "1.840.0", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index 02e880a4b0..105e7aff81 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.839.0", + "version": "1.840.0", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts",