diff --git a/.release-please-manifest.json b/.release-please-manifest.json index aa5035b0db..85fc5126b0 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.894.1" + ".": "1.895.1" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 4504f2122d..6938a8535f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog +## [1.895.1](https://github.com/windmill-labs/windmill/compare/v1.895.0...v1.895.1) (2026-12-02) + + +### Bug Fixes + +* reconnect GCP pull triggers whose streaming pull stops ([#12805](https://github.com/windmill-labs/windmill/issues/12805)) ([de40457](https://github.com/windmill-labs/windmill/commit/de40457c34de45037cfdd3eb89eac71d528156d4)) + +## [1.895.0](https://github.com/windmill-labs/windmill/compare/v1.894.1...v1.895.0) (2026-12-02) + + +### Features + +* count MCP token shapes and URLs, offer an upgrade ([#12782](https://github.com/windmill-labs/windmill/issues/12782)) ([f8e049d](https://github.com/windmill-labs/windmill/commit/f8e049d426de144c084f93cf334a229430a654d7)) +* let MCP clients see the images a run returns ([#12674](https://github.com/windmill-labs/windmill/issues/12674)) ([67e5de0](https://github.com/windmill-labs/windmill/commit/67e5de0892e10efcf1b384a80f9cd4935b5503df)) + + +### Bug Fixes + +* keep edited scopes of an MCP sign-in across token refreshes ([#12781](https://github.com/windmill-labs/windmill/issues/12781)) ([442ac5b](https://github.com/windmill-labs/windmill/commit/442ac5bfeb2c820d630c0b4a6f83d3717b2676df)) +* keep typographic quotes in powershell arguments ([#12780](https://github.com/windmill-labs/windmill/issues/12780)) ([9a3fd38](https://github.com/windmill-labs/windmill/commit/9a3fd388ec841f089449a33103d825804849228c)) +* let external jwt viewers render sandboxed apps ([#12807](https://github.com/windmill-labs/windmill/issues/12807)) ([e6dbc5d](https://github.com/windmill-labs/windmill/commit/e6dbc5dd7963dc9f41e53b477ead3ccaeb080b96)) +* load sandboxed raw apps behind a cookie-authenticated proxy ([#12787](https://github.com/windmill-labs/windmill/issues/12787)) ([9312b08](https://github.com/windmill-labs/windmill/commit/9312b08e9a2bb3a59d8235f0f60dafa47e4bb0c0)) +* read drafts in a folder just created through another token ([#12778](https://github.com/windmill-labs/windmill/issues/12778)) ([b0f7573](https://github.com/windmill-labs/windmill/commit/b0f7573a66876423e856ea96f606e4830a32d3c5)) +* render public apps unsandboxed for external jwt viewers ([#12806](https://github.com/windmill-labs/windmill/issues/12806)) ([f6c9f55](https://github.com/windmill-labs/windmill/commit/f6c9f55dfdcfe5d1d7557b3f3781fee87ab47089)) +* sign resume urls with a dedicated key ([#12797](https://github.com/windmill-labs/windmill/issues/12797)) ([994f9b8](https://github.com/windmill-labs/windmill/commit/994f9b8b27929538b0d3bc6f60bc2691b61dc089)) + ## [1.894.1](https://github.com/windmill-labs/windmill/compare/v1.894.0...v1.894.1) (2026-12-01) diff --git a/backend/.sqlx/query-0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002.json b/backend/.sqlx/query-0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002.json new file mode 100644 index 0000000000..040cd620cb --- /dev/null +++ b/backend/.sqlx/query-0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT name, (extra_perms ->> $2)::boolean AS \"grant\",\n $2 = ANY(owners) AS \"target_owner!\", NULL::text AS blocked\n FROM folder WHERE workspace_id = $1 ORDER BY name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "grant", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "target_owner!", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "blocked", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + null, + null, + null + ] + }, + "hash": "0ca9b2930531c353b953379061c7d6576977c5d7dac388a5d831c39a81076002" +} diff --git a/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json b/backend/.sqlx/query-15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7.json similarity index 53% rename from backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json rename to backend/.sqlx/query-15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7.json index b517bb1790..d442fa8e18 100644 --- a/backend/.sqlx/query-81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41.json +++ b/backend/.sqlx/query-15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\"\n FROM folder WHERE workspace_id = $1 AND name = ANY($2)", + "query": "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\",\n (extra_perms ->> $4)::boolean AS \"grant\"\n FROM folder WHERE workspace_id = $1 AND name = ANY($2)", "describe": { "columns": [ { @@ -12,19 +12,26 @@ "ordinal": 1, "name": "via!", "type_info": "TextArray" + }, + { + "ordinal": 2, + "name": "grant", + "type_info": "Bool" } ], "parameters": { "Left": [ "Text", "TextArray", - "TextArray" + "TextArray", + "Text" ] }, "nullable": [ false, + null, null ] }, - "hash": "81ed7bc2a02a9a535ce901e33984880fffdb7b2b91b678a6c315070d6fad7b41" + "hash": "15aa703d8684daadc959a0b04f8316f8f78ffa741edaaa7d94448bcc6836ffd7" } diff --git a/backend/.sqlx/query-9a4aaac681b1eeb2a718d7cd05170d05f559d20a91c15e0ca629dd882db5d4b8.json b/backend/.sqlx/query-9a4aaac681b1eeb2a718d7cd05170d05f559d20a91c15e0ca629dd882db5d4b8.json new file mode 100644 index 0000000000..b5f9ad9474 --- /dev/null +++ b/backend/.sqlx/query-9a4aaac681b1eeb2a718d7cd05170d05f559d20a91c15e0ca629dd882db5d4b8.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM v2_job j, _sqlx_migrations m\n WHERE j.id = $1 AND j.workspace_id = $2 AND m.version = $3\n AND j.created_at < m.installed_on + interval '1 day') AS \"accepted!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "accepted!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Int8" + ] + }, + "nullable": [ + null + ] + }, + "hash": "9a4aaac681b1eeb2a718d7cd05170d05f559d20a91c15e0ca629dd882db5d4b8" +} diff --git a/backend/.sqlx/query-a90e708b76103d064432f69a5b7395ed698b5249e3a6a0b1f31498b4cf6945ee.json b/backend/.sqlx/query-a90e708b76103d064432f69a5b7395ed698b5249e3a6a0b1f31498b4cf6945ee.json new file mode 100644 index 0000000000..37eaf198b8 --- /dev/null +++ b/backend/.sqlx/query-a90e708b76103d064432f69a5b7395ed698b5249e3a6a0b1f31498b4cf6945ee.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE mcp_oauth_refresh_token SET scopes = $1 WHERE access_token_hash = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "TextArray", + "Text" + ] + }, + "nullable": [] + }, + "hash": "a90e708b76103d064432f69a5b7395ed698b5249e3a6a0b1f31498b4cf6945ee" +} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 93b8caccba..f669d26928 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -828,7 +828,7 @@ checksum = "850b60ddcc664dcd848f8a2fa8436ab9336e051d6dd2b3f21f897dd8e9c24703" dependencies = [ "base64 0.22.1", "bytes", - "http 1.5.0", + "http 1.6.0", "rand 0.8.5", "reqwest 0.12.28", "serde", @@ -1007,7 +1007,7 @@ dependencies = [ "bytes", "fastrand 2.5.0", "hex", - "http 1.5.0", + "http 1.6.0", "ring 0.17.14", "time", "tokio", @@ -1082,7 +1082,7 @@ dependencies = [ "bytes", "bytes-utils", "fastrand 2.5.0", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "percent-encoding", "pin-project-lite", @@ -1109,7 +1109,7 @@ dependencies = [ "bytes", "fastrand 2.5.0", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "regex-lite", "tracing", ] @@ -1159,7 +1159,7 @@ dependencies = [ "bytes", "fastrand 2.5.0", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "regex-lite", "tracing", ] @@ -1185,7 +1185,7 @@ dependencies = [ "aws-types", "fastrand 2.5.0", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "regex-lite", "tracing", "url", @@ -1210,7 +1210,7 @@ dependencies = [ "bytes", "fastrand 2.5.0", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "regex-lite", "tracing", ] @@ -1234,7 +1234,7 @@ dependencies = [ "bytes", "fastrand 2.5.0", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "regex-lite", "tracing", ] @@ -1258,7 +1258,7 @@ dependencies = [ "bytes", "fastrand 2.5.0", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "regex-lite", "tracing", ] @@ -1282,7 +1282,7 @@ dependencies = [ "bytes", "fastrand 2.5.0", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "regex-lite", "tracing", ] @@ -1307,7 +1307,7 @@ dependencies = [ "aws-types", "fastrand 2.5.0", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "regex-lite", "tracing", ] @@ -1328,7 +1328,7 @@ dependencies = [ "hex", "hmac 0.12.1", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "percent-encoding", "sha2 0.10.9", "time", @@ -1371,7 +1371,7 @@ dependencies = [ "futures-core", "futures-util", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "http-body 0.4.6", "percent-encoding", "pin-project-lite", @@ -1391,7 +1391,7 @@ dependencies = [ "bytes-utils", "futures-core", "futures-util", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "http-body-util", "percent-encoding", @@ -1412,7 +1412,7 @@ dependencies = [ "h2 0.3.27", "h2 0.4.21", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "http-body 0.4.6", "hyper 0.14.32", "hyper 1.13.0", @@ -1482,7 +1482,7 @@ dependencies = [ "bytes", "fastrand 2.5.0", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "http-body 0.4.6", "http-body 1.1.0", "http-body-util", @@ -1502,7 +1502,7 @@ dependencies = [ "aws-smithy-types", "bytes", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "pin-project-lite", "tokio", "tracing", @@ -1520,7 +1520,7 @@ dependencies = [ "bytes-utils", "futures-core", "http 0.2.12", - "http 1.5.0", + "http 1.6.0", "http-body 0.4.6", "http-body 1.1.0", "http-body-util", @@ -1579,7 +1579,7 @@ dependencies = [ "bytes", "form_urlencoded", "futures-util", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "http-body-util", "hyper 1.13.0", @@ -1611,7 +1611,7 @@ checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" dependencies = [ "bytes", "futures-core", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "http-body-util", "mime", @@ -1959,7 +1959,7 @@ dependencies = [ "futures-core", "futures-util", "hex", - "http 1.5.0", + "http 1.6.0", "http-body-util", "hyper 1.13.0", "hyper-named-pipe", @@ -2195,9 +2195,15 @@ dependencies = [ [[package]] name = "byteorder" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" [[package]] name = "bytes" @@ -2564,6 +2570,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2550f75b8cfac212855f6b1885455df8eaee8fe8e246b647d69146142e016084" +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + [[package]] name = "colorchoice" version = "1.0.5" @@ -4137,7 +4149,7 @@ dependencies = [ "error_reporter", "h2 0.4.21", "hickory-resolver", - "http 1.5.0", + "http 1.6.0", "http-body-util", "hyper 1.13.0", "hyper-rustls 0.27.10", @@ -5401,6 +5413,15 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + [[package]] name = "ff" version = "0.13.1" @@ -6027,6 +6048,16 @@ dependencies = [ "polyval", ] +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + [[package]] name = "git-version" version = "0.3.9" @@ -6113,7 +6144,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "de13e62d7e0ffc3eb40a0113ddf753cf6ec741be739164442b08893db4f9bfca" dependencies = [ "google-cloud-token", - "http 1.5.0", + "http 1.6.0", "thiserror 1.0.69", "tokio", "tokio-retry2", @@ -6245,7 +6276,7 @@ dependencies = [ "fnv", "futures-core", "futures-sink", - "http 1.5.0", + "http 1.6.0", "indexmap 2.14.2", "slab", "tokio", @@ -6360,7 +6391,7 @@ dependencies = [ "base64 0.22.1", "bytes", "headers-core", - "http 1.5.0", + "http 1.6.0", "httpdate", "mime", "sha1", @@ -6372,7 +6403,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" dependencies = [ - "http 1.5.0", + "http 1.6.0", ] [[package]] @@ -6407,7 +6438,7 @@ checksum = "629d8f3bbeda9d148036d6b0de0a3ab947abd08ce90626327fc3547a49d59d97" dependencies = [ "dirs 6.0.0", "futures", - "http 1.5.0", + "http 1.6.0", "indicatif", "libc", "log", @@ -6550,9 +6581,9 @@ dependencies = [ [[package]] name = "http" -version = "1.5.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05" dependencies = [ "bytes", "itoa", @@ -6576,7 +6607,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", - "http 1.5.0", + "http 1.6.0", ] [[package]] @@ -6587,7 +6618,7 @@ checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "pin-project-lite", ] @@ -6613,7 +6644,7 @@ dependencies = [ "async-compression", "bstr", "futures", - "http 1.5.0", + "http 1.6.0", "http-body-util", "hyper 1.13.0", "hyper-rustls 0.26.0", @@ -6685,7 +6716,7 @@ dependencies = [ "futures-channel", "futures-core", "h2 0.4.21", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "httparse", "httpdate", @@ -6705,7 +6736,7 @@ dependencies = [ "bytes", "futures-util", "headers", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "hyper-rustls 0.27.10", "hyper-util", @@ -6752,7 +6783,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a0bea761b46ae2b24eb4aef630d8d1c398157b6fc29e6350ecf090a0b70c952c" dependencies = [ "futures-util", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "hyper-util", "log", @@ -6770,7 +6801,7 @@ version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "hyper-util", "log", @@ -6836,7 +6867,7 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "httparse", "hyper 1.13.0", @@ -7075,6 +7106,34 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd62e6b5e86ea8eeeb8db1de02880a6abc01a397b2ebb64b5d74ac255318f5cb" +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c8d2831f3eb9706eeac62164959a288f12c047a3c53b353c6c00d5d60eb5c7f" +dependencies = [ + "byteorder-lite", + "quick-error", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -7272,12 +7331,12 @@ dependencies = [ [[package]] name = "jiff" -version = "1.0.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f" +checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92" dependencies = [ - "jiff-core 1.0.2", - "jiff-static 1.0.3", + "jiff-core 1.1.0", + "jiff-static 1.1.0", "jiff-tzdb-platform 1.0.0", "log", "portable-atomic", @@ -7297,9 +7356,9 @@ dependencies = [ [[package]] name = "jiff-core" -version = "1.0.2" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f" +checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79" dependencies = [ "log", ] @@ -7318,11 +7377,11 @@ dependencies = [ [[package]] name = "jiff-static" -version = "1.0.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8" +checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3" dependencies = [ - "jiff-core 1.0.2", + "jiff-core 1.1.0", "proc-macro2", "quote", "syn 3.0.10", @@ -7596,7 +7655,7 @@ dependencies = [ "either", "futures", "home", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "http-body-util", "hyper 1.13.0", @@ -7630,7 +7689,7 @@ dependencies = [ "chrono", "derive_more 2.1.1", "form_urlencoded", - "http 1.5.0", + "http 1.6.0", "json-patch", "k8s-openapi", "schemars 0.8.22", @@ -8315,6 +8374,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", + "simd-adler32", ] [[package]] @@ -8380,6 +8440,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "multer" version = "3.1.0" @@ -8389,7 +8459,7 @@ dependencies = [ "bytes", "encoding_rs", "futures-util", - "http 1.5.0", + "http 1.6.0", "httparse", "memchr", "mime", @@ -8897,7 +8967,7 @@ dependencies = [ "base64 0.22.1", "chrono", "getrandom 0.2.17", - "http 1.5.0", + "http 1.6.0", "rand 0.8.5", "reqwest 0.12.28", "serde", @@ -8928,7 +8998,7 @@ dependencies = [ "chrono", "form_urlencoded", "futures", - "http 1.5.0", + "http 1.6.0", "http-body-util", "httparse", "humantime", @@ -9076,7 +9146,7 @@ dependencies = [ "ed25519-dalek 3.0.0", "getrandom 0.4.3", "hmac 0.12.1", - "http 1.5.0", + "http 1.6.0", "itertools 0.14.0", "log", "oauth2", @@ -9203,7 +9273,7 @@ checksum = "50f6639e842a97dbea8886e3439710ae463120091e2e064518ba8e716e6ac36d" dependencies = [ "async-trait", "bytes", - "http 1.5.0", + "http 1.6.0", "opentelemetry 0.30.0", "reqwest 0.12.28", ] @@ -9216,7 +9286,7 @@ checksum = "5683015d09e2df236ef005b17f6f196f0d5f6313c4fa43a7b6a53b52776e4331" dependencies = [ "async-trait", "bytes", - "http 1.5.0", + "http 1.6.0", "opentelemetry 0.32.0", ] @@ -9226,7 +9296,7 @@ version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dbee664a43e07615731afc539ca60c6d9f1a9425e25ca09c57bc36c87c55852b" dependencies = [ - "http 1.5.0", + "http 1.6.0", "opentelemetry 0.30.0", "opentelemetry-http 0.30.0", "opentelemetry-proto 0.30.0", @@ -9245,7 +9315,7 @@ version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9966929966d17620d7c316c643ba62631826e10021409357772d5eea84f62c35" dependencies = [ - "http 1.5.0", + "http 1.6.0", "opentelemetry 0.32.0", "opentelemetry-http 0.32.0", "opentelemetry-proto 0.32.0", @@ -10009,6 +10079,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "polling" version = "2.8.0" @@ -10467,6 +10550,18 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quick-xml" version = "0.37.5" @@ -11006,7 +11101,7 @@ dependencies = [ "futures-core", "futures-util", "h2 0.4.21", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "http-body-util", "hyper 1.13.0", @@ -11054,7 +11149,7 @@ dependencies = [ "futures-core", "futures-util", "h2 0.4.21", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "http-body-util", "hyper 1.13.0", @@ -11095,7 +11190,7 @@ checksum = "07bc3f1384cffa4f274dad2d4ddd73aed32fed8f786d96c6be8aa4e5fd3c3b58" dependencies = [ "anyhow", "async-trait", - "http 1.5.0", + "http 1.6.0", "reqwest 0.13.5", "serde", "thiserror 2.0.21", @@ -11112,7 +11207,7 @@ dependencies = [ "async-trait", "futures", "getrandom 0.2.17", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "reqwest 0.13.5", "reqwest-middleware", @@ -11237,7 +11332,7 @@ dependencies = [ "bytes", "chrono", "futures", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "http-body-util", "oauth2", @@ -12262,7 +12357,7 @@ dependencies = [ "indexmap 1.9.3", "indexmap 2.14.2", "jiff 0.2.46", - "jiff 1.0.3", + "jiff 1.1.0", "schemars 0.9.0", "schemars 1.2.3", "serde_core", @@ -14427,7 +14522,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", - "http 1.5.0", + "http 1.6.0", "httparse", "rand 0.8.5", "ring 0.17.14", @@ -14512,7 +14607,7 @@ dependencies = [ "base64 0.22.1", "bytes", "flate2", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "http-body-util", "hyper 1.13.0", @@ -14544,7 +14639,7 @@ dependencies = [ "bytes", "flate2", "h2 0.4.21", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "http-body-util", "hyper 1.13.0", @@ -14613,7 +14708,7 @@ dependencies = [ "axum-core", "cookie", "futures-util", - "http 1.5.0", + "http 1.6.0", "parking_lot", "pin-project-lite", "tower-layer", @@ -14632,7 +14727,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", - "http 1.5.0", + "http 1.6.0", "http-body 1.1.0", "http-body-util", "mime", @@ -14867,7 +14962,7 @@ dependencies = [ "byteorder", "bytes", "data-encoding", - "http 1.5.0", + "http 1.6.0", "httparse", "log", "native-tls", @@ -14889,7 +14984,7 @@ dependencies = [ "byteorder", "bytes", "data-encoding", - "http 1.5.0", + "http 1.6.0", "httparse", "log", "native-tls", @@ -15530,7 +15625,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "974fa1e325e6cc5327de8887f189a441fcff4f8eedcd31ec87f0ef0cc5283fbc" dependencies = [ "bytes", - "http 1.5.0", + "http 1.6.0", "thiserror 2.0.21", "url", ] @@ -15562,6 +15657,12 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + [[package]] name = "which" version = "4.4.2" @@ -15655,7 +15756,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-nats", @@ -15745,7 +15846,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.894.1" +version = "1.895.1" dependencies = [ "async-stream", "async-trait", @@ -15758,7 +15859,7 @@ dependencies = [ "bytes", "eventsource-stream", "futures", - "http 1.5.0", + "http 1.6.0", "indexmap 2.14.2", "lazy_static", "mime_guess", @@ -15780,7 +15881,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", @@ -15793,7 +15894,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "argon2", @@ -15821,8 +15922,10 @@ dependencies = [ "git-version", "hex", "hmac 0.12.1", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", + "image", + "image-webp", "indexmap 2.14.2", "itertools 0.14.0", "jsonwebtoken 10.4.0", @@ -15935,11 +16038,11 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "lazy_static", "quick_cache", @@ -15959,7 +16062,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", @@ -15976,12 +16079,12 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "axum", "chrono", - "http 1.5.0", + "http 1.6.0", "itertools 0.14.0", "jsonwebtoken 10.4.0", "lazy_static", @@ -16004,7 +16107,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.894.1" +version = "1.895.1" dependencies = [ "reqwest 0.12.28", "serde", @@ -16014,7 +16117,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", @@ -16031,7 +16134,7 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "base64 0.22.1", @@ -16053,7 +16156,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "axum", @@ -16076,7 +16179,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", @@ -16092,7 +16195,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", @@ -16114,7 +16217,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", @@ -16136,7 +16239,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", @@ -16150,7 +16253,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-nats", @@ -16186,13 +16289,13 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "axum", "base64 0.22.1", "chrono", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "lazy_static", "serde", @@ -16212,7 +16315,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", @@ -16240,11 +16343,11 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "axum", - "http 1.5.0", + "http 1.6.0", "indexmap 2.14.2", "itertools 0.14.0", "lazy_static", @@ -16262,7 +16365,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", @@ -16281,13 +16384,13 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "axum", "chrono", "futures", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "itertools 0.14.0", "lazy_static", @@ -16323,7 +16426,7 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "axum", @@ -16354,7 +16457,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.894.1" +version = "1.895.1" dependencies = [ "lazy_static", "serde", @@ -16366,14 +16469,14 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.894.1" +version = "1.895.1" dependencies = [ "argon2", "axum", "base32", "chrono", "hmac 0.12.1", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "lazy_static", "rand 0.9.5", @@ -16394,7 +16497,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", @@ -16409,14 +16512,14 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.894.1" +version = "1.895.1" dependencies = [ "axum", "chrono", "constant_time_eq 0.3.1", "futures", "hex", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "lazy_static", "magic-crypt", @@ -16448,7 +16551,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.894.1" +version = "1.895.1" dependencies = [ "chrono", "lazy_static", @@ -16463,7 +16566,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "axum", @@ -16482,7 +16585,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.894.1" +version = "1.895.1" dependencies = [ "aes-gcm", "aho-corasick", @@ -16519,7 +16622,7 @@ dependencies = [ "hex", "hkdf", "hmac 0.12.1", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "indexmap 2.14.2", "ipnet", @@ -16603,7 +16706,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.894.1" +version = "1.895.1" dependencies = [ "chrono", "futures", @@ -16623,7 +16726,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.894.1" +version = "1.895.1" dependencies = [ "regex", "serde", @@ -16640,7 +16743,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16667,7 +16770,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "futures", @@ -16684,7 +16787,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.894.1" +version = "1.895.1" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16700,13 +16803,13 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", "chrono", "futures", - "http 1.5.0", + "http 1.6.0", "oauth2", "reqwest 0.13.5", "rmcp", @@ -16722,7 +16825,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -16731,7 +16834,7 @@ dependencies = [ "base64 0.22.1", "chrono", "hmac 0.12.1", - "http 1.5.0", + "http 1.6.0", "itertools 0.14.0", "lazy_static", "reqwest 0.13.5", @@ -16754,7 +16857,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "arc-swap", @@ -16779,7 +16882,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-stream", @@ -16815,7 +16918,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "futures", @@ -16834,7 +16937,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.894.1" +version = "1.895.1" dependencies = [ "convert_case 0.6.0", "serde", @@ -16843,7 +16946,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -16855,7 +16958,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "serde_json", @@ -16867,7 +16970,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "gosyn", @@ -16879,7 +16982,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -16891,7 +16994,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "serde_json", @@ -16903,7 +17006,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "nu-parser", @@ -16914,7 +17017,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16925,7 +17028,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16937,7 +17040,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -16948,7 +17051,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-recursion", @@ -16971,7 +17074,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "serde_json", @@ -16983,7 +17086,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -16997,7 +17100,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -17014,7 +17117,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -17027,7 +17130,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "serde", @@ -17039,7 +17142,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -17057,7 +17160,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -17073,7 +17176,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -17090,7 +17193,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -17104,7 +17207,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-recursion", @@ -17142,7 +17245,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "const_format", @@ -17180,7 +17283,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.894.1" +version = "1.895.1" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17191,7 +17294,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-recursion", @@ -17201,7 +17304,7 @@ dependencies = [ "dashmap", "futures", "hex", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "lazy_static", "magic-crypt", @@ -17226,7 +17329,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -17250,13 +17353,13 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", "axum", "chrono", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "itertools 0.14.0", "lazy_static", @@ -17283,7 +17386,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -17310,7 +17413,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -17320,7 +17423,7 @@ dependencies = [ "chrono", "constant_time_eq 0.3.1", "hex", - "http 1.5.0", + "http 1.6.0", "itertools 0.14.0", "lazy_static", "quick_cache", @@ -17343,7 +17446,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -17363,7 +17466,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -17373,7 +17476,7 @@ dependencies = [ "chrono", "google-cloud-googleapis", "google-cloud-pubsub", - "http 1.5.0", + "http 1.6.0", "itertools 0.14.0", "jsonwebtoken 10.4.0", "lazy_static", @@ -17397,7 +17500,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -17408,7 +17511,7 @@ dependencies = [ "futures", "hex", "hmac 0.12.1", - "http 1.5.0", + "http 1.6.0", "hyper 1.13.0", "itertools 0.14.0", "lazy_static", @@ -17434,7 +17537,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -17457,7 +17560,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -17481,7 +17584,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-nats", @@ -17505,7 +17608,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -17540,7 +17643,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -17568,7 +17671,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-trait", @@ -17576,7 +17679,7 @@ dependencies = [ "base64 0.22.1", "chrono", "futures", - "http 1.5.0", + "http 1.6.0", "itertools 0.14.0", "serde", "serde_json", @@ -17594,7 +17697,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17614,7 +17717,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-once-cell", @@ -17732,7 +17835,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.894.1" +version = "1.895.1" dependencies = [ "bytes", "fs4", @@ -18703,3 +18806,18 @@ dependencies = [ "cc", "pkg-config", ] + +[[package]] +name = "zune-core" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1a65ee146f41cb456b005bc898af3ab1495ded4ee61ac3637103f40ccacac18" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 7cc8a60b12..63bfa6650e 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.894.1" +version = "1.895.1" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.894.1" +version = "1.895.1" authors = ["Ruben Fiszel "] edition = "2021" @@ -618,6 +618,8 @@ once_cell = "1.17.1" dashmap = "6.1.0" gosyn = "0.2.6" bytes = "1.4.0" +image = { version = "0.25.10", default-features = false, features = ["gif", "jpeg", "png", "webp"] } +image-webp = "0.2.4" gethostname = "0.4.3" # Not pinned exactly: the excluded `parsers/windmill-parser-wasm` workspace pins # =0.2.103 to match its vendored `cli/wasm/*` artifacts, yet path-depends on diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index a8a04a4e0c..c87dfd131e 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -84303c10a4d26410624ff5adc93d09ff8adc2f8a +3dc5c2c69dd2e690c78e15498093627447aaafcb diff --git a/backend/migrations/20261201163725_resume_signature_key.down.sql b/backend/migrations/20261201163725_resume_signature_key.down.sql new file mode 100644 index 0000000000..e0ac49d1ec --- /dev/null +++ b/backend/migrations/20261201163725_resume_signature_key.down.sql @@ -0,0 +1 @@ +SELECT 1; diff --git a/backend/migrations/20261201163725_resume_signature_key.up.sql b/backend/migrations/20261201163725_resume_signature_key.up.sql new file mode 100644 index 0000000000..abd80193bf --- /dev/null +++ b/backend/migrations/20261201163725_resume_signature_key.up.sql @@ -0,0 +1,3 @@ +-- No schema change: the `installed_on` of this migration dates the resume key on this instance (see +-- `RESUME_KEY_MIGRATION`). Do not edit, squash or re-record it, that would move the date. +SELECT 1; diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index f792a4eca6..b809f9007d 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.894.1" +version = "1.895.1" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.894.1" +version = "1.895.1" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.894.1" +version = "1.895.1" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.894.1" +version = "1.895.1" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index bdd04317ef..67abb17670 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.894.1" +version = "1.895.1" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/tests/access_view.rs b/backend/tests/access_view.rs index e3edf95494..40ca9c9773 100644 --- a/backend/tests/access_view.rs +++ b/backend/tests/access_view.rs @@ -1,5 +1,8 @@ //! Another member's access lists paths the caller may not be able to read, so only a workspace //! admin may ask for it. +//! +//! The auth cache is process-wide and keyed by workspace and token, so a test that gives +//! test-user-2 other groups or folders than another test does signs in with a token of its own. use sqlx::{Pool, Postgres}; @@ -64,3 +67,68 @@ async fn test_member_cannot_read_another_members_access(db: Pool) -> a Ok(()) } + +/// The navigator writes grants with the kind it is given, and `acls/add` sends a full-code app's +/// change to git sync only under `raw_app`. `blocked` must refuse what `acls/add` would refuse. +#[sqlx::test(fixtures("base"))] +async fn test_browse_items_kind_and_blocked(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + "INSERT INTO folder (workspace_id, name, display_name, owners, extra_perms, created_by) + VALUES ('test-workspace', 'fin', 'fin', '{u/test-user}', '{\"u/test-user-2\": false}', 'test-user'); + INSERT INTO app (id, workspace_id, path, summary, policy, versions, extra_perms) + VALUES (1, 'test-workspace', 'f/fin/dash', '', '{}', '{1}', '{}'); + INSERT INTO app_version (id, app_id, value, created_by, raw_app) + VALUES (1, 1, '{}', 'test-user', true); + INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256('BROWSE_TOKEN'::bytea), 'hex'), 'BROWSE_TOK', 'BROWSE_TOKEN', + 'test2@windmill.dev', 'browse', false);", + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let url = format!( + "http://localhost:{}/api/w/test-workspace/access/browse_items", + server.addr.port() + ); + let browse = |token: &str| { + reqwest::Client::new() + .get(&url) + .query(&[("principal", "u/test-user-2"), ("prefix", "f/fin/")]) + .header("Authorization", format!("Bearer {token}")) + .send() + }; + + let member: serde_json::Value = browse("BROWSE_TOKEN") + .await? + .error_for_status()? + .json() + .await?; + assert_eq!( + member["items"], + serde_json::json!([{ + "kind": "raw_app", + "path": "f/fin/dash", + "grant": null, + "blocked": "Only admins of the workspace or of f/fin can share it" + }]) + ); + + let admin: serde_json::Value = browse("SECRET_TOKEN") + .await? + .error_for_status()? + .json() + .await?; + assert_eq!(admin["items"][0]["blocked"], serde_json::Value::Null); + + // A mistyped principal is refused rather than listed as holding nothing. + let resp = reqwest::Client::new() + .get(&url) + .query(&[("principal", "g/does_not_exist")]) + .header("Authorization", "Bearer SECRET_TOKEN") + .send() + .await?; + assert_eq!(resp.status(), 404, "{}", resp.text().await?); + + Ok(()) +} diff --git a/backend/tests/app_render_ext_jwt_viewer.rs b/backend/tests/app_render_ext_jwt_viewer.rs new file mode 100644 index 0000000000..5c283afc42 --- /dev/null +++ b/backend/tests/app_render_ext_jwt_viewer.rs @@ -0,0 +1,154 @@ +//! A viewer authenticated by an external JWT (`jwt_ext_`) has no `usr` row, yet is a +//! member of the workspace its JWT names, so it keeps the publisher's unsandboxed +//! render. When the publisher isolates the app, its embed token must authenticate +//! without `usr`: a `token` row owned by the viewer's email never would, and the +//! embedded app would reload forever on 401s. +//! +//! The RSA keypair is a fixed test vector: `JWT_EXT_PUBLIC_KEY` is read once per +//! process, so it is set before the server first authenticates a `jwt_ext_` bearer. + +#![cfg(all(feature = "enterprise", feature = "private"))] + +use std::time::{SystemTime, UNIX_EPOCH}; + +use jsonwebtoken::{encode, Algorithm, EncodingKey, Header}; +use serde_json::json; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +const PRIV: &str = "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDW0+VQN2+bO2ZA\nlXLaJgDvOxWL8Yt8JAjKxtBuoEXm7LKSlTRY/5IXPtfNu5NowYu2fW+4KUh89mQ4\ngg4oV6V7kS2qOBEUC4ODkxyKfOOfu+n+uTiZufD+xelaw2AClBFw8vzCIdzZofUJ\n8GJS9UNdEtUSYqzngV2QObN/cgN50JRJtymsbzgioOkvExGZY9qFOCpxxtsMBa/H\n6mwXPpAM4dO4cZq77aLn9erBjgBL5KaYZoHjMOSoWRCcY9mdgXx/FoR34Sk0khVF\n1JFAz1jD83+Yh9Y/slzCD2DL/6+GHa1lNwpaKDsYAQythHItErnKKJqsaaxdqHqU\nLGMzkKmDAgMBAAECggEAIShc0SrH8R++l+Kj8tkWyoCbbMQqu/hxMEsgyf0MN6j6\nTvb0jiAJk8jr/3cfjiBWyM3yO8HeIbDYpdgns0ED67SWuxp4QwMb7hJQv2yoqB5A\nREP2YSklR02TckzhjsRShNUcVM0WjLNwt3NWLxO9V/+bdNZXdaFZUvTKUwttTz8C\ncpsn2+Xw97NJk+xho2T0ddLpgP7gHORQ8Hwa8xyEXHWWftCaTw/1i61JGO5c6BvX\ncTAAsGpdSBQXEskwNc6J6v4KtcbE71FQM5wtxjbLIkt3etzJAMwByFd9Fm6gvprv\nyxugvgqI/XxCmK2+ecO5YNyxCzPJy/Om/9ZBuQAugQKBgQD7dZvFYQeB7IaoG5yB\ncIPj/mq7pGGrtpdBOsUUR9kDKV4b2b0AB3+itsfra3YXQz7aKhy7DSCdzM/iz7sy\n/mnfKuLJm8CNDApWmQIZpj+TMWHUWaZPqQtLFnTVnbu/lYrMevKs6o62AgQaVH1i\n/kVHlXl/r5M0ASagT2l9CcXjYQKBgQDatPRN5T/wcikjA1nxOvr+6L5vBiSwSvoJ\nIUGZ5qjvE4z09BrwUnsCtxsmCQ1i3zmCEP/p9AkUgAVPtP9dcF8TJECtp1S6CVx6\n6Qu6z+nimUTW1bGYd3KMZ+XKa1Uml0cliF9/wxnbRJdBsLQAqxxlN2G7guHZs/PI\nVGMGth6bYwKBgHzXaeu3fXuyizQA6VWWH9Tcpe7c8KTItRVscRXdic85BYD8PAo8\nrtCAwIaPxoRMHXNAvxzaqpvNaFRp3720c6mZaBjB2/nqxWMy+cj0MdIJDVHY5Gne\nOj4gOwcnFWRLgSp9y+evWATiwVi1I783D/w3KKgM6h9ChwPGCVBLvtRhAoGBAJtl\n0+i9KW9JTl1odjHnPIx/B0CP1uXEgGCYVqppsEMfWxp5j+KOWIUXYZzm9bH49j2q\noouzL/h29k8qRgA4ZfWN3r8ElDkTibhzejgknwS47qbPc77nsGZ/NFFdbkVbW9wZ\nR/HZyLd5xxeP3HZVHnn0nebEGoG7UU5YV3xfTuQNAoGBALKl0/GGg8A52+pV/0z1\n4ZSaP0/wBBk6IKMHCLM+4/2hWoNMW8SndD8HYegJ9TunxOGhuC0sXC0r/fAJ3HF8\nAjtlFwVPfLONjHEWwOG8ll77K9jy5eBDL+csySOHqHI9wzIyxSzKg65uDkIiP0ni\ndOQkC+Yq6YYGhMoOQShezBfm\n-----END PRIVATE KEY-----\n"; +const PUB: &str = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1tPlUDdvmztmQJVy2iYA\n7zsVi/GLfCQIysbQbqBF5uyykpU0WP+SFz7XzbuTaMGLtn1vuClIfPZkOIIOKFel\ne5EtqjgRFAuDg5Mcinzjn7vp/rk4mbnw/sXpWsNgApQRcPL8wiHc2aH1CfBiUvVD\nXRLVEmKs54FdkDmzf3IDedCUSbcprG84IqDpLxMRmWPahTgqccbbDAWvx+psFz6Q\nDOHTuHGau+2i5/XqwY4AS+SmmGaB4zDkqFkQnGPZnYF8fxaEd+EpNJIVRdSRQM9Y\nw/N/mIfWP7Jcwg9gy/+vhh2tZTcKWig7GAEMrYRyLRK5yiiarGmsXah6lCxjM5Cp\ngwIDAQAB\n-----END PUBLIC KEY-----\n"; + +async fn create_app( + client: &reqwest::Client, + db: &Pool, + ws: &str, + path: &str, + sandbox: bool, +) -> anyhow::Result { + let resp = client + .post(format!("{ws}/apps/create")) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&json!({ + "path": path, + "summary": "Embedded with an external JWT", + "value": {}, + "policy": { "execution_mode": "publisher", "triggerables": {}, "sandbox": sandbox } + })) + .send() + .await?; + assert_eq!(resp.status(), 201, "{}", resp.text().await?); + // Read access through the group the JWT claims, as a publisher-mode app requires. + sqlx::query("UPDATE app SET extra_perms = '{\"g/all\": false}' WHERE path = $1") + .bind(path) + .execute(db) + .await?; + Ok(client + .get(format!("{ws}/apps/secret_of/{path}")) + .header("Authorization", "Bearer SECRET_TOKEN") + .send() + .await? + .text() + .await?) +} + +async fn get_json( + client: &reqwest::Client, + url: &str, + bearer: &str, +) -> anyhow::Result { + let resp = client + .get(url) + .header("Authorization", format!("Bearer {bearer}")) + .send() + .await?; + assert_eq!(resp.status(), 200, "{url}: {}", resp.text().await?); + Ok(resp.json().await?) +} + +#[sqlx::test(fixtures("base"))] +async fn ext_jwt_viewer_renders_embedded_apps(db: Pool) -> anyhow::Result<()> { + unsafe { std::env::set_var("JWT_EXT_PUBLIC_KEY", PUB) }; + initialize_tracing().await; + set_jwt_secret().await; + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + let client = reqwest::Client::new(); + let open_secret = create_app(&client, &db, &ws, "u/test-user/ext_jwt_open", false).await?; + let isolated_secret = + create_app(&client, &db, &ws, "u/test-user/ext_jwt_isolated", true).await?; + + let exp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() + 3600; + let jwt = encode( + &Header::new(Algorithm::RS256), + &json!({ + "email": "embedded@example.com", + "username": "embedded", + "is_admin": false, + "is_operator": false, + "groups": ["all"], + "folders": [], + "workspace_id": "test-workspace", + "exp": exp, + }), + &EncodingKey::from_rsa_pem(PRIV.as_bytes())?, + )?; + let viewer = format!("jwt_ext_{jwt}"); + + let body = get_json( + &client, + &format!("{ws}/apps_u/embed_token/{open_secret}"), + &viewer, + ) + .await?; + assert_eq!(body["sandbox"], json!(false), "{body}"); + assert!(body["token"].is_null(), "no embed token to mint: {body}"); + + let body = get_json( + &client, + &format!("{ws}/apps_u/embed_token/{isolated_secret}"), + &viewer, + ) + .await?; + assert_eq!(body["sandbox"], json!(true), "{body}"); + let embed = body["token"] + .as_str() + .expect("an isolated render gets a token"); + let expiration: chrono::DateTime = + serde_json::from_value(body["expiration"].clone())?; + assert!( + expiration.timestamp() <= exp as i64, + "capped on the viewer's JWT: {body}" + ); + let whoami = get_json(&client, &format!("{ws}/users/whoami"), embed).await?; + assert_eq!(whoami["email"], json!("embedded@example.com")); + get_json( + &client, + &format!("{ws}/apps_u/public_app/{isolated_secret}"), + embed, + ) + .await?; + // Held to the embed scopes: it cannot renew itself or reach another app. + for url in [ + format!("{ws}/apps_u/embed_token/{isolated_secret}"), + format!("{ws}/apps/get/p/u/test-user/ext_jwt_open"), + ] { + let status = client + .get(&url) + .header("Authorization", format!("Bearer {embed}")) + .send() + .await? + .status(); + assert!(status == 401 || status == 403, "{url}: {status}"); + } + + let tokens: i64 = sqlx::query_scalar("SELECT count(*) FROM token WHERE email = $1") + .bind("embedded@example.com") + .fetch_one(&db) + .await?; + assert_eq!(tokens, 0); + Ok(()) +} diff --git a/backend/tests/drafts_new_folder_read.rs b/backend/tests/drafts_new_folder_read.rs new file mode 100644 index 0000000000..a7ad63f7c9 --- /dev/null +++ b/backend/tests/drafts_new_folder_read.rs @@ -0,0 +1,54 @@ +//! A draft read in a folder the caller just created works at once, from any of their tokens. +//! +//! The AI session tools create the folder through one token (a JWT minted per tool call) and +//! read the draft through another, whose identity was cached before the folder existed. The +//! folder has no deployed item yet, so nothing but the caller's folder set can admit the read. + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn test_draft_read_in_folder_created_through_another_token( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::query( + "INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256('SECOND_TOKEN_2'::bytea), 'hex'), 'SECOND_TOK', 'SECOND_TOKEN_2', + 'test2@windmill.dev', 'second token', false)", + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let base = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + let client = reqwest::Client::new(); + let read = || { + client + .get(format!("{base}/drafts/get_own/script/f/fresh/hello")) + .header("Authorization", "Bearer SECOND_TOKEN_2") + .send() + }; + + // Caches the second token's identity, without the folder. + assert_eq!(read().await?.status(), 404); + + let resp = client + .post(format!("{base}/folders/create")) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .json(&json!({ "name": "fresh" })) + .send() + .await?; + assert!(resp.status().is_success(), "{}", resp.text().await?); + + let resp = read().await?; + let status = resp.status(); + let body = resp.text().await?; + assert_eq!(status, 200, "draft read in the new folder refused: {body}"); + assert_eq!(serde_json::from_str::(&body)?, Value::Null); + Ok(()) +} diff --git a/backend/tests/wac_approval_urls.rs b/backend/tests/wac_approval_urls.rs index 7883c69b17..ef8d00f6b1 100644 --- a/backend/tests/wac_approval_urls.rs +++ b/backend/tests/wac_approval_urls.rs @@ -289,7 +289,6 @@ async fn wac_concurrent_colliding_mints_admit_exactly_one( async fn resume_signatures_are_bound_to_the_run_and_its_workspace( db: Pool, ) -> anyhow::Result<()> { - use hmac::Mac; initialize_tracing().await; let server = ApiServer::start(db.clone()).await?; @@ -330,10 +329,12 @@ async fn resume_signatures_are_bound_to_the_run_and_its_workspace( } } - let mut mac = hmac::Hmac::::new_from_slice(b"test-key-2")?; - mac.update(uuid::Uuid::parse_str(WAC_JOB)?.as_bytes()); - mac.update(&5u32.to_be_bytes()); - let foreign = hex::encode(mac.finalize().into_bytes()); + let foreign = windmill_common::variables::resume_signature( + "test-key-2", + uuid::Uuid::parse_str(WAC_JOB)?, + 5, + None, + )?; for op in ["resume", "cancel"] { let status = client .post(format!( diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index 9362c3b9f1..86cd21adb2 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -206,8 +206,12 @@ impl AuthCache { } } - pub async fn invalidate(&self, w_id: &str, token: String) { - AUTH_CACHE.remove(&(w_id.to_string(), token)); + /// Drops every cached identity of `email`, whatever token it was resolved from. A change + /// to what the user can reach must reach all of them: the AI session tools act through a + /// JWT minted from the caller's cached identity, so the token presenting the change is + /// not the one that will present the next request. + pub fn invalidate_user(&self, email: &str) { + AUTH_CACHE.retain(|_, cached| cached.authed.email != email); } /// `client_ip` is the address of the request presenting `token` (`ClientIp`), `None` outside diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index c6efabac71..d541a57e3f 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -93,9 +93,10 @@ pub struct ApiAuthed { /// superadmin (`require_super_admin`), GHSA-hfh4-cx4h-3fcr. pub job_id: Option, /// When this credential itself expires, if it carries its own expiry rather than a - /// token row. Set for a guest JWT (its `exp`): a token minted from it is capped at - /// this, since the JWT's expiry is a guest's only revocation and there is no row to - /// look the limit up in. `None` for every credential whose limit lives in `token`. + /// token row. Set for a guest JWT and an external JWT (`jwt_ext_`), from its `exp`: a + /// token minted from either is capped at this, since there is no row to look the limit + /// up in, and an app's isolated render refuses to mint for an external JWT without it. + /// `None` for every credential whose limit lives in `token`. pub credential_expiry: Option>, /// The OAuth client of an external issuer acting for this user (`mcp_external_idp`). /// Recorded on the runs it starts and handed to their steps as `WM_MCP_CLIENT`. diff --git a/backend/windmill-api-groups/src/access.rs b/backend/windmill-api-groups/src/access.rs index 6fa159c008..9e790016e7 100644 --- a/backend/windmill-api-groups/src/access.rs +++ b/backend/windmill-api-groups/src/access.rs @@ -18,14 +18,20 @@ use windmill_api_auth::ApiAuthed; use windmill_common::{ auth::fetch_authed_from_permissioned_as, db::UserDB, - error::{Error, JsonResult}, + error::{Error, JsonResult, Result}, + workspaces::{check_operator_can_manage, ManageKind}, DB, }; pub fn workspaced_service() -> Router { - Router::new().route("/get", get(get_access)) + Router::new() + .route("/get", get(get_access)) + .route("/browse_folders", get(browse_folders)) + .route("/browse_items", get(browse_items)) } +const BROWSE_PAGE: i64 = 100; + /// `(kind, table, extra filter)`. Captures, capture configs and eval datasets are left out on /// purpose: they are test data attached to an item, not something access is granted to. const ITEM_TABLES: [(&str, &str, &str); 17] = [ @@ -74,6 +80,12 @@ struct FolderAccess { owner: bool, /// The `extra_perms` keys (`u/` or `g/`) that grant the folder. via: Vec, + /// The principal's own entry in `extra_perms`: absent when none, false for read, true for write. + #[serde(skip_serializing_if = "Option::is_none")] + grant: Option, + /// Why the caller cannot change the principal's own entry. Set only where there is one. + #[serde(skip_serializing_if = "Option::is_none")] + blocked: Option, } #[derive(Serialize)] @@ -82,6 +94,9 @@ struct ItemAccess { path: String, write: bool, reasons: Vec, + /// Why the caller cannot change the principal's own grant. Set only where there is one. + #[serde(skip_serializing_if = "Option::is_none")] + blocked: Option, } #[derive(Serialize)] @@ -112,12 +127,27 @@ struct ItemRow { folder_write: bool, } +/// The `kind` column for a row of `table`. Full-code apps live in `app` too, but their grants must +/// be written with kind `raw_app`, which git sync dispatches to `.raw_app` rather than `.app`. +fn kind_column(kind: &str, table: &str) -> String { + if kind == "app" { + format!( + "CASE WHEN (SELECT raw_app FROM app_version \ + WHERE id = {table}.versions[array_upper({table}.versions, 1)]) \ + THEN 'raw_app' ELSE 'app' END" + ) + } else { + format!("'{kind}'::text") + } +} + fn items_query() -> String { let union = ITEM_TABLES .iter() .map(|(kind, table, filter)| { + let kind = kind_column(kind, table); format!( - "SELECT '{kind}'::text AS kind, path::text AS path, extra_perms FROM {table} \ + "SELECT {kind} AS kind, path::text AS path, extra_perms FROM {table} \ WHERE workspace_id = $1 {filter}" ) }) @@ -175,20 +205,15 @@ impl From for ItemAccess { *write } }); - ItemAccess { kind: r.kind, path: r.path, write, reasons } + ItemAccess { kind: r.kind, path: r.path, write, reasons, blocked: None } } } -async fn get_access( - authed: ApiAuthed, - Extension(db): Extension, - Extension(user_db): Extension, - Path(w_id): Path, - Query(AccessQuery { principal }): Query, -) -> JsonResult { +/// Splits `u/` or `g/` and refuses callers who may not look at that principal. +fn check_principal<'a>(authed: &ApiAuthed, principal: &'a str) -> Result<(&'a str, &'a str)> { let (prefix, name) = principal .split_once('/') - .filter(|(_, name)| !name.is_empty()) + .filter(|(prefix, name)| matches!(*prefix, "u" | "g") && !name.is_empty()) .ok_or_else(|| Error::BadRequest("principal must be u/ or g/".into()))?; // Another principal's list names paths the caller may not be able to read. A group's reach is @@ -196,8 +221,7 @@ async fn get_access( let allowed = authed.is_admin || match prefix { "u" => name == authed.username, - "g" => authed.groups.iter().any(|g| g == name), - _ => false, + _ => authed.groups.iter().any(|g| g == name), }; if !allowed { return Err(Error::PermissionDenied( @@ -205,15 +229,36 @@ async fn get_access( .into(), )); } + Ok((prefix, name)) +} - let email = match prefix { +/// The principal as it would be authenticated, with its groups and the folders it reaches. +async fn fetch_target( + db: &DB, + w_id: &str, + prefix: &str, + name: &str, + principal: &str, +) -> Result { + let email = target_email(db, w_id, prefix, name).await?; + let mut target = fetch_authed_from_permissioned_as(principal, &email, w_id, db).await?; + // A workspace group and an instance group can share a name, and both come back. + target.groups.sort(); + target.groups.dedup(); + Ok(target) +} + +/// The principal's email, empty for a group. Not found when the principal does not exist, so +/// no route answers for a mistyped one as if it existed with no grants. +async fn target_email(db: &DB, w_id: &str, prefix: &str, name: &str) -> Result { + Ok(match prefix { "u" => { let usr = sqlx::query!( "SELECT email, disabled FROM usr WHERE workspace_id = $1 AND username = $2", - &w_id, + w_id, name ) - .fetch_optional(&db) + .fetch_optional(db) .await? .ok_or_else(|| Error::NotFound(format!("user {name} not found")))?; if usr.disabled { @@ -224,15 +269,15 @@ async fn get_access( usr.email } "g" => { - // Instance groups are granted through the same `g/` keys, and the check above + // Instance groups are granted through the same `g/` keys, and the callers' check // lets their members ask, so a name from either table is a group here. let exists = sqlx::query_scalar!( "SELECT EXISTS(SELECT 1 FROM group_ WHERE workspace_id = $1 AND name = $2) OR EXISTS(SELECT 1 FROM instance_group WHERE name = $2)", - &w_id, + w_id, name ) - .fetch_one(&db) + .fetch_one(db) .await? .unwrap_or(false); if !exists { @@ -245,12 +290,19 @@ async fn get_access( "principal must be u/ or g/".into(), )) } - }; + }) +} - let mut target = fetch_authed_from_permissioned_as(&principal, &email, &w_id, &db).await?; - // A workspace group and an instance group can share a name, and both come back. - target.groups.sort(); - target.groups.dedup(); +async fn get_access( + authed: ApiAuthed, + Extension(db): Extension, + Extension(user_db): Extension, + Path(w_id): Path, + Query(AccessQuery { principal }): Query, +) -> JsonResult { + let (prefix, name) = check_principal(&authed, &principal)?; + + let target = fetch_target(&db, &w_id, prefix, name, &principal).await?; if target.is_admin { return Ok(Json(AccessReport { @@ -276,38 +328,54 @@ async fn get_access( .map(|f| f.0.clone()) .collect::>(); let mut via = sqlx::query!( - "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\" + "SELECT name, ARRAY(SELECT k FROM jsonb_object_keys(extra_perms) k WHERE k = ANY($3) ORDER BY k) AS \"via!\", + (extra_perms ->> $4)::boolean AS \"grant\" FROM folder WHERE workspace_id = $1 AND name = ANY($2)", &w_id, &folder_names, - &perms + &perms, + &principal ) .fetch_all(&db) .await? .into_iter() - .map(|r| (r.name, r.via)) + .map(|r| (r.name, (r.via, r.grant))) .collect::>(); let mut folders = target .folders .iter() - .map(|(name, write, owner)| FolderAccess { - name: name.clone(), - write: *write, - owner: *owner, - via: via.remove(name).unwrap_or_default(), + .map(|(name, write, owner)| { + let (via, grant) = via.remove(name).unwrap_or_default(); + // An owner keeps write whatever its entry says, so there is nothing to change. + let blocked = + (grant.is_some() && !*owner && !windmill_api_auth::is_owner(&authed, name)) + .then(|| folder_blocked(name)); + FolderAccess { name: name.clone(), write: *write, owner: *owner, via, grant, blocked } }) .collect::>(); folders.sort_by(|a, b| a.name.cmp(&b.name)); let mut tx = user_db.begin(&target).await?; - let items = sqlx::query_as::<_, ItemRow>(&items_query()) + let rows = sqlx::query_as::<_, ItemRow>(&items_query()) .bind(&w_id) .fetch_all(&mut *tx) - .await? - .into_iter() - .map(ItemAccess::from) - .collect(); + .await?; tx.commit().await?; + let denied = manage_denied(&db, &w_id, &authed).await?; + let items = rows + .into_iter() + .map(|r| { + let direct = match prefix { + "u" => r.user_grant.is_some(), + _ => r.group_read.iter().any(|g| g == name), + }; + let mut item = ItemAccess::from(r); + if direct { + item.blocked = item_blocked(&authed, &denied, &item.kind, &item.path); + } + item + }) + .collect(); Ok(Json(AccessReport { principal, @@ -317,3 +385,204 @@ async fn get_access( items, })) } + +#[derive(Serialize)] +struct BrowseFolder { + name: String, + /// The principal's own entry in the folder's `extra_perms`: absent, read (false) or write. + grant: Option, + /// Owners always keep write; `acls/add` refuses to lower it. + target_owner: bool, + #[serde(skip_serializing_if = "Option::is_none")] + blocked: Option, +} + +#[derive(Serialize, sqlx::FromRow)] +struct BrowseItem { + kind: String, + path: String, + grant: Option, + #[sqlx(skip)] + #[serde(skip_serializing_if = "Option::is_none")] + blocked: Option, +} + +#[derive(Serialize)] +struct BrowseItems { + items: Vec, + has_more: bool, +} + +#[derive(Deserialize)] +struct BrowseItemsQuery { + principal: String, + /// Only paths starting with this, e.g. `f/billing/` or `u/alice/`. + prefix: Option, + kind: Option, + search: Option, + offset: Option, +} + +/// Why the caller cannot change grants on `path`, mirroring the checks `acls/add` makes. +fn grant_blocked(authed: &ApiAuthed, path: &str) -> Option { + if authed.is_admin { + return None; + } + let mut parts = path.splitn(3, '/'); + match (parts.next(), parts.next()) { + (Some("u"), Some(owner)) if owner == authed.username => None, + (Some("u"), Some(owner)) => { + Some(format!("Only u/{owner} and workspace admins can share it")) + } + (Some("f"), Some(folder)) if windmill_api_auth::is_owner(authed, folder) => None, + (Some("f"), Some(folder)) => Some(folder_blocked(folder)), + _ => Some("Only workspace admins can share items under g/".to_string()), + } +} + +fn folder_blocked(folder: &str) -> String { + format!("Only admins of the workspace or of f/{folder} can share it") +} + +async fn browse_folders( + authed: ApiAuthed, + Extension(db): Extension, + Extension(user_db): Extension, + Path(w_id): Path, + Query(AccessQuery { principal }): Query, +) -> JsonResult> { + let (prefix, name) = check_principal(&authed, &principal)?; + // Ownership can come through one of the principal's groups, as in `/access/get`. + let target = fetch_target(&db, &w_id, prefix, name, &principal).await?; + let owned = target + .folders + .iter() + .filter(|(_, _, owner)| *owner) + .map(|(name, ..)| name.as_str()) + .collect::>(); + let mut tx = user_db.begin(&authed).await?; + let mut folders = sqlx::query_as!( + BrowseFolder, + "SELECT name, (extra_perms ->> $2)::boolean AS \"grant\", + $2 = ANY(owners) AS \"target_owner!\", NULL::text AS blocked + FROM folder WHERE workspace_id = $1 ORDER BY name", + &w_id, + &principal + ) + .fetch_all(&mut *tx) + .await?; + tx.commit().await?; + for folder in &mut folders { + folder.target_owner |= owned.contains(folder.name.as_str()); + if !windmill_api_auth::is_owner(&authed, &folder.name) { + folder.blocked = Some(folder_blocked(&folder.name)); + } + } + Ok(Json(folders)) +} + +async fn browse_items( + authed: ApiAuthed, + Extension(db): Extension, + Extension(user_db): Extension, + Path(w_id): Path, + Query(q): Query, +) -> JsonResult { + let (prefix, name) = check_principal(&authed, &q.principal)?; + target_email(&db, &w_id, prefix, name).await?; + let tables = ITEM_TABLES + .iter() + .filter(|(kind, ..)| { + q.kind + .as_deref() + .map_or(true, |k| k == *kind || (k == "raw_app" && *kind == "app")) + }) + .collect::>(); + if tables.is_empty() { + return Err(Error::BadRequest("unknown kind".into())); + } + // SAFETY: table names and filters come from the `ITEM_TABLES` constant, never from the request. + let union = tables + .iter() + .map(|(kind, table, filter)| { + let kind = kind_column(kind, table); + format!( + "SELECT {kind} AS kind, path::text AS path, (extra_perms ->> $2)::boolean AS \"grant\" + FROM {table} WHERE workspace_id = $1 {filter}" + ) + }) + .collect::>() + .join(" UNION ALL "); + let sql = format!( + "SELECT kind, path, \"grant\" FROM ({union}) i + WHERE ($3::text IS NULL OR starts_with(path, $3)) + AND ($4::text IS NULL OR strpos(lower(path), lower($4)) > 0) + AND ($7::text IS NULL OR kind = $7) + ORDER BY path, kind LIMIT $5 OFFSET $6" + ); + let mut tx = user_db.begin(&authed).await?; + let mut items = sqlx::query_as::<_, BrowseItem>(&sql) + .bind(&w_id) + .bind(&q.principal) + .bind(q.prefix.as_deref().filter(|p| !p.is_empty())) + .bind(q.search.as_deref().map(str::trim).filter(|s| !s.is_empty())) + .bind(BROWSE_PAGE + 1) + .bind(q.offset.unwrap_or(0).max(0)) + .bind(q.kind.as_deref()) + .fetch_all(&mut *tx) + .await?; + tx.commit().await?; + let has_more = items.len() as i64 > BROWSE_PAGE; + items.truncate(BROWSE_PAGE as usize); + + let denied = manage_denied(&db, &w_id, &authed).await?; + for item in &mut items { + item.blocked = item_blocked(&authed, &denied, &item.kind, &item.path); + } + Ok(Json(BrowseItems { items, has_more })) +} + +/// Operators may be barred from managing schedules and triggers, `/acls` included. +/// Only a refusal becomes a lock text; any other error (the role lookup failing) is returned, so +/// an outage is not shown as a decision. +async fn manage_denied( + db: &DB, + w_id: &str, + authed: &ApiAuthed, +) -> Result> { + let mut denied = vec![]; + if !authed.is_admin { + for kind in [ManageKind::Schedules, ManageKind::Triggers] { + match check_operator_can_manage(db, w_id, authed, kind).await { + Ok(()) => {} + // A plain sentence like the path rules' texts, so without the "Permission + // denied: " prefix the error's display adds. + Err(Error::PermissionDenied(reason)) => denied.push((kind, reason)), + Err(e) => return Err(e), + } + } + } + Ok(denied) +} + +/// Why the caller cannot change grants on this item: the operator gate first, then the path. +fn item_blocked( + authed: &ApiAuthed, + denied: &[(ManageKind, String)], + kind: &str, + path: &str, +) -> Option { + let manage_kind = match kind { + "schedule" => Some(ManageKind::Schedules), + k if k.ends_with("_trigger") => Some(ManageKind::Triggers), + _ => None, + }; + manage_kind + .and_then(|mk| { + denied + .iter() + .find(|(k, _)| *k == mk) + .map(|(_, e)| e.clone()) + }) + .or_else(|| grant_blocked(authed, path)) +} diff --git a/backend/windmill-api-groups/src/folders.rs b/backend/windmill-api-groups/src/folders.rs index ddf121b4d8..36a26f9cd1 100644 --- a/backend/windmill-api-groups/src/folders.rs +++ b/backend/windmill-api-groups/src/folders.rs @@ -17,7 +17,7 @@ use lazy_static::lazy_static; use regex::Regex; use windmill_api_auth::{ build_scope_path_filter, build_scope_path_predicate, check_scopes, ApiAuthed, AuthCache, - ScopePathFilter, Tokened, + ScopePathFilter, }; use windmill_audit::audit_oss::{audit_log, AuditAuthorable}; use windmill_audit::ActionKind; @@ -263,7 +263,6 @@ lazy_static! { async fn create_folder( authed: ApiAuthed, - Tokened { token }: Tokened, Extension(db): Extension, Extension(user_db): Extension, Extension(webhook): Extension, @@ -295,7 +294,6 @@ async fn create_folder( ))); } check_name_conflict(&mut tx, &w_id, &ng.name).await?; - cache.invalidate(&w_id, token).await; let owner = username_to_permissioned_as(&authed.username); let owners = ng.owners.unwrap_or_else(|| vec![owner.clone()]); let owners = if owners.contains(&owner) { @@ -394,6 +392,8 @@ async fn create_folder( .await?; tx.commit().await?; + // After the commit: a request resolving the identity in between would cache the old folders. + cache.invalidate_user(&authed.email); handle_deployment_metadata( &authed.email, diff --git a/backend/windmill-api-integration-tests/tests/mcp_oauth_token_delete.rs b/backend/windmill-api-integration-tests/tests/mcp_oauth_token_delete.rs index e2acea3869..c5078cdeb7 100644 --- a/backend/windmill-api-integration-tests/tests/mcp_oauth_token_delete.rs +++ b/backend/windmill-api-integration-tests/tests/mcp_oauth_token_delete.rs @@ -1,5 +1,6 @@ //! Deleting an MCP OAuth access token revokes its refresh grant, and only that one; an access //! token removed by the expiry sweep keeps its grant refreshable, until its user is disabled. +//! Editing an access token's scopes holds across refreshes. #![cfg(feature = "mcp")] use serde_json::json; @@ -110,6 +111,27 @@ async fn test_deleted_mcp_token_cannot_refresh(db: Pool) -> anyhow::Re "invalid_grant" ); + let (edited_client, edited_access, edited_refresh) = connect("SECRET_TOKEN").await?; + // The last two leave the access token unrestricted, which the grant must not become. + for scopes in [json!(["mcp:all", "mcp:read_only"]), json!([]), json!(null)] { + let resp = http + .post(format!( + "{base}/users/tokens/update_scopes/{}", + &edited_access[..10] + )) + .bearer_auth("SECRET_TOKEN") + .json(&json!({ "scopes": scopes })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + } + let resp = refresh(&edited_client, &edited_refresh).await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + assert_eq!( + resp.json::().await?["scope"], + "mcp:all mcp:read_only" + ); + expire_and_sweep(idle_access).await?; let resp = refresh(&idle_client, &idle_refresh).await?; assert_eq!(resp.status(), 200, "{}", resp.text().await?); diff --git a/backend/windmill-api-integration-tests/tests/resume_signatures.rs b/backend/windmill-api-integration-tests/tests/resume_signatures.rs new file mode 100644 index 0000000000..76494c52f8 --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/resume_signatures.rs @@ -0,0 +1,103 @@ +use hmac::{Hmac, Mac}; +use sha2::Sha256; +use sqlx::{Pool, Postgres}; +use uuid::Uuid; +use windmill_test_utils::*; + +/// A suspended flow created `days` after now. +async fn suspended_flow(db: &Pool, id: Uuid, days: i32) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, kind, tag, args, created_at) + VALUES ($1, 'test-workspace', 'test-user', 'u/test-user', 'flow', 'flow', '{}'::jsonb, + now() + make_interval(days => $2))", + ) + .bind(id) + .bind(days) + .execute(db) + .await?; + sqlx::query( + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, tag, running, suspend) + VALUES ($1, 'test-workspace', now(), 'flow', true, 1)", + ) + .bind(id) + .execute(db) + .await?; + Ok(()) +} + +/// A signature made with the bare workspace key, which the fixture sets to `test-key`. +fn bare_key_signature(job: Uuid, tail: &[u8]) -> String { + let mut mac = Hmac::::new_from_slice(b"test-key").unwrap(); + mac.update(job.as_bytes()); + mac.update(tail); + hex::encode(mac.finalize().into_bytes()) +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn resume_signatures_have_their_own_key(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + let client = reqwest::Client::new(); + let resume = async |job: Uuid, resume_id: u32, sig: &str, approver: &str| { + client + .post(format!("{base}/jobs_u/resume/{job}/{resume_id}/{sig}")) + .query(&[("approver", approver)]) + .json(&serde_json::json!({})) + .send() + .await + .unwrap() + .status() + .as_u16() + }; + + // The layouts of the other messages the workspace key signs are not resume signatures. + for (job_prefix, tail) in [ + ("", "view_token"), + ("", "public_view_token"), + ("", "approval_token"), + ("file_key=0123456", "789&exp=4102444800"), + ("test-workspace:n", "extcloud:1:nonce:user"), + ("wm-fork-test:nex", "tcloud:1:nonce:user"), + ("test-workspace:g", "oogle:1:nonce"), + ("test-workspace:G", "oogle:1:nonce:path:user"), + ] { + let job = Uuid::from_slice(job_prefix.as_bytes()).unwrap_or_else(|_| Uuid::new_v4()); + suspended_flow(&db, job, 0).await?; + let sig = bare_key_signature(job, tail.as_bytes()); + let (resume_id, approver) = tail.split_at(4); + let resume_id = u32::from_be_bytes(resume_id.as_bytes().try_into()?); + assert!( + resume(job, resume_id, &sig, approver).await >= 400, + "{job_prefix}{tail}" + ); + } + + // Bare-key URLs already handed out keep working; a job created more than a day after the resume + // key migration (which has just run here) only takes the new ones. + for (days, takes_bare_key) in [(0, true), (2, false)] { + let job = Uuid::new_v4(); + suspended_flow(&db, job, days).await?; + let bare = bare_key_signature(job, b"\0\0\0\x01bob"); + assert_eq!(resume(job, 1, &bare, "bob").await == 201, takes_bare_key); + + let job = Uuid::new_v4(); + suspended_flow(&db, job, days).await?; + let sig = client + .get(format!("{base}/jobs/job_signature/{job}/1?approver=bob")) + .bearer_auth("SECRET_TOKEN") + .send() + .await? + .error_for_status()? + .text() + .await?; + assert_ne!(sig, bare_key_signature(job, b"\0\0\0\x01bob")); + assert_eq!(resume(job, 1, &sig, "bob").await, 201); + } + + server.close().await?; + Ok(()) +} diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index 4dab6a6e65..72b19748aa 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -4629,6 +4629,21 @@ async fn update_token_scopes( ) .execute(&mut *tx) .await?; + // A refresh re-issues the grant's scopes. A grant is never left unrestricted, which an empty + // list is too: it keeps its own scopes then. + let restricted = req + .scopes + .as_deref() + .filter(|s| !windmill_api_auth::is_effectively_unscoped(Some(s))); + if let Some(scopes) = restricted { + sqlx::query!( + "UPDATE mcp_oauth_refresh_token SET scopes = $1 WHERE access_token_hash = $2", + scopes, + &token.token_hash, + ) + .execute(&mut *tx) + .await?; + } let prefix = token_prefix; let scopes_json = serde_json::to_string(&req.scopes).unwrap_or_default(); diff --git a/backend/windmill-api/Cargo.toml b/backend/windmill-api/Cargo.toml index 5d6229b892..d44b78c2fd 100644 --- a/backend/windmill-api/Cargo.toml +++ b/backend/windmill-api/Cargo.toml @@ -48,7 +48,7 @@ sqs_trigger = ["dep:windmill-trigger-sqs", "windmill-store/sqs_trigger"] gcp_trigger = ["dep:windmill-trigger-gcp", "windmill-store/gcp_trigger"] azure_trigger = ["dep:windmill-trigger-azure", "windmill-store/azure_trigger"] cloud = ["windmill-common/cloud", "windmill-api-auth/cloud", "windmill-store/cloud", "windmill-api-workspaces/cloud"] -mcp = ["dep:windmill-mcp", "windmill-mcp/server", "windmill-mcp/auth", "windmill-api-auth/mcp", "windmill-store/mcp"] +mcp = ["dep:windmill-mcp", "dep:image", "dep:image-webp", "windmill-mcp/server", "windmill-mcp/auth", "windmill-api-auth/mcp", "windmill-store/mcp"] bedrock = ["windmill-ai/bedrock"] python = ["windmill-dep-map/python", "dep:windmill-parser-py", "dep:windmill-parser-py-imports", "windmill-api-scripts/python", "windmill-api-configs/python", "windmill-api-agent-workers?/python", "windmill-trigger/python", "windmill-common/python"] no_auth = ["windmill-api-auth/no_auth", "windmill-store/no_auth", "windmill-api-users/no_auth"] @@ -107,6 +107,8 @@ chrono.workspace = true hex.workspace = true base64.workspace = true base32.workspace = true +image = { workspace = true, optional = true } +image-webp = { workspace = true, optional = true } serde_urlencoded.workspace = true serde_yml.workspace = true cron.workspace = true diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 69ae832125..6a6e43152a 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.894.1 + version: 1.895.1 title: Windmill API contact: @@ -30,6 +30,10 @@ paths: /version: get: summary: get backend version + description: | + The edition and version (e.g. `EE v1.893.0`) for an authenticated caller. Without + credentials it answers 200 with the edition alone (`EE` or `CE`), so it stays usable as a + liveness probe. operationId: backendVersion tags: - settings @@ -26899,6 +26903,102 @@ paths: schema: $ref: "#/components/schemas/PrincipalAccess" + /w/{workspace}/access/browse_folders: + get: + summary: list the folders the caller can read, with the principal's direct grant on each + operationId: browseAccessFolders + tags: + - granular_acl + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: principal + description: "`u/` or `g/`" + in: query + required: true + schema: + type: string + responses: + "200": + description: folders + content: + application/json: + schema: + type: array + items: + type: object + properties: + name: + type: string + grant: + description: the principal's entry in the folder's extra_perms; absent when none, false for read, true for write + type: boolean + nullable: true + target_owner: + type: boolean + blocked: + description: why the caller cannot change this grant + type: string + required: [name, target_owner] + + /w/{workspace}/access/browse_items: + get: + summary: list items the caller can read, with the principal's direct grant on each + operationId: browseAccessItems + tags: + - granular_acl + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: principal + description: "`u/` or `g/`" + in: query + required: true + schema: + type: string + - name: prefix + description: only paths starting with this, e.g. `f/billing/` + in: query + schema: + type: string + - name: kind + in: query + schema: + type: string + - name: search + in: query + schema: + type: string + - name: offset + in: query + schema: + type: integer + responses: + "200": + description: a page of 100 items + content: + application/json: + schema: + type: object + properties: + items: + type: array + items: + type: object + properties: + kind: + type: string + path: + type: string + grant: + type: boolean + nullable: true + blocked: + description: why the caller cannot change this grant + type: string + required: [kind, path] + has_more: + type: boolean + required: [items, has_more] + /w/{workspace}/acls/get/{kind}/{path}: get: summary: get granular acls @@ -39539,6 +39639,12 @@ components: type: array items: type: string + grant: + description: the principal's own entry on the folder; absent when none, false for read, true for write + type: boolean + blocked: + description: why the caller cannot change the principal's own entry; set only where there is one + type: string required: [name, write, owner, via] items: type: array @@ -39555,6 +39661,9 @@ components: type: array items: $ref: "#/components/schemas/AccessReason" + blocked: + description: why the caller cannot change the principal's own grant; set only where there is one + type: string required: [kind, path, write, reasons] required: [principal, is_admin, groups, folders, items] diff --git a/backend/windmill-api/src/ai_session_tools/gen/tools.json b/backend/windmill-api/src/ai_session_tools/gen/tools.json index 4435b8c09d..d3fe4a5e14 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/tools.json +++ b/backend/windmill-api/src/ai_session_tools/gen/tools.json @@ -2707,7 +2707,7 @@ }, { "name": "read_s3_file", - "description": "Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text or JSON file, the columns, their types and the first 50 rows of a CSV, TSV, NDJSON or Parquet file, or the image itself for a png, jpeg, gif or webp of up to 3.75 MB, which you then see. Other files return their metadata only.", + "description": "Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text or JSON file, the columns, their types and the first 50 rows of a CSV, TSV, NDJSON or Parquet file, or the image itself for a png, jpeg, gif or webp of up to 30 MB, which you then see (one past 3.75 MB or 8000 px comes as a smaller JPEG copy). Other files return their metadata only.", "parameters": { "type": "object", "properties": { diff --git a/backend/windmill-api/src/ai_session_tools/images.rs b/backend/windmill-api/src/ai_session_tools/images.rs new file mode 100644 index 0000000000..833d5af252 --- /dev/null +++ b/backend/windmill-api/src/ai_session_tools/images.rs @@ -0,0 +1,382 @@ +//! Image files handed to an MCP client's model: a file within the limits as it is, a file past +//! them as a JPEG copy, and why an image is left out. Which results are images is `runs.rs`'s. + +use std::time::Duration; + +use tokio::sync::{Semaphore, SemaphorePermit}; + +use super::ToolImage; + +/// The largest image handed to the model, in bytes. Its base64 is at most 5,000,000 +/// characters: the 5 MB per image that Claude takes on Amazon Bedrock, the lowest of its +/// platforms (the Claude API takes 10 MB). +pub(super) const MAX_IMAGE_BYTES: usize = 3_750_000; +/// The largest file read to be copied, and its base64 in characters. +pub(super) const MAX_SOURCE_BYTES: usize = 30_000_000; +pub(super) const MAX_SOURCE_CHARS: usize = MAX_SOURCE_BYTES / 3 * 4; + +/// A server reads this many images at once, from the read of a file to the end of its copy: +/// each holds its file, up to 30 MB, and decoding the largest peaks at about 200 MB. A call +/// that waits longer than `READ_WAIT` leaves its image out rather than queue. +static READ_SLOTS: Semaphore = Semaphore::const_new(2); +const READ_WAIT: Duration = Duration::from_secs(5); + +pub(super) type ReadSlot = SemaphorePermit<'static>; + +pub(super) async fn read_slot() -> Result { + match tokio::time::timeout(READ_WAIT, READ_SLOTS.acquire()).await { + Ok(Ok(slot)) => Ok(slot), + _ => Err(Unattached { + key: "busy", + why: "the server is busy reading other images, call the tool again".to_string(), + }), + } +} + +/// An image as the model is handed it, and for a file past the limits, the copy it is. +#[cfg_attr(not(feature = "mcp"), allow(dead_code))] +pub(super) struct Attachment { + pub image: ToolImage, + pub copy: Option, +} + +/// Why an image is left out of an answer: what the model reads, and the `feature_usage` +/// key it counts under. +#[derive(Debug)] +pub(super) struct Unattached { + pub key: &'static str, + pub why: String, +} + +pub(super) fn too_large() -> Unattached { + let why = format!("larger than {} MB", MAX_SOURCE_BYTES as f64 / 1e6); + Unattached { key: "too_large", why } +} + +pub(super) fn not_image(why: &str) -> Unattached { + Unattached { key: "not_image", why: why.to_string() } +} + +pub(super) fn unreadable(why: String) -> Unattached { + Unattached { key: "unreadable", why } +} + +/// An image of a result's base64, `slot` held when its read took one. +pub(super) async fn decode_inline_image( + data: &str, + slot: Option, +) -> Result { + use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD}; + use base64::Engine; + let data: String = data.chars().filter(|c| !matches!(c, '\n' | '\r')).collect(); + let bytes = STANDARD + .decode(&data) + .or_else(|_| STANDARD_NO_PAD.decode(&data)) + .map_err(|_| not_image("its content is not base64"))?; + image_from_bytes(bytes, slot).await +} + +/// A file within the limits as it is, a file past them as a JPEG copy, made holding `slot`, +/// or one taken here. The header is read first, so an image already in the result and within +/// the limits never waits for another's copy. +#[cfg(feature = "mcp")] +pub(super) async fn image_from_bytes( + bytes: Vec, + slot: Option, +) -> Result { + let (bytes, format, as_is) = blocking(move || { + let format = image_format(&bytes)?; + let as_is = image_as_is(&bytes, format)?; + Ok((bytes, format, as_is)) + }) + .await?; + if let Some(attachment) = as_is { + return Ok(attachment); + } + let slot = match slot { + Some(slot) => slot, + None => read_slot().await?, + }; + blocking(move || { + // Held until the decoding ends, also when the answer is no longer awaited. + let _slot = slot; + image_copy(&bytes, format) + }) + .await +} + +/// Only an MCP client is handed images, and the image crates are built only with it. +#[cfg(not(feature = "mcp"))] +pub(super) async fn image_from_bytes( + _bytes: Vec, + _slot: Option, +) -> Result { + Err(unreadable( + "images are read only for MCP clients".to_string(), + )) +} + +/// The widest or tallest image handed to the model: the Claude API refuses a larger one, and +/// with it the whole request. +#[cfg(feature = "mcp")] +const MAX_IMAGE_SIDE: u32 = 8000; +/// The longest side of the JPEG copy handed for an image past either limit: the most Claude +/// reads, which scales a larger image down itself. +#[cfg(feature = "mcp")] +const COPY_SIDE: u32 = 2576; +/// The most memory an image copied takes decoded: a 6000x4000 RGBA image, or a 42 MP photo. +#[cfg(feature = "mcp")] +const MAX_DECODED_BYTES: u64 = 128_000_000; +/// The most a decoder allocates besides the pixels, for the file's metadata mostly. A PNG's +/// color profile is compressed, and the decoder's default allowance (512 MiB) lets a file of +/// a few hundred KB inflate it to hundreds of MB. +#[cfg(feature = "mcp")] +const MAX_METADATA_BYTES: u64 = 16_000_000; + +/// A file's type, read from its bytes: the key or extension only says an image is worth +/// reading, and a provider can refuse the whole request for an image whose bytes are not the +/// type it is sent as. +#[cfg(feature = "mcp")] +fn image_format(bytes: &[u8]) -> Result { + use image::ImageFormat; + image::guess_format(bytes) + .ok() + .filter(|format| { + matches!( + format, + ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::Gif | ImageFormat::WebP + ) + }) + .ok_or_else(|| not_image("not a PNG, JPEG, GIF or WebP file")) +} + +/// The file itself, when it is within the limits. +#[cfg(feature = "mcp")] +fn image_as_is(bytes: &[u8], format: image::ImageFormat) -> Result, Unattached> { + use base64::Engine; + let (width, height) = image_reader(bytes, format) + .into_dimensions() + .map_err(|_| not_image("its width and height cannot be read"))?; + if bytes.len() > MAX_IMAGE_BYTES || width.max(height) > MAX_IMAGE_SIDE { + return Ok(None); + } + let data = base64::engine::general_purpose::STANDARD.encode(bytes); + let image = ToolImage { data, mime_type: format.to_mime_type() }; + Ok(Some(Attachment { image, copy: None })) +} + +/// Work that takes CPU time, run off the async threads. A decoder that panics leaves the +/// image out. +#[cfg(feature = "mcp")] +async fn blocking( + work: impl FnOnce() -> Result + Send + 'static, +) -> Result { + tokio::task::spawn_blocking(work) + .await + .unwrap_or_else(|_| Err(not_image("it cannot be decoded"))) +} + +/// A reader whose decoder allocates at most `MAX_METADATA_BYTES` besides the pixels. +#[cfg(feature = "mcp")] +fn image_reader( + bytes: &[u8], + format: image::ImageFormat, +) -> image::ImageReader> { + let mut limits = image::Limits::default(); + limits.max_alloc = Some(MAX_METADATA_BYTES); + let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes), format); + reader.limits(limits); + reader +} + +/// A JPEG copy of an image, at most `COPY_SIDE` on its longest side and its quality lowered +/// until it is within `MAX_IMAGE_BYTES`. +#[cfg(feature = "mcp")] +fn image_copy(bytes: &[u8], format: image::ImageFormat) -> Result { + use base64::Engine; + use image::codecs::jpeg::JpegEncoder; + use image::metadata::Orientation; + use image::{DynamicImage, ImageDecoder}; + let undecodable = + |error: image::ImageError| not_image(&format!("it cannot be decoded: {error}")); + let mut decoder = image_reader(bytes, format) + .into_decoder() + .map_err(undecodable)?; + let (mut width, mut height) = decoder.dimensions(); + if decoder.total_bytes() > MAX_DECODED_BYTES { + let why = format!("{width}x{height} px, too large to decode"); + return Err(Unattached { key: "too_large", why }); + } + let orientation = match format { + image::ImageFormat::WebP => webp_orientation(bytes), + _ => decoder.orientation().ok(), + } + .unwrap_or(Orientation::NoTransforms); + let mut pixels = DynamicImage::from_decoder(decoder).map_err(undecodable)?; + if width.max(height) > COPY_SIDE { + pixels = pixels.thumbnail(COPY_SIDE, COPY_SIDE); + } + // The copy keeps no EXIF data, so a photo taken sideways is turned as viewers show it. + pixels.apply_orientation(orientation); + if matches!( + orientation, + Orientation::Rotate90 + | Orientation::Rotate270 + | Orientation::Rotate90FlipH + | Orientation::Rotate270FlipH + ) { + (width, height) = (height, width); + } + let pixels = over_white(pixels); + for quality in [85, 70, 50, 30] { + let mut jpeg = Vec::new(); + JpegEncoder::new_with_quality(&mut jpeg, quality) + .encode_image(&pixels) + .map_err(|error| unreadable(format!("its copy cannot be encoded: {error}")))?; + if jpeg.len() <= MAX_IMAGE_BYTES { + let data = base64::engine::general_purpose::STANDARD.encode(&jpeg); + let (copy_width, copy_height) = pixels.dimensions(); + let copy = + format!("a {copy_width}x{copy_height} JPEG copy of the {width}x{height} px file"); + let image = ToolImage { data, mime_type: "image/jpeg" }; + return Ok(Attachment { image, copy: Some(copy) }); + } + } + let why = format!( + "larger than {} MB even as a JPEG copy", + MAX_IMAGE_BYTES as f64 / 1e6 + ); + Err(Unattached { key: "too_large", why }) +} + +/// A WebP's orientation, from its EXIF chunk. image's WebP decoder ignores `max_alloc`, and +/// allocates an EXIF chunk at the length its header declares, up to 4 GB, before reading it, +/// so the chunk is read through image-webp with the metadata limit. +#[cfg(feature = "mcp")] +fn webp_orientation(bytes: &[u8]) -> Option { + let mut decoder = image_webp::WebPDecoder::new(std::io::Cursor::new(bytes)).ok()?; + decoder.set_memory_limit(MAX_METADATA_BYTES as usize); + image::metadata::Orientation::from_exif_chunk(&decoder.exif_metadata().ok()??) +} + +/// An image's pixels as RGB, its transparent parts over white: a JPEG keeps no transparency, +/// and the color under it is often black, the color of the text drawn on it. +#[cfg(feature = "mcp")] +fn over_white(pixels: image::DynamicImage) -> image::RgbImage { + if !pixels.has_alpha() { + return pixels.into_rgb8(); + } + let rgba = pixels.into_rgba8(); + image::RgbImage::from_fn(rgba.width(), rgba.height(), |x, y| { + let [r, g, b, a] = rgba.get_pixel(x, y).0.map(u32::from); + let over = |c: u32| ((c * a + 255 * (255 - a)) / 255) as u8; + image::Rgb([over(r), over(g), over(b)]) + }) +} + +#[cfg(all(test, feature = "mcp"))] +mod tests { + use super::*; + + /// A black JPEG of `width` x `height`. + fn jpeg(width: u32, height: u32) -> Vec { + let mut file = Vec::new(); + image::codecs::jpeg::JpegEncoder::new(&mut file) + .encode_image(&image::RgbImage::new(width, height)) + .unwrap(); + file + } + + fn decoded(attachment: &Attachment) -> image::DynamicImage { + use base64::Engine; + let bytes = base64::engine::general_purpose::STANDARD + .decode(&attachment.image.data) + .unwrap(); + image::load_from_memory(&bytes).unwrap() + } + + #[tokio::test] + async fn an_image_within_the_limits_is_sent_as_the_type_its_bytes_are() { + use base64::Engine; + // A `{"png": ...}` holding a JPEG goes out as one, unchanged but for its line breaks. + let data = base64::engine::general_purpose::STANDARD.encode(jpeg(3, 2)); + let wrapped = format!("{}\n{}", &data[..8], &data[8..]); + let sent = decode_inline_image(&wrapped, None).await.unwrap(); + assert_eq!( + (sent.image.mime_type, sent.image.data.as_str(), sent.copy), + ("image/jpeg", data.as_str(), None) + ); + let page = decode_inline_image("PGh0bWw+", None).await; + assert!(matches!(page, Err(Unattached { key: "not_image", .. }))); + } + + #[tokio::test] + async fn an_image_past_the_limits_is_sent_as_a_jpeg_copy() { + // EXIF orientation 6, a photo taken sideways: the copy is turned as viewers show it. + let exif = b"\xff\xe1\0\x22Exif\0\0MM\0\x2a\0\0\0\x08\0\x01\x01\x12\0\x03\0\0\0\x01\0\x06\0\0\0\0\0\0"; + let file = jpeg(9000, 10); + let sideways = [&file[..2], exif.as_slice(), &file[2..]].concat(); + let sent = image_from_bytes(sideways, None).await.unwrap(); + assert_eq!( + sent.copy.as_deref(), + Some("a 3x2576 JPEG copy of the 10x9000 px file") + ); + let copy = decoded(&sent); + assert_eq!( + (sent.image.mime_type, copy.width(), copy.height()), + ("image/jpeg", 3, 2576) + ); + + // Transparent parts are drawn over white. + let mut png = Vec::new(); + image::RgbaImage::new(9000, 2) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let copy = decoded(&image_from_bytes(png, None).await.unwrap()).to_rgb8(); + assert!(copy.pixels().all(|pixel| pixel.0.iter().all(|&c| c > 250))); + + // An image too large to decode is refused from its header: a 10000x10000 GIF. + let gif = b"GIF89a\x10\x27\x10\x27\0\0\0,\0\0\0\0\x10\x27\x10\x27\0\x02\x02\x44\x01\0;"; + let refused = image_from_bytes(gif.to_vec(), None).await; + assert!(matches!(refused, Err(Unattached { key: "too_large", .. }))); + } + + #[test] + fn a_color_profile_past_the_metadata_limit_is_dropped() { + use image::{ImageDecoder, ImageEncoder}; + let mut png = Vec::new(); + let mut encoder = image::codecs::png::PngEncoder::new(&mut png); + encoder + .set_icc_profile(vec![0; MAX_METADATA_BYTES as usize + 1]) + .unwrap(); + encoder + .write_image(&[0; 3], 1, 1, image::ExtendedColorType::Rgb8) + .unwrap(); + let mut decoder = image_reader(&png, image::ImageFormat::Png) + .into_decoder() + .unwrap(); + assert_eq!(decoder.icc_profile().unwrap(), None); + } + + #[test] + fn a_webp_exif_chunk_past_the_metadata_limit_is_not_read() { + use image::ImageEncoder; + // EXIF orientation 6: viewers turn the image a quarter turn clockwise. + let mut exif = b"II*\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x06\0\0\0\0\0\0\0".to_vec(); + let copy = |exif: &[u8]| { + let mut webp = Vec::new(); + let mut encoder = image::codecs::webp::WebPEncoder::new_lossless(&mut webp); + encoder.set_exif_metadata(exif.to_vec()).unwrap(); + encoder + .write_image(&[0; 6], 2, 1, image::ExtendedColorType::Rgb8) + .unwrap(); + image_copy(&webp, image::ImageFormat::WebP) + .unwrap() + .copy + .unwrap() + }; + assert_eq!(copy(&exif), "a 1x2 JPEG copy of the 1x2 px file"); + exif.resize(MAX_METADATA_BYTES as usize + 1, 0); + assert_eq!(copy(&exif), "a 2x1 JPEG copy of the 2x1 px file"); + } +} diff --git a/backend/windmill-api/src/ai_session_tools/mod.rs b/backend/windmill-api/src/ai_session_tools/mod.rs index 8b623b230c..ebef16a418 100644 --- a/backend/windmill-api/src/ai_session_tools/mod.rs +++ b/backend/windmill-api/src/ai_session_tools/mod.rs @@ -64,6 +64,7 @@ mod data; mod deploy; mod flows; mod guidance; +mod images; #[cfg(feature = "mcp")] mod instructions; mod items; @@ -265,6 +266,15 @@ pub(crate) fn session_tools(access: SessionAccess) -> impl Iterator; +/// An image the model reads beside a tool's text: an MCP `image` content block, or for the +/// chat, an image it attaches to the conversation. +#[derive(Serialize)] +pub(crate) struct ToolImage { + /// Standard base64. + pub data: String, + pub mime_type: &'static str, +} + /// The caller, and the API reached as them. pub(crate) struct Ctx<'a> { pub auth: &'a ApiAuthed, @@ -284,18 +294,11 @@ pub(crate) struct Ctx<'a> { /// What the card draws of this call, as `(key, value)`: returned in the result's /// `_meta`, which the model never reads. pub view: std::sync::Mutex>, - /// Images the model sees beside the text: MCP sends them as image content, the chat + /// The images the model reads beside the text: MCP sends them as image content, the chat /// attaches them to the conversation. pub images: std::sync::Mutex>, } -/// An image a tool returns, base64-encoded. -#[derive(Serialize)] -pub(crate) struct ToolImage { - pub mime_type: String, - pub data: String, -} - impl<'a> Ctx<'a> { pub(crate) fn new( auth: &'a ApiAuthed, @@ -318,6 +321,13 @@ impl<'a> Ctx<'a> { } } + /// Whether the model reads images beside the text. The chat's providers take a tool + /// result as text only (OpenAI's tool messages cannot carry an image), so only an MCP + /// client is handed any. + pub(super) fn reads_images(&self) -> bool { + self.surface == Surface::Mcp + } + /// Hand the chat something to apply. A no-op for MCP, which has no editor. pub(super) fn effect(&self, effect: chat::Effect) { if self.surface == Surface::Chat { @@ -335,15 +345,6 @@ impl Ctx<'_> { *self.view.lock().unwrap() = Some((key, value)); } - /// Return an image to the model with the call's text. - pub fn push_image(&self, mime_type: &str, bytes: &[u8]) { - use base64::Engine; - self.images.lock().unwrap().push(ToolImage { - mime_type: mime_type.to_string(), - data: base64::engine::general_purpose::STANDARD.encode(bytes), - }); - } - /// Call the API as the caller. `path` follows `/api`; a non-2xx answer is the error. pub async fn request(&self, method: &str, path: &str, body: Option) -> ToolResult { self.request_within(method, path, body, REQUEST_TIMEOUT) @@ -360,22 +361,43 @@ impl Ctx<'_> { body: Option, timeout: std::time::Duration, ) -> ToolResult { - let bytes = self.request_bytes(method, path, body, timeout).await?; - Ok(String::from_utf8_lossy(&bytes).into_owned()) + let (status, bytes) = self.send(method, path, body, timeout, usize::MAX).await?; + let text = String::from_utf8_lossy(bytes.as_deref().unwrap_or_default()).into_owned(); + match status.is_success() { + true => Ok(text), + false => Err(api_error(status, &text)), + } } - /// `GET` a route that answers with bytes, such as a file's content. - pub async fn get_bytes(&self, path: &str) -> Result, String> { - self.request_bytes("GET", path, None, REQUEST_TIMEOUT).await + /// `GET` an answer as bytes, at most `max_bytes` of them: `None` for a longer answer, + /// which is not read past the limit. + pub async fn get_bytes( + &self, + path: &str, + max_bytes: usize, + ) -> Result, String> { + let (status, bytes) = self + .send("GET", path, None, REQUEST_TIMEOUT, max_bytes) + .await?; + match status.is_success() { + true => Ok(bytes), + false => { + let text = String::from_utf8_lossy(bytes.as_deref().unwrap_or_default()); + Err(api_error(status, &text)) + } + } } - async fn request_bytes( + /// Call the API as the caller and read at most `max_bytes` of the answer: `None` past + /// that. + async fn send( &self, method: &str, path: &str, body: Option, timeout: std::time::Duration, - ) -> Result, String> { + max_bytes: usize, + ) -> Result<(http::StatusCode, Option), String> { let url = guarded_url(self.base_internal_url, self.w_id, method, path, self.access)?; // No route scope: this server only admits `mcp:all`, several routes (hub, embeddings) // map to none, and `guarded_url` is what keeps a call on its route. The tag fence @@ -394,23 +416,15 @@ impl Ctx<'_> { .unwrap() .get(self.base_internal_url) .cloned(); - let (status, bytes) = match router { + match router { Some(router) => { - self.call_router(router, method, &url, body, scopes, timeout) - .await? + self.call_router(router, method, &url, body, scopes, timeout, max_bytes) + .await + } + None => { + self.call_http(method, &url, body, scopes, timeout, max_bytes) + .await } - None => self.call_http(method, &url, body, scopes, timeout).await?, - }; - if status.is_success() { - return Ok(bytes); - } - let text = String::from_utf8_lossy(&bytes); - if text.trim().is_empty() { - // What a browser's request reports for an answer with no body. - let reason = status.canonical_reason().unwrap_or_default(); - Err(format!("{}: {reason}", status.as_u16())) - } else { - Err(format!("{}: {}", status.as_u16(), text)) } } @@ -424,7 +438,8 @@ impl Ctx<'_> { body: Option, scopes: Option>, timeout: std::time::Duration, - ) -> Result<(http::StatusCode, Vec), String> { + max_bytes: usize, + ) -> Result<(http::StatusCode, Option), String> { use tower::ServiceExt; let parsed = reqwest::Url::parse(url).map_err(|e| e.to_string())?; // The router does not see the base URL's own path prefix. @@ -454,10 +469,8 @@ impl Ctx<'_> { tokio::time::timeout(timeout, async { let Ok(response) = router.oneshot(request).await; let status = response.status(); - let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) - .await - .map_err(|e| e.to_string())?; - Ok((status, bytes.to_vec())) + let body = read_capped(response.into_body().into_data_stream(), max_bytes).await?; + Ok((status, body)) }) .await .map_err(|_| format!("Failed to execute request: {method} {url} timed out"))? @@ -471,7 +484,8 @@ impl Ctx<'_> { body: Option, scopes: Option>, timeout: std::time::Duration, - ) -> Result<(http::StatusCode, Vec), String> { + max_bytes: usize, + ) -> Result<(http::StatusCode, Option), String> { let method = http::Method::from_bytes(method.as_bytes()).map_err(|e| e.to_string())?; let token = self .jwt @@ -490,8 +504,14 @@ impl Ctx<'_> { .await .map_err(|e| format!("Failed to execute request: {e}"))?; let status = response.status(); - let bytes = response.bytes().await.map_err(|e| e.to_string())?; - Ok((status, bytes.to_vec())) + if response + .content_length() + .is_some_and(|len| len > max_bytes as u64) + { + return Ok((status, None)); + } + let body = read_capped(response.bytes_stream(), max_bytes).await?; + Ok((status, body)) } pub async fn get(&self, path: &str) -> Result { @@ -549,6 +569,36 @@ impl Ctx<'_> { } } +/// A failed API call as the session reads it: the status code, then the answer. +fn api_error(status: http::StatusCode, body: &str) -> String { + if body.trim().is_empty() { + // What a browser's request reports for an answer with no body. + let reason = status.canonical_reason().unwrap_or_default(); + format!("{}: {reason}", status.as_u16()) + } else { + format!("{}: {body}", status.as_u16()) + } +} + +/// A body read in full while it stays within `max` bytes: `None` once it passes that, +/// without reading the rest. +async fn read_capped( + stream: impl futures::Stream>, + max: usize, +) -> Result, String> { + use futures::StreamExt; + let mut stream = std::pin::pin!(stream); + let mut body = bytes::BytesMut::new(); + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(|e| e.to_string())?; + if body.len().saturating_add(chunk.len()) > max { + return Ok(None); + } + body.extend_from_slice(&chunk); + } + Ok(Some(body.freeze())) +} + /// Routes outside the workspace that a tool reads. const INSTANCE_ROUTES: &[&str] = &[ "/docs/", @@ -816,10 +866,11 @@ pub(crate) async fn call_session_tool( name: &str, args: Value, ) -> Result { - if ctx.surface == Surface::Mcp && views::TOOLS.contains(&name) { - return Ok(outcome(views::call(ctx, name, &args).await)); - } - let result = call_generated_tool(ctx, name, &args).await?; + let result = if ctx.surface == Surface::Mcp && views::TOOLS.contains(&name) { + views::call(ctx, name, &args).await + } else { + call_generated_tool(ctx, name, &args).await? + }; let mut outcome = outcome(result); if !outcome.is_error { outcome.images = std::mem::take(&mut *ctx.images.lock().unwrap()); diff --git a/backend/windmill-api/src/ai_session_tools/runs.rs b/backend/windmill-api/src/ai_session_tools/runs.rs index 473443edb6..437a8539a0 100644 --- a/backend/windmill-api/src/ai_session_tools/runs.rs +++ b/backend/windmill-api/src/ai_session_tools/runs.rs @@ -7,6 +7,10 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; use super::chat::{Effect, RunPhase}; +use super::images::{ + decode_inline_image, image_from_bytes, not_image, read_slot, too_large, unreadable, Attachment, + Unattached, MAX_IMAGE_BYTES, MAX_SOURCE_BYTES, MAX_SOURCE_CHARS, +}; use super::workspace::{ api_message, get_draft, infer_script_schema, load_flow, load_script_to_run, path_enc, }; @@ -216,6 +220,9 @@ pub(super) async fn finish_run( "\n\nFor per-step statuses and results (subflow steps included), call get_run with id=\"{id}\"." )); } + if ctx.reads_images() { + summary.push_str(&image_hint(&id, job.get("result")).unwrap_or_default()); + } summary.push_str(&run_page); Ok(summary) } @@ -2311,10 +2318,15 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult { enc(step) ); let response = ctx.get(&route).await?; - if let Some(job_id) = finished_step_job(&response) { + let finished = finished_step_job(&response); + if let Some(job_id) = finished { ctx.effect(Effect::InspectedRun { job_id: job_id.to_string() }); } - return Ok(step_result(&response, step)); + let images = match finished.filter(|_| ctx.reads_images() && !card) { + Some(job_id) => step_images(ctx, job_id, &response["entries"][0]).await, + None => None, + }; + return Ok(step_result(&response, step, images.as_ref())); } // Only the job read is load-bearing: logs and the step tree each answer part of @@ -2396,7 +2408,12 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult { None => report_run(ctx, id, Some(job), details), } } - let run = shape_run(id, &job?, logs, &results); + let job = job?; + let images = match ctx.reads_images() && !card { + true => attach_result_images(ctx, id, job.get("result"), results["entries"].get(0)).await, + false => None, + }; + let run = shape_run(id, &job, logs, &results, images.as_ref()); ctx.effect(Effect::InspectedRun { job_id: id.to_string() }); Ok(match ctx.link(&format!("/run/{}", enc(id))) { Some(url) => format!("{run}\n\nRun page: {url}"), @@ -2404,6 +2421,24 @@ async fn read_run(ctx: &Ctx<'_>, args: &Value, card: bool) -> ToolResult { }) } +/// The kind of image a result the job read swapped for a marker looks like (`png`, `jpeg`, +/// `gif` or `svg`), from the head of it the step tree carries, and the result's length in +/// characters. +fn too_big_image<'a>(result: Option<&Value>, root: Option<&'a Value>) -> Option<(&'a str, u64)> { + if result? != TOO_BIG { + return None; + } + let root = root?; + let kind = root["result_prefix"] + .as_str()? + .strip_prefix("{\"")? + .split('"') + .next()?; + ["png", "jpeg", "gif", "svg"] + .contains(&kind) + .then_some((kind, root["result_length"].as_u64()?)) +} + /// The job read swaps a result past ~90 KB for a marker, so an image under the card's cap /// is read again by its one field. The step tree's head of the result says which it is. async fn big_image_result( @@ -2412,29 +2447,30 @@ async fn big_image_result( job: &Value, root: Option<&Value>, ) -> Option { - if job.get("result")? != TOO_BIG { - return None; - } - let root = root?; - let kind = root["result_prefix"] - .as_str()? - .strip_prefix("{\"")? - .split('"') - .next()?; - if !["png", "jpeg", "gif", "svg"].contains(&kind) - || root["result_length"].as_u64()? > CARD_IMAGE_CHARS as u64 + 64 - { + let (kind, length) = too_big_image(job.get("result"), root)?; + if length > CARD_IMAGE_CHARS as u64 + 64 { return None; } + read_whole_image(ctx, id, kind, length).await.ok().flatten() +} + +/// A swapped result read again by its one field `kind`, `length` being the result's text in +/// characters: `None` when the result holds more than that field. +async fn read_whole_image( + ctx: &Ctx<'_>, + id: &str, + kind: &str, + length: u64, +) -> Result, String> { let route = ctx.ws(&format!( "jobs/completed/get_result/{}?json_path={kind}", enc(id) )); - let field = ctx.get(&route).await.ok()?; + let field = ctx.get(&route).await?; // The field alone must be the whole result, as `card_image` requires: a result with more // keys is no image, and keeps its marker. The length is the result's text, in characters. let whole = json!({ kind: field }); - (jsonb_text_len(&whole) == root["result_length"].as_u64()?).then_some(whole) + Ok((jsonb_text_len(&whole) == length).then_some(whole)) } /// The length in characters of a value as PostgreSQL prints a jsonb: `", "` between items @@ -2457,6 +2493,316 @@ fn jsonb_text_len(value: &Value) -> u64 { } } +// ============================================================================ +// Images the model reads: a result Windmill draws as an image, attached to +// `get_run`'s answer for an MCP client. +// ============================================================================ + +/// The images one answer carries at most, and their bytes together. +const MAX_IMAGES: usize = 4; +const MAX_IMAGES_BYTES: usize = 2 * MAX_IMAGE_BYTES; +/// The object storage files the run page draws as an image, and GIFs, which models read. +const IMAGE_EXTENSIONS: [&str; 5] = [".png", ".jpg", ".jpeg", ".gif", ".webp"]; + +/// Where an image result's bytes are. +#[derive(Debug, PartialEq)] +enum ImageRef<'a> { + /// Base64 in the result itself, under the kind its key names. + Inline { kind: &'a str, data: &'a str }, + /// A file in the workspace's object storage. + S3 { key: &'a str, storage: Option<&'a str> }, +} + +/// The images a result is, in the shapes the run page draws as one: `{png|jpeg|gif}` of +/// base64, a file in object storage with an image extension, or a list of such files. +fn image_refs(result: &Value) -> Vec> { + match result.as_array() { + // The run page lists files only when every item is one, up to 100 of them. + Some(items) + if items.len() <= 100 + && items + .iter() + .all(|item| item.is_object() && s3_file(item).is_some()) => + { + items.iter().filter_map(s3_image).collect() + } + Some(_) => Vec::new(), + None => inline_image(result) + .or_else(|| s3_image(result)) + .into_iter() + .collect(), + } +} + +/// The object storage file a value names, `{s3, storage?}` or `s3:///`, as +/// its key and storage. +fn s3_file(value: &Value) -> Option<(&str, Option<&str>)> { + let (key, storage) = match value { + Value::String(uri) => { + let (storage, key) = uri.strip_prefix("s3://")?.split_once('/')?; + (key, Some(storage)) + } + Value::Object(file) => ( + file.get("s3")?.as_str()?, + file.get("storage").and_then(Value::as_str), + ), + _ => return None, + }; + (!key.is_empty()).then_some((key, storage.filter(|s| !s.is_empty()))) +} + +fn s3_image(value: &Value) -> Option> { + let (key, storage) = s3_file(value)?; + let lower = key.to_ascii_lowercase(); + IMAGE_EXTENSIONS + .iter() + .any(|ext| lower.ends_with(ext)) + .then_some(ImageRef::S3 { key, storage }) +} + +/// A one-key result's value as text, bare or as a file's `content`: how a script returns +/// an image or a page inline, as `{"png": ""}`. +fn single_file(result: &Value) -> Option<(&str, &str)> { + let [(kind, value)] = result.as_object()?.iter().collect::>()[..] else { + return None; + }; + let data = value + .as_str() + .or_else(|| value.get("content").and_then(Value::as_str)) + .filter(|d| !d.is_empty())?; + Some((kind.as_str(), data)) +} + +fn is_base64(data: &str) -> bool { + data.bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=' | b'\n' | b'\r')) +} + +fn inline_image(result: &Value) -> Option> { + let (kind, data) = single_file(result)?; + (matches!(kind, "png" | "jpeg" | "gif") && is_base64(data)) + .then_some(ImageRef::Inline { kind, data }) +} + +/// What `get_run` writes beside a result's images: under `key`, what became of them, and +/// for an inline image the label standing in for its base64, which tells the model nothing. +struct ImageNote { + key: &'static str, + text: String, + label: Option, +} + +fn image_label(kind: &str) -> String { + format!("{} image", kind.to_uppercase()) +} + +/// Attach the images `result` is, `entry` being its job's entry in the step tree, which +/// says what a result the job read swapped for a marker was. `None` for a result that is no +/// image. A failed read leaves its image out and says why; it never fails the answer. +async fn attach_result_images( + ctx: &Ctx<'_>, + job_id: &str, + result: Option<&Value>, + entry: Option<&Value>, +) -> Option { + let result = result?; + let swapped = too_big_image(Some(result), entry).filter(|(kind, _)| *kind != "svg"); + let (label, total, reads) = match swapped { + Some((kind, length)) => { + let read = read_swapped_image(ctx, job_id, kind, length).await?; + (Some(image_label(kind)), 1, vec![(None, read)]) + } + None => { + let refs = image_refs(result); + let label = match refs.first()? { + ImageRef::Inline { kind, .. } => Some(image_label(kind)), + ImageRef::S3 { .. } => None, + }; + // One after another, so an answer holds one of the server's read slots at a time. + let mut reads = Vec::new(); + for image in refs.iter().take(MAX_IMAGES) { + let name = match image { + ImageRef::S3 { key, .. } => Some(*key), + ImageRef::Inline { .. } => None, + }; + reads.push((name, read_image(ctx, image).await)); + } + (label, refs.len(), reads) + } + }; + let mut budget = MAX_IMAGES_BYTES; + let outcomes: Vec<(Option<&str>, Result, String>)> = reads + .into_iter() + .map(|(name, read)| { + let outcome = read.and_then(|Attachment { image, copy }| { + let bytes = image.data.len() / 4 * 3; + if bytes > budget { + let why = format!( + "this answer already carries {} MB of images", + MAX_IMAGES_BYTES as f64 / 1e6 + ); + return Err(Unattached { key: "too_large", why }); + } + budget -= bytes; + ctx.images.lock().unwrap().push(image); + Ok(copy) + }); + // Only an object storage file is named, by its key. + let source = if name.is_some() { "s3" } else { "inline" }; + let key = match &outcome { + Ok(Some(_)) => "copy", + Ok(None) => source, + Err(skip) => skip.key, + }; + windmill_common::feature_usage::log_feature_usage("mcp_workspace", "result_image", key); + (name, outcome.map_err(|skip| skip.why)) + }) + .collect(); + Some(ImageNote { + key: if result.is_array() { + "result_images" + } else { + "result_image" + }, + text: image_note_text(&outcomes, total, result.is_array()), + label, + }) +} + +fn image_note_text( + outcomes: &[(Option<&str>, Result, String>)], + total: usize, + listed: bool, +) -> String { + if !listed { + return match outcomes.first().map(|(_, outcome)| outcome) { + Some(Err(why)) => format!("not attached: {why}"), + Some(Ok(Some(copy))) => format!("attached as {copy}"), + _ => "attached".to_string(), + }; + } + let attached = outcomes.iter().filter(|(_, o)| o.is_ok()).count(); + let mut text = format!("{attached} of {total} images attached"); + for (name, outcome) in outcomes { + if let Ok(Some(copy)) = outcome { + text.push_str(&format!("; {} as {copy}", name.unwrap_or("image"))); + } + } + let failed: Vec = outcomes + .iter() + .filter_map(|(name, outcome)| { + let why = outcome.as_ref().err()?; + Some(format!("{} ({why})", name.unwrap_or("image"))) + }) + .collect(); + if !failed.is_empty() { + text.push_str(&format!("; not attached: {}", failed.join(", "))); + } + if total > outcomes.len() { + text.push_str(&format!( + "; an answer carries at most {MAX_IMAGES}, the rest are on the run page" + )); + } + text +} + +/// One image as the model is handed it, or why not. +async fn read_image(ctx: &Ctx<'_>, image: &ImageRef<'_>) -> Result { + match *image { + ImageRef::Inline { data, .. } => decode_inline_image(data, None).await, + ImageRef::S3 { key, storage } => read_s3_image(ctx, key, storage).await, + } +} + +/// An inline image the job read swapped for a marker, read again by its one field. `None` +/// when the result holds more than that field, and so is no image. +async fn read_swapped_image( + ctx: &Ctx<'_>, + job_id: &str, + kind: &str, + length: u64, +) -> Option> { + if length > MAX_SOURCE_CHARS as u64 + 64 { + return Some(Err(too_large())); + } + let slot = match read_slot().await { + Ok(slot) => slot, + Err(busy) => return Some(Err(busy)), + }; + let whole = match read_whole_image(ctx, job_id, kind, length).await { + Ok(whole) => whole?, + Err(error) => { + let why = format!("its read failed: {}", js_head(api_message(&error), 300)); + return Some(Err(unreadable(why))); + } + }; + Some(match inline_image(&whole) { + Some(ImageRef::Inline { data, .. }) => decode_inline_image(data, Some(slot)).await, + _ => Err(not_image("its content is not base64")), + }) +} + +/// A file of the workspace's object storage, read as the caller through the route the run +/// page previews it with, so the same storage permission rules apply. +pub(super) async fn read_s3_image( + ctx: &Ctx<'_>, + key: &str, + storage: Option<&str>, +) -> Result { + if !cfg!(all(feature = "private", feature = "parquet")) { + let why = "reading object storage needs Windmill Enterprise Edition"; + return Err(unreadable(why.to_string())); + } + let storage = storage + .map(|s| format!("&storage={}", enc(s))) + .unwrap_or_default(); + let route = ctx.ws(&format!( + "job_helpers/load_image_preview?file_key={}{storage}", + enc(key) + )); + let slot = read_slot().await?; + match ctx.get_bytes(&route, MAX_SOURCE_BYTES).await { + Ok(Some(bytes)) => image_from_bytes(bytes.into(), Some(slot)).await, + Ok(None) => Err(too_large()), + Err(error) => Err(unreadable(format!( + "object storage answered: {}", + js_head(api_message(&error), 300) + ))), + } +} + +/// The images of a finished step's result. Its entry carries the whole result when it is +/// short, and only its head otherwise. +async fn step_images(ctx: &Ctx<'_>, job_id: &str, entry: &Value) -> Option { + let prefix = entry["result_prefix"].as_str()?; + let whole = entry["result_length"] + .as_u64() + .is_none_or(|length| length == prefix.chars().count() as u64); + let result = match whole { + true => serde_json::from_str(prefix).ok()?, + false => json!(TOO_BIG), + }; + attach_result_images(ctx, job_id, Some(&result), Some(entry)).await +} + +/// What a run tool adds about a result only `get_run` attaches: an image, or a result too +/// big to show, which may be one. +fn image_hint(id: &str, result: Option<&Value>) -> Option { + let result = result?; + if result == TOO_BIG { + return Some(format!( + "\n\nThe result is too large to show here. If it is an image, get_run with id=\"{id}\" attaches it." + )); + } + if image_refs(result).is_empty() { + return None; + } + Some(match result.is_array() { + true => format!("\n\nThe result lists images: call get_run with id=\"{id}\" to see them."), + false => format!("\n\nThe result is an image: call get_run with id=\"{id}\" to see it."), + }) +} + /// The end of a job's log, read without the rest of it: an offset past the end returns /// no log but where it ends, and a second read starts just before that. A log grows as long /// as its job runs, and the card asks again on every refresh. The result stream's offset is @@ -2933,19 +3279,9 @@ fn describe_result(result: &Value) -> Option { /// An image result as Windmill draws it, for the card to draw too: base64 for PNG, JPEG and /// GIF, the markup itself for SVG, either bare or as a file's `content`. fn card_image(result: &Value) -> Option { - let [(kind, value)] = result.as_object()?.iter().collect::>()[..] else { - return None; - }; - let data = value - .as_str() - .or_else(|| value.get("content").and_then(Value::as_str)) - .filter(|d| !d.is_empty() && d.len() <= CARD_IMAGE_CHARS)?; - let base64 = |d: &str| { - d.bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=' | b'\n' | b'\r')) - }; - match kind.as_str() { - "png" | "jpeg" | "gif" if base64(data) => Some(json!({ "type": kind, "data": data })), + let (kind, data) = single_file(result).filter(|(_, data)| data.len() <= CARD_IMAGE_CHARS)?; + match kind { + "png" | "jpeg" | "gif" if is_base64(data) => Some(json!({ "type": kind, "data": data })), "svg" => Some(json!({ "type": "svg", "data": data })), _ => None, } @@ -3094,8 +3430,14 @@ fn run_card(id: &str, job: Option<&Value>) -> Map { /// A run as `get_run` reports it: its summary, args, result and logs around the step /// tree. `logs` is the log read's own outcome, so a failed read is told apart from an -/// empty log. -fn shape_run(id: &str, job: &Value, logs: Result, results: &Value) -> String { +/// empty log. `images` says what became of the images the result is. +fn shape_run( + id: &str, + job: &Value, + logs: Result, + results: &Value, + images: Option<&ImageNote>, +) -> String { let mut run = summarize_run(job); run.shift_remove("id"); // Why a run ended badly. @@ -3115,8 +3457,8 @@ fn shape_run(id: &str, job: &Value, logs: Result, results: &Valu run.insert("steps_unavailable".into(), true.into()); } // The server swaps a payload too big to send for a marker, each field in its own - // form. That is reported, never fetched around: the result keeps the head the step - // tree carries. + // form. That is reported, and fetched around only for an image the model is handed: + // otherwise the result keeps the head the step tree carries. if let Some(job_args) = job.get("args").filter(|a| truthy(Some(a))) { let too_big = job_args .as_object() @@ -3128,10 +3470,19 @@ fn shape_run(id: &str, job: &Value, logs: Result, results: &Valu } } if let Some(result) = job.get("result") { - if result == TOO_BIG { - run.insert("result_truncated".into(), true.into()); - } else { - run.insert("result".into(), cap(&stringify(result), false).into()); + match images.and_then(|note| note.label.as_deref()) { + Some(label) => { + run.insert("result".into(), label.into()); + } + None if result == TOO_BIG => { + run.insert("result_truncated".into(), true.into()); + } + None => { + run.insert("result".into(), cap(&stringify(result), false).into()); + } + } + if let Some(note) = images { + run.insert(note.key.into(), note.text.clone().into()); } } let logs = match logs { @@ -3160,7 +3511,8 @@ fn finished_step_job(response: &Value) -> Option<&str> { } /// One step's result in full, from the single entry the server resolved its address to. -fn step_result(response: &Value, step: &str) -> String { +/// `images` says what became of the images the result is. +fn step_result(response: &Value, step: &str, images: Option<&ImageNote>) -> String { if let Some(error) = response["step_error"].as_str().filter(|e| !e.is_empty()) { let hidden = if truthy(response.get("scope_filtered")) { " (Steps running on tags outside your token’s scope are hidden.)" @@ -3187,7 +3539,14 @@ fn step_result(response: &Value, step: &str) -> String { } else { String::new() }; - format!("Step \"{step}\" (job {job_id}, {status}) result:\n{prefix}{truncated}") + let mut body = match images.and_then(|note| note.label.as_deref()) { + Some(label) => label.to_string(), + None => format!("{prefix}{truncated}"), + }; + if let Some(note) = images { + body.push_str(&format!("\n\n{}: {}", note.key, note.text)); + } + format!("Step \"{step}\" (job {job_id}, {status}) result:\n{body}") } #[cfg(test)] @@ -3585,6 +3944,68 @@ mod tests { ); } + #[test] + fn image_results_are_the_shapes_the_run_page_draws() { + let inline = |kind, data| vec![ImageRef::Inline { kind, data }]; + let s3 = |key, storage| ImageRef::S3 { key, storage }; + assert_eq!( + image_refs(&json!({ "png": "iVBORw0KGgo=" })), + inline("png", "iVBORw0KGgo=") + ); + assert_eq!( + image_refs(&json!({ "jpeg": { "content": "/9j/4A==" } })), + inline("jpeg", "/9j/4A==") + ); + assert_eq!( + image_refs(&json!({ "s3": "charts/q3.PNG" })), + vec![s3("charts/q3.PNG", None)] + ); + assert_eq!( + image_refs(&json!("s3://secondary/a.webp")), + vec![s3("a.webp", Some("secondary"))] + ); + // A list counts when every item is a file, and only its images are read. + let files = json!([{ "s3": "a.png", "storage": "secondary" }, { "s3": "b.csv" }, { "s3": "c.jpg" }]); + assert_eq!( + image_refs(&files), + vec![s3("a.png", Some("secondary")), s3("c.jpg", None)] + ); + for not_an_image in [ + json!([{ "s3": "a.png" }, { "rows": 1 }]), + json!({ "svg": "" }), + json!({ "chart": { "png": "iVBORw0KGgo=" } }), + json!({ "png": "iVBORw0KGgo=", "rows": 1 }), + json!({ "png": "not base64!" }), + json!({ "s3": "report.pdf" }), + ] { + assert!(image_refs(¬_an_image).is_empty(), "{not_an_image}"); + } + } + + #[test] + fn an_attached_inline_image_reads_as_its_label() { + let job = + json!({ "type": "CompletedJob", "success": true, "result": { "png": "iVBORw0KGgo=" } }); + let note = ImageNote { + key: "result_image", + text: "attached".into(), + label: Some("PNG image".into()), + }; + let text = shape_run( + "j", + &job, + Ok(String::new()), + &json!({ "entries": [] }), + Some(¬e), + ); + assert!( + text.contains(r#""result": "PNG image""#) + && text.contains(r#""result_image": "attached""#), + "{text}" + ); + assert!(!text.contains("iVBORw0KGgo"), "{text}"); + } + #[test] fn steps_are_named_from_the_flow_at_any_depth() { let flow = json!({ "modules": [{ diff --git a/backend/windmill-api/src/ai_session_tools/storage.rs b/backend/windmill-api/src/ai_session_tools/storage.rs index 03aa82d385..dc65559aa6 100644 --- a/backend/windmill-api/src/ai_session_tools/storage.rs +++ b/backend/windmill-api/src/ai_session_tools/storage.rs @@ -5,6 +5,8 @@ use serde_json::{json, Map, Value}; use super::data::with_query; +use super::images::{Attachment, Unattached}; +use super::runs::read_s3_image; use super::workspace::path_enc; use super::{array, bool_arg, opt_str_arg, pretty, str_arg, Ctx, ToolResult}; @@ -49,9 +51,6 @@ const MAX_CELL_CHARS: usize = 1000; const DEFAULT_QUERY_ROWS: u64 = 50; const MAX_QUERY_ROWS: u64 = 500; const QUERY_HINT: &str = "Filter, sort or page it with query_s3_table."; -/// Anthropic refuses an image whose base64 data passes 5 MB, and the server has no image -/// library to downscale with. -const MAX_IMAGE_BYTES: u64 = 5 * 1024 * 1024 / 4 * 3; /// What the S3 file browser shows as an image. const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp"]; @@ -230,27 +229,15 @@ async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult { } } if is_image_key(key) { - if size > MAX_IMAGE_BYTES { - out.insert("image".into(), "not attached: larger than 3.75 MB".into()); - } else { - let bytes = ctx - .get_bytes(&with_query( - ctx.ws("job_helpers/load_image_preview"), - &[("file_key", Some(key)), ("storage", storage)], - )) - .await?; - // Model APIs refuse an image whose declared type is not its content's, so - // the type comes from the bytes, never from the key's extension. - if let Some(mime_type) = sniff_image(&bytes) { - ctx.push_image(mime_type, &bytes); - out.insert("image".into(), "attached".into()); - } else { - out.insert( - "image".into(), - "not attached: not a png, jpeg, gif or webp image".into(), - ); + // As `get_run` hands a run's images: one past the model's limits goes as a JPEG copy. + let note = match read_s3_image(ctx, key, storage).await { + Ok(Attachment { image, copy }) => { + ctx.images.lock().unwrap().push(image); + copy.map_or("attached".to_string(), |copy| format!("attached as {copy}")) } - } + Err(Unattached { why, .. }) => format!("not attached: {why}"), + }; + out.insert("image".into(), note.into()); } else { let mut length = size.min(PREVIEW_BYTES); let mut preview = text_preview(ctx, key, storage, size, length).await?; @@ -488,20 +475,6 @@ fn is_image_key(key: &str) -> bool { .is_some_and(|(_, ext)| IMAGE_EXTENSIONS.contains(&ext.to_lowercase().as_str())) } -fn sniff_image(bytes: &[u8]) -> Option<&'static str> { - if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { - Some("image/png") - } else if bytes.starts_with(&[0xff, 0xd8, 0xff]) { - Some("image/jpeg") - } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") { - Some("image/gif") - } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { - Some("image/webp") - } else { - None - } -} - /// Bytes of `value` once pretty-printed `depth` levels deep in the result. fn pretty_len(value: &Value, depth: usize) -> usize { let s = pretty(value); @@ -824,11 +797,4 @@ mod tests { assert_eq!(table_endpoint("a/b.NDJSON"), Some("load_csv_preview")); assert_eq!(table_endpoint("a/b.json"), None); } - - #[test] - fn image_type_comes_from_the_bytes() { - assert_eq!(sniff_image(b"\xff\xd8\xff\xe0rest"), Some("image/jpeg")); - assert_eq!(sniff_image(b"RIFF\0\0\0\0WEBPVP8 "), Some("image/webp")); - assert_eq!(sniff_image(b" String { - + + + +
{ setHoverHighlight(key) tooltipEnter(e.currentTarget as HTMLElement, leaf) }} + onmousemove={leafActions && !isHl ? () => setHoverHighlight(key) : undefined} onmouseleave={tooltipLeave} > - e.preventDefault()} - onclickcapture={(e: MouseEvent) => { - // Capture, not a delegated onclick: the picker is portalled outside the app root, - // where a delegated handler runs after SvelteKit's link handler has already - // followed the href, too late for preventDefault to keep a plain click on `pick`. - if (href && isNewTabClick(e)) return - e.preventDefault() - pick(leaf, e.metaKey || e.ctrlKey) - }} + +
- {@render defaultLeafIcon(leaf)} - -
e.preventDefault()} + onclickcapture={inert + ? undefined + : (e: MouseEvent) => { + // Capture, not a delegated onclick: the picker is portalled outside the app root, + // where a delegated handler runs after SvelteKit's link handler has already + // followed the href, too late for preventDefault to keep a plain click on `pick`. + if (href && isNewTabClick(e)) return + e.preventDefault() + pick(leaf, e.metaKey || e.ctrlKey) + }} > - {#if leaf.secondary} -
{leaf.label}
-
- {secondary ?? leaf.secondary} -
- {:else} -
- {secondary ?? leaf.label} -
+ {@render defaultLeafIcon(leaf)} + +
+ {#if leaf.secondary} +
{leaf.label}
+
+ {secondary ?? leaf.secondary} +
+ {:else} +
+ {secondary ?? leaf.label} +
+ {/if} +
+ + {#if leafActions} + + {#if badge} + {badge.label} + {/if} + + {:else if leafBadge || leafAction} + +
+ {#if action} + + + {/if} + {#if badge} +
+ {badge.label} +
+ {/if} +
+ {/if} +
+ {#if actions.length} + +
+ {#if mainAction && !done} + + + + {/if}
- - - {#if leafBadge || leafAction} - -
- {#if action} - - - {/if} - {#if badge} -
- {badge.label} -
- {/if} + {/if} + {#if done} + +
+ + {done}
{/if}
@@ -753,6 +909,11 @@ leaves and ignores the current scope. > {@render defaultBranchIcon(entry.node)} {entry.node.label} + {#if entry.node.badge} + {entry.node.badge} + {/if} {#if entry.node.loading} {/if} @@ -767,6 +928,8 @@ leaves and ignores the current scope.
Loading…
+ {:else if currentBranch?.note} +
{currentBranch.note}
{/if}
{/if} diff --git a/frontend/src/lib/components/LoginPageHeader.svelte b/frontend/src/lib/components/LoginPageHeader.svelte index ca5c7eafff..a55a964813 100644 --- a/frontend/src/lib/components/LoginPageHeader.svelte +++ b/frontend/src/lib/components/LoginPageHeader.svelte @@ -3,7 +3,7 @@ import Version from './Version.svelte' import DarkModeToggle from './sidebar/DarkModeToggle.svelte' import WindmillIcon from './icons/WindmillIcon.svelte' - import { whitelabelNameStore } from '$lib/stores' + import { superadmin, whitelabelNameStore } from '$lib/stores' import { capitalize } from '$lib/utils' interface Props { @@ -35,7 +35,10 @@ {#if showVersion}
- + + {#if $superadmin} + + {/if}
{/if}
diff --git a/frontend/src/lib/components/access/GrantNavigator.svelte b/frontend/src/lib/components/access/GrantNavigator.svelte new file mode 100644 index 0000000000..803b0caaaf --- /dev/null +++ b/frontend/src/lib/components/access/GrantNavigator.svelte @@ -0,0 +1,535 @@ + + + + + +{#snippet leafIcon(leaf: DrillLeaf)} + +{/snippet} + + diff --git a/frontend/src/lib/components/access/access.ts b/frontend/src/lib/components/access/access.ts new file mode 100644 index 0000000000..08d8df97bb --- /dev/null +++ b/frontend/src/lib/components/access/access.ts @@ -0,0 +1,70 @@ +import { + GranularAclService, + type BrowseAccessFoldersResponse, + type BrowseAccessItemsResponse +} from '$lib/gen' + +export type GrantLevel = 'none' | 'read' | 'write' + +/** Where the Grant navigator reads and changes grants. Without one it uses the API, in the + * operating workspace. */ +export type GrantSource = { + /** The caller's own `u/` space, listed first. */ + ownSpace: string + folders: () => Promise + items: (query: { + prefix?: string + search?: string + offset?: number + }) => Promise + /** Sets the principal's own entry, as `setGrant` does. */ + set: (kind: string, path: string, level: GrantLevel) => Promise +} + +type AclKind = Parameters[0]['kind'] + +export const KIND_LABELS: Record = { + script: 'Script', + flow: 'Flow', + app: 'App', + raw_app: 'Full-code app', + resource: 'Resource', + variable: 'Variable', + schedule: 'Schedule', + http_trigger: 'HTTP route', + websocket_trigger: 'WebSocket trigger', + kafka_trigger: 'Kafka trigger', + nats_trigger: 'NATS trigger', + postgres_trigger: 'Postgres trigger', + mqtt_trigger: 'MQTT trigger', + amqp_trigger: 'AMQP trigger', + gcp_trigger: 'GCP Pub/Sub trigger', + azure_trigger: 'Azure trigger', + sqs_trigger: 'SQS trigger', + email_trigger: 'Email trigger' +} + +/** Sets `principal`'s own entry on an item or folder (`kind` `folder`, `path` the folder name). */ +export async function setGrant( + workspace: string, + kind: string, + path: string, + principal: string, + level: GrantLevel +): Promise { + if (level === 'none') { + await GranularAclService.removeGranularAcls({ + workspace, + kind: kind as AclKind, + path, + requestBody: { owner: principal } + }) + } else { + await GranularAclService.addGranularAcls({ + workspace, + kind: kind as AclKind, + path, + requestBody: { owner: principal, write: level === 'write' } + }) + } +} diff --git a/frontend/src/lib/components/common/button/Button.svelte b/frontend/src/lib/components/common/button/Button.svelte index 9a3b9fe6ac..e514c0686f 100644 --- a/frontend/src/lib/components/common/button/Button.svelte +++ b/frontend/src/lib/components/common/button/Button.svelte @@ -516,9 +516,11 @@ 'rounded-md m-0 p-0 center-center h-full', variant === 'border' ? 'border-0 border-r border-y ' : 'border-0', 'rounded-r-md !rounded-l-none', - size === 'xs2' || size === 'xs' || unifiedSize === 'md' || unifiedSize === 'sm' - ? '!w-8' - : '!w-10', + unifiedSize === 'xs' || unifiedSize === '2xs' + ? '!w-6' + : size === 'xs2' || size === 'xs' || unifiedSize === 'md' || unifiedSize === 'sm' + ? '!w-8' + : '!w-10', dropdownBtnClasses )} > diff --git a/frontend/src/lib/components/copilot/chat/storageTools.ts b/frontend/src/lib/components/copilot/chat/storageTools.ts index ccf334b123..67482289e7 100644 --- a/frontend/src/lib/components/copilot/chat/storageTools.ts +++ b/frontend/src/lib/components/copilot/chat/storageTools.ts @@ -115,7 +115,7 @@ const listS3FilesToolDef = createToolDef( const readS3FileToolDef = createToolDef( readS3FileSchema, 'read_s3_file', - "Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text or JSON file, the columns, their types and the first 50 rows of a CSV, TSV, NDJSON or Parquet file, or the image itself for a png, jpeg, gif or webp of up to 3.75 MB, which you then see. Other files return their metadata only." + "Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text or JSON file, the columns, their types and the first 50 rows of a CSV, TSV, NDJSON or Parquet file, or the image itself for a png, jpeg, gif or webp of up to 30 MB, which you then see (one past 3.75 MB or 8000 px comes as a smaller JPEG copy). Other files return their metadata only." ) const queryS3TableToolDef = createToolDef( queryS3TableSchema, diff --git a/frontend/src/lib/components/drillPicker.ts b/frontend/src/lib/components/drillPicker.ts index 7ef6922599..2461a7687f 100644 --- a/frontend/src/lib/components/drillPicker.ts +++ b/frontend/src/lib/components/drillPicker.ts @@ -35,6 +35,19 @@ export type DrillLeaf = { plainLabel?: boolean } +/** Something a leaf row offers (see the picker's `leafActions`). */ +export type DrillLeafAction = { + label: string + icon?: DrillIcon + /** What running it does, shown under its label in the row's dropdown. */ + hint?: string + /** The row's button, with the others in its dropdown; the first one is otherwise. */ + preferred?: boolean + loading?: boolean + disabled?: boolean + run: () => void +} + /** Branch node — interior entry the user drills into. */ export type DrillBranch = { type: 'branch' @@ -44,6 +57,11 @@ export type DrillBranch = { children: DrillNode[] /** Show a spinner alongside the branch (async loading in progress). */ loading?: boolean + /** Plain text on the right of the branch's row ("Read"), like a leaf's `leafBadge`. */ + badge?: string + /** A line under the branch's entries once drilled in and loaded, for a branch whose entries + * never leave it empty ("f/x has no items yet"), so the picker's "Empty" cannot show. */ + note?: string /** Hide from search index traversal. Used by the workspace adapter to * keep the cross-kind 'all' branch out of search (its leaves are * duplicates of the per-kind branches' leaves). */ diff --git a/frontend/src/lib/components/home/HomeConnectDrawer.svelte b/frontend/src/lib/components/home/HomeConnectDrawer.svelte index 3530da35fa..964b7b8738 100644 --- a/frontend/src/lib/components/home/HomeConnectDrawer.svelte +++ b/frontend/src/lib/components/home/HomeConnectDrawer.svelte @@ -1,6 +1,7 @@
@@ -590,7 +496,7 @@ {item} value="custom" label="Custom" - tooltip="Select exactly which scripts, flows, and endpoints to expose" + tooltip="Select exactly which scripts and flows to expose" /> {/snippet} @@ -680,56 +586,8 @@ {/if}
- {#if !runnablesOnly} -
- {@render sectionHeader('API Endpoints', selectAllEndpoints, clearAllEndpoints)} - e.name))} - placeholder="Select endpoints" - bind:value={selectedEndpoints} - /> -
- {/if} - - {#if !runnablesOnly && withheldEndpoints.length > 0} - - - Endpoints that cannot be limited to specific script paths are withheld from a token - restricted to a script selection: {withheldEndpoints.join(', ')}. Widening the script - wildcard pattern to * exposes them, and keeps the run tools below available. - - - {/if} - - {#if !runnablesOnly && runByPathTools.length > 0} -
- Run tools -

- Running a script or flow by path is granted by the Scripts and Flows selections above, - not by the endpoint list, so a token can never run something outside its scope. -

-
- {#each runByPathTools as tool (tool.name)} -
- {tool.name} - - {#if tool.exposed} - exposed - {:else} - not exposed — select at least one {tool.resource} above, or add a {tool.resource} - wildcard pattern - {/if} - -
- {/each} -
-
- {/if} -
- Selected: {selectedScripts.length} scripts, {selectedFlows.length} flows{#if !runnablesOnly}, - {selectedEndpoints.length} - endpoints{/if} + Selected: {selectedScripts.length} scripts, {selectedFlows.length} flows
@@ -786,51 +644,25 @@ {:else}
- {#if !readOnly} - Scripts & Flows that will be available via MCP -
- {#if includedRunnables.length > 0 && includedRunnables.length <= 5} - {#each includedRunnables as scriptOrFlow (scriptOrFlow)} - {scriptOrFlow} - {/each} - {:else if includedRunnables.length > 0} - {#each includedRunnables.slice(0, 3) as scriptOrFlow (scriptOrFlow)} - {scriptOrFlow} - {/each} - - +{includedRunnables.length - 3} more - - {:else} -

- {warning} -

- {/if} -
- {:else} -

- Scripts and flows are hidden because this token is read-only. -

- {/if} - - {#if !runnablesOnly} - API endpoint tools that will be available via MCP -
- {#each exposedEndpointTools as endpoint (endpoint.name)} - - {#snippet text()} -
-
{endpoint.description}
-
- {endpoint.method} - {endpoint.path} -
-
- {/snippet} - {endpoint.name} -
+ Scripts & Flows that will be available via MCP +
+ {#if includedRunnables.length > 0 && includedRunnables.length <= 5} + {#each includedRunnables as scriptOrFlow (scriptOrFlow)} + {scriptOrFlow} {/each} -
- {/if} + {:else if includedRunnables.length > 0} + {#each includedRunnables.slice(0, 3) as scriptOrFlow (scriptOrFlow)} + {scriptOrFlow} + {/each} + + +{includedRunnables.length - 3} more + + {:else} +

+ {warning} +

+ {/if} +
{/if} {/if} diff --git a/frontend/src/lib/components/mcp/McpUpgradeNotice.svelte b/frontend/src/lib/components/mcp/McpUpgradeNotice.svelte new file mode 100644 index 0000000000..ff3e103b64 --- /dev/null +++ b/frontend/src/lib/components/mcp/McpUpgradeNotice.svelte @@ -0,0 +1,121 @@ + + +{#if listed.length > 0} + + + + (open = false)} + > +
+

+ We rebuilt the MCP toolset for building on Windmill. Your AI client gets the same tools as + Windmill's AI sessions, to build apps, flows, triggers, data tables and AI agents. +

+
    + {#each listed as token (token.token_prefix)} +
  • + +
  • + {/each} +
+

This cannot be undone from this page.

+
+
+{/if} diff --git a/frontend/src/lib/components/mcp/endpointScopePolicy.test.ts b/frontend/src/lib/components/mcp/endpointScopePolicy.test.ts deleted file mode 100644 index 86832f6c44..0000000000 --- a/frontend/src/lib/components/mcp/endpointScopePolicy.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - endpointPathPolicy, - isEndpointExposed, - parseMcpScopeState, - pruneEndpointSelection -} from './endpointScopePolicy' -import { mcpEndpointTools } from '$lib/mcpEndpointTools' - -const state = (...scopes: string[]) => parseMcpScopeState(scopes) - -describe('isEndpointExposed', () => { - it('gates run-by-path tools on the script/flow scope, not the endpoint scope', () => { - // Selecting the endpoint without any script path exposes nothing... - const endpointsOnly = state('mcp:endpoints:runScriptByPath,listScripts') - expect(isEndpointExposed(endpointsOnly, 'runScriptByPath')).toBe(false) - expect(isEndpointExposed(endpointsOnly, 'listScripts')).toBe(true) - - // ...while a script path exposes it without any endpoint scope. - expect(isEndpointExposed(state('mcp:scripts:f/team/*'), 'runScriptByPath')).toBe(true) - expect(isEndpointExposed(state('mcp:scripts:f/team/*'), 'runFlowByPath')).toBe(false) - - // Favorites reach their runnables through per-item tools only. - expect(isEndpointExposed(state('mcp:favorites'), 'runScriptByPath')).toBe(false) - expect(isEndpointExposed(state('mcp:all'), 'runScriptByPath')).toBe(true) - }) - - // A script/flow tool the URL addresses by path but the policy does not name falls - // through to "no policy", which is "not path-confined at all" — a scoped token then - // reaches every path of that kind. Catch the omission here rather than in a review. - it('gives every path-addressed script/flow tool a policy', () => { - const unpoliced = mcpEndpointTools - .filter((e) => /\/(scripts|flows)\//.test(e.path) && e.path.includes('{path}')) - .map((e) => e.name) - .filter((name) => endpointPathPolicy(name) === undefined) - expect(unpoliced).toEqual([]) - }) - - it('withholds unconfinable tools from path-confined tokens', () => { - const confined = state('mcp:scripts:f/team/*', 'mcp:endpoints:*') - expect(isEndpointExposed(confined, 'runScriptPreviewAndWaitResult')).toBe(false) - expect(isEndpointExposed(confined, 'getScriptByPath')).toBe(true) - - // A `*` script pattern is not a confinement. - expect( - isEndpointExposed(state('mcp:scripts:*', 'mcp:endpoints:*'), 'runScriptPreviewAndWaitResult') - ).toBe(true) - }) -}) - -describe('pruneEndpointSelection', () => { - it('keeps a `*` endpoint scope, which would otherwise revoke every endpoint tool', () => { - expect(pruneEndpointSelection(['*'], false)).toEqual(['*']) - expect(pruneEndpointSelection(['*'], true)).toEqual(['*']) - }) - - it('drops only names the endpoint scope cannot honor', () => { - expect(pruneEndpointSelection(['runScriptByPath', 'listScripts'], false)).toEqual([ - 'listScripts' - ]) - // Non-GET endpoints go only when the token is read-only. - expect(pruneEndpointSelection(['createScript', 'listScripts'], false)).toEqual([ - 'createScript', - 'listScripts' - ]) - expect(pruneEndpointSelection(['createScript', 'listScripts'], true)).toEqual(['listScripts']) - }) -}) diff --git a/frontend/src/lib/components/mcp/endpointScopePolicy.ts b/frontend/src/lib/components/mcp/endpointScopePolicy.ts deleted file mode 100644 index 2b9fecd136..0000000000 --- a/frontend/src/lib/components/mcp/endpointScopePolicy.ts +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Mirrors `endpoint_path_policy` / `endpoint_tool_in_scope` in - * backend/windmill-mcp/src/server/runner.rs. Two endpoint tools are not governed - * by the `mcp:endpoints:` scope at all, and two more are hidden from tokens - * confined to specific script paths — without mirroring that here, the scope - * picker advertises tools the server will never list. - */ - -import { mcpEndpointTools } from '$lib/mcpEndpointTools' - -export type McpResourceKind = 'script' | 'flow' - -export type EndpointPathPolicy = - /** Runs the script/flow named by the `path` argument. Listed when the token - * grants at least one path of that kind; the endpoint scope is ignored. */ - | { kind: 'runByPath'; resource: McpResourceKind } - /** Reads/writes a script/flow named by a path argument, itself confined to - * the token's path patterns. Listed by the endpoint scope. */ - | { kind: 'pathArgs'; resource: McpResourceKind } - /** Takes no checkable path (delete-by-hash) or runs arbitrary code - * (preview); hidden from tokens confined to specific paths. */ - | { kind: 'unconfinable'; resource: McpResourceKind } - -export function endpointPathPolicy(name: string): EndpointPathPolicy | undefined { - switch (name) { - case 'runScriptByPath': - return { kind: 'runByPath', resource: 'script' } - case 'runFlowByPath': - return { kind: 'runByPath', resource: 'flow' } - case 'getScriptByPath': - case 'deleteScriptByPath': - case 'createScript': - case 'updateScript': - return { kind: 'pathArgs', resource: 'script' } - case 'getFlowByPath': - case 'deleteFlowByPath': - case 'createFlow': - case 'updateFlow': - return { kind: 'pathArgs', resource: 'flow' } - case 'deleteScriptByHash': - case 'runScriptPreviewAndWaitResult': - return { kind: 'unconfinable', resource: 'script' } - default: - return undefined - } -} - -/** The parsed shape of an MCP token's scopes, as `McpScopeConfig` on the backend. */ -export type McpScopeState = { - /** Legacy `mcp:all` — grants every path and endpoint. */ - all: boolean - /** Legacy `mcp:favorites` — reaches favorites through per-item tools only. */ - favorites: boolean - scripts: string[] - flows: string[] - endpoints: string[] -} - -function parseResourceList(resources: string): string[] { - return resources - .split(',') - .map((s) => s.trim()) - .filter((s) => s.length > 0) -} - -/** Mirrors `parse_mcp_scopes` so the picker can preview exactly what the server - * will make of the scope string it is about to emit. `mcp:hub:` is deliberately - * ignored: hub apps select which hub scripts become tools and never affect - * endpoint-tool exposure. */ -export function parseMcpScopeState(scopes: string[]): McpScopeState { - const state: McpScopeState = { - all: false, - favorites: false, - scripts: [], - flows: [], - endpoints: [] - } - for (const scope of scopes) { - if (scope === 'mcp:all') { - state.all = true - state.scripts.push('*') - state.flows.push('*') - state.endpoints.push('*') - } else if (scope === 'mcp:favorites') { - state.favorites = true - } else if (scope.startsWith('mcp:all:')) { - const folder = scope.slice('mcp:all:'.length) - state.scripts.push(folder) - state.flows.push(folder) - state.endpoints.push('*') - } else if (scope.startsWith('mcp:scripts:')) { - state.scripts.push(...parseResourceList(scope.slice('mcp:scripts:'.length))) - } else if (scope.startsWith('mcp:flows:')) { - state.flows.push(...parseResourceList(scope.slice('mcp:flows:'.length))) - } else if (scope.startsWith('mcp:endpoints:')) { - state.endpoints.push(...parseResourceList(scope.slice('mcp:endpoints:'.length))) - } - } - return state -} - -function patterns(state: McpScopeState, resource: McpResourceKind): string[] { - return resource === 'script' ? state.scripts : state.flows -} - -/** Whether the token grants access to any concrete path of this kind. */ -function hasAnyResource(state: McpScopeState, resource: McpResourceKind): boolean { - return state.all || patterns(state, resource).length > 0 -} - -/** Whether the token restricts this kind to specific paths. A `*` pattern grants - * every path, so it is not a confinement. */ -function isPathConfined(state: McpScopeState, resource: McpResourceKind): boolean { - if (state.all) return false - const list = patterns(state, resource) - return list.length > 0 && !list.includes('*') -} - -function matchesPattern(name: string, pattern: string): boolean { - if (pattern === name) return true - if (!pattern.endsWith('/*')) return false - const prefix = pattern.slice(0, -2) - if (!name.startsWith(prefix)) return false - return name.length === prefix.length || name[prefix.length] === '/' -} - -/** Mirrors `is_resource_allowed`: whether a path (or endpoint name) is granted by - * any of these patterns, where a pattern is `*`, an exact path, or `/*`. */ -export function matchesAnyPattern(path: string, patterns: string[]): boolean { - if (patterns.length === 0) return false - if (patterns.includes('*')) return true - return patterns.some((pattern) => matchesPattern(path, pattern)) -} - -const nonGetEndpoints = new Set( - mcpEndpointTools.filter((e) => e.method !== 'GET').map((e) => e.name) -) - -/** Strip from an `mcp:endpoints:` selection only the names that scope cannot - * honor: run-by-path tools, which `isEndpointExposed` gates on the script/flow - * scope instead, and — for a read-only token — the non-GET endpoints the server - * refuses. Every other entry is preserved, notably a `*` wildcard, which is a - * valid endpoint scope that dropping would silently revoke every endpoint tool. */ -export function pruneEndpointSelection(selected: string[], readOnly: boolean): string[] { - return selected.filter( - (name) => - endpointPathPolicy(name)?.kind !== 'runByPath' && !(readOnly && nonGetEndpoints.has(name)) - ) -} - -/** Whether the server will list this endpoint tool for a token with these scopes. */ -export function isEndpointExposed(state: McpScopeState, name: string): boolean { - const granular = !state.all && !state.favorites - const endpointAllowed = !granular || matchesAnyPattern(name, state.endpoints) - const policy = endpointPathPolicy(name) - switch (policy?.kind) { - case 'runByPath': - return hasAnyResource(state, policy.resource) - case 'unconfinable': - return endpointAllowed && !isPathConfined(state, policy.resource) - default: - return endpointAllowed - } -} diff --git a/frontend/src/lib/components/mcp/mcpUpgrade.test.ts b/frontend/src/lib/components/mcp/mcpUpgrade.test.ts new file mode 100644 index 0000000000..cef38133b8 --- /dev/null +++ b/frontend/src/lib/components/mcp/mcpUpgrade.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { canUpgradeMcpScopes } from './mcpUpgrade' + +describe('canUpgradeMcpScopes', () => { + it('takes an unmarked mcp:all token alone', () => { + expect(canUpgradeMcpScopes(['mcp:all'])).toBe(true) + expect(canUpgradeMcpScopes(['mcp:all', 'mcp:workspaces:a,b'])).toBe(true) + expect(canUpgradeMcpScopes(['mcp:favorites'])).toBe(false) + expect(canUpgradeMcpScopes(['mcp:all:f/x/*'])).toBe(false) + expect(canUpgradeMcpScopes([])).toBe(false) + }) + + it('leaves out a token that already gets the session toolset', () => { + expect(canUpgradeMcpScopes(['mcp:all', 'mcp:session'])).toBe(false) + expect(canUpgradeMcpScopes(['mcp:all', 'mcp:read_only'])).toBe(false) + expect(canUpgradeMcpScopes(['mcp:all', 'mcp:read_run'])).toBe(false) + }) + + it('leaves out a token the upgrade would take something from', () => { + expect(canUpgradeMcpScopes(['mcp:all', 'mcp:hub:slack'])).toBe(false) + expect(canUpgradeMcpScopes(['mcp:all', 'variables:read:u/a/*'])).toBe(false) + expect(canUpgradeMcpScopes(['mcp:all', 'if_jobs:filter_tags:gpu'])).toBe(true) + }) +}) diff --git a/frontend/src/lib/components/mcp/mcpUpgrade.ts b/frontend/src/lib/components/mcp/mcpUpgrade.ts new file mode 100644 index 0000000000..79abe0c7c4 --- /dev/null +++ b/frontend/src/lib/components/mcp/mcpUpgrade.ts @@ -0,0 +1,31 @@ +import type { TruncatedToken } from '$lib/gen' +import { MCP_SESSION, RUNNABLES_AS_TOOLS } from './McpAccessPicker.svelte' + +const RECENT_MS = 30 * 24 * 60 * 60 * 1000 + +/** Scopes that already decide the toolset of an `mcp:all` token. */ +const DECIDED = [MCP_SESSION, RUNNABLES_AS_TOOLS, 'mcp:read_only', 'mcp:read_run'] + +/** Whether adding `mcp:session` moves this token from the endpoint tools to the session toolset + * without losing anything else: the session toolset has no hub scripts as tools, and refuses a + * token carrying a non-MCP scope (`admits` in backend/windmill-mcp/src/server/session.rs). */ +export function canUpgradeMcpScopes(scopes: string[]): boolean { + return ( + scopes.includes('mcp:all') && + scopes.every( + (s) => + (s.startsWith('mcp:') && !s.startsWith('mcp:hub:') && !DECIDED.includes(s)) || + s.startsWith('if_jobs:filter_tags:') + ) + ) +} + +/** Recently used tokens the upgrade applies to. */ +export function upgradableMcpTokens(tokens: TruncatedToken[], now = Date.now()): TruncatedToken[] { + return tokens.filter( + (t) => + canUpgradeMcpScopes(t.scopes ?? []) && + now - Date.parse(t.last_used_at) < RECENT_MS && + (!t.expiration || Date.parse(t.expiration) > now) + ) +} diff --git a/frontend/src/lib/components/mcp/scopePatterns.ts b/frontend/src/lib/components/mcp/scopePatterns.ts new file mode 100644 index 0000000000..ac01385d73 --- /dev/null +++ b/frontend/src/lib/components/mcp/scopePatterns.ts @@ -0,0 +1,15 @@ +function matchesPattern(name: string, pattern: string): boolean { + if (pattern === name) return true + if (!pattern.endsWith('/*')) return false + const prefix = pattern.slice(0, -2) + if (!name.startsWith(prefix)) return false + return name.length === prefix.length || name[prefix.length] === '/' +} + +/** Mirrors `is_resource_allowed` in backend/windmill-mcp/src/common/scope.rs: whether a path is + * granted by any of these patterns, where a pattern is `*`, an exact path, or `/*`. */ +export function matchesAnyPattern(path: string, patterns: string[]): boolean { + if (patterns.length === 0) return false + if (patterns.includes('*')) return true + return patterns.some((pattern) => matchesPattern(path, pattern)) +} diff --git a/frontend/src/lib/components/offboarding-utils.ts b/frontend/src/lib/components/offboarding-utils.ts index b920979b7f..d9f5b584cd 100644 --- a/frontend/src/lib/components/offboarding-utils.ts +++ b/frontend/src/lib/components/offboarding-utils.ts @@ -109,6 +109,8 @@ export function itemHref(kind: string, path: string): string | undefined { case 'app': case 'apps': return `/apps/get/${path}` + case 'raw_app': + return `/apps_raw/get/${path}` case 'resource': case 'resources': return `/resources#/resource/${path}` diff --git a/frontend/src/lib/components/raw_apps/RawAppPreview.svelte b/frontend/src/lib/components/raw_apps/RawAppPreview.svelte index b8a316b235..8ec2d2a190 100644 --- a/frontend/src/lib/components/raw_apps/RawAppPreview.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppPreview.svelte @@ -221,6 +221,28 @@ port.postMessage(payload) } + /** Fetches a bundle file for a sandboxed wrapper whose own request failed: from its + * opaque origin it cannot send a proxy's cookie, this page can. Nonce-gated and sent + * on the asker's port, as in `respondCtx`. The text enters the sandbox, so it must be + * the bundle and not, say, the proxy's login page: no redirect, exact content type. */ + async function respondAsset(ext: unknown, nonceEcho: unknown, port?: MessagePort) { + if (!port || nonceEcho !== handshakeNonce || (ext !== 'js' && ext !== 'css')) return + let text: string | undefined = undefined + try { + const res = await fetch(`/api/w/${workspace}/apps_u/get_data/v/${secret}.${ext}`, { + redirect: 'error' + }) + const contentType = res.headers.get('content-type')?.split(';')[0].trim() + if (!res.ok || contentType !== (ext === 'js' ? 'text/javascript' : 'text/css')) { + throw new Error(`unexpected response: ${res.status} ${contentType}`) + } + text = await res.text() + } catch (e) { + console.error(`Could not load the raw app's ${ext} bundle`, e) + } + port.postMessage(text) + } + onMount(() => { initialHash = pageHash() if (framed) { @@ -286,6 +308,8 @@ pendingNonce = nonceEcho pendingPort = port } + } else if (data?.type === 'windmill:asset') { + respondAsset(data.ext, data.nonce, event.ports?.[0]) } else if (data?.type === 'wm_ls_op') { // The bundle mutated localStorage — apply it to the shared store. if (!framed) { diff --git a/frontend/src/lib/components/settings/CreateToken.svelte b/frontend/src/lib/components/settings/CreateToken.svelte index 6cdbf8fe97..be637cbb6f 100644 --- a/frontend/src/lib/components/settings/CreateToken.svelte +++ b/frontend/src/lib/components/settings/CreateToken.svelte @@ -753,12 +753,7 @@ {#if !scopes || scopes.length === 0}
- +
{/if} diff --git a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte index a892501b84..47c5993b20 100644 --- a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte +++ b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte @@ -255,12 +255,7 @@ /> {:else} - + {/if} {/key} diff --git a/frontend/src/lib/components/settings/ScopesPicker.svelte b/frontend/src/lib/components/settings/ScopesPicker.svelte index 5532783205..d5289135d7 100644 --- a/frontend/src/lib/components/settings/ScopesPicker.svelte +++ b/frontend/src/lib/components/settings/ScopesPicker.svelte @@ -1,113 +1,70 @@ -{#if mode === 'standard'} -
- - {#if limited && standardScopes.length === 0} -

- Pick at least one scope: with none picked, the token is not restricted. -

- {/if} - {#if limited} - - {#snippet topSlot()} - - {/snippet} - - {/if} -
-{:else} -
-
- -
- -
-{/if} +
+ + {#if limited && standardScopes.length === 0} +

+ Pick at least one scope: with none picked, the token is not restricted. +

+ {/if} + {#if limited} + + {#snippet topSlot()} + + {/snippet} + + {/if} +
diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 987bfcb333..1c6329286e 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -330,6 +330,21 @@ const cookieDomain = isolateDevAuth ? '' : 'localhost' // with it so that one worktree's login does not stand for another's session. const sessionHintCookie = isolateDevAuth ? `${authCookie}_hint` : 'wm_session' +// `changeOrigin` rewrites Host to the backend's, so pass on the host the browser addressed: +// over plain http to a LAN or Tailscale address there is no Sec-Fetch-Site, and the backend's +// cross-site check (request_site.rs) then matches Origin against the hosts it can see. +function forwardHost(proxy) { + proxy.on('proxyReq', (proxyReq, req) => { + if (req.headers.host && !req.headers['x-forwarded-host']) + proxyReq.setHeader('x-forwarded-host', req.headers.host) + }) +} + +function configureApiProxy(proxy) { + forwardHost(proxy) + isolateAuthCookie(proxy) +} + function isolateAuthCookie(proxy) { if (!isolateDevAuth) return proxy.on('proxyReq', (proxyReq, req) => { @@ -454,7 +469,7 @@ const config = { target: remoteUrl, changeOrigin: true, cookieDomainRewrite: cookieDomain, - configure: isolateAuthCookie + configure: configureApiProxy }, '^/api/w/[^/]+/s3_proxy/.*': { target: remoteUrl, @@ -474,7 +489,7 @@ const config = { target: remoteUrl, changeOrigin: true, cookieDomainRewrite: cookieDomain, - configure: isolateAuthCookie + configure: configureApiProxy }, '^/ws/.*': { target: process.env.REMOTE_LSP ?? process.env.REMOTE_EXTRA ?? 'https://app.windmill.dev', diff --git a/lsp/Pipfile b/lsp/Pipfile index cd9d2cb8f5..97514fa56e 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.894.1" +wmill = ">=1.895.1" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index bd5a0a34b2..da59954f6f 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.894.1 + version: 1.895.1 title: OpenFlow Spec contact: name: Ruben Fiszel diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index 300f32579d..94fa5ed1ed 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.894.1' + ModuleVersion = '1.895.1' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index 781e7ec1ed..f8caa4dcd5 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.894.1" +version = "1.895.1" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index cc3c137c4b..5bcbea9eef 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.894.1", + "version": "1.895.1", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts", "./taskParams.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index 519357529d..fcb05a6373 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.894.1", + "version": "1.895.1", "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 577ffe58b0..825ef83382 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.894.1 +1.895.1 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index 4da9a39a00..e113e94b91 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.894.1", + "version": "1.895.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.894.1", + "version": "1.895.1", "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 f80ecff785..6464e53b19 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.894.1", + "version": "1.895.1", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts",