diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 129af2ee98..7805631ded 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.854.2" + ".": "1.856.0" } diff --git a/AGENTS.md b/AGENTS.md index 1d564d346a..4c99482d43 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,7 @@ Open-source platform for internal tools, workflows, API integrations, background - **Domain vocabulary**: `CONTEXT.md` — the words this codebase uses for its own concepts (step, step setting, trigger step, …). Name things the way it does. - **CLI commands**: when adding/modifying/removing a command, subcommand, option, or description in `cli/src/commands/`, run `python system_prompts/generate.py` to refresh `system_prompts/auto-generated/` and `cli/src/guidance/skills.gen.ts`. The CLI docs the agents use to operate `wmill` are derived from the source — stale generated files give agents the wrong flags. - **AI guidance** (chat prompts and CLI skills): what the AI knows about Windmill itself — how flows, scripts, apps, pipelines and resources work — is written once, in `system_prompts/base/` and `system_prompts/languages/`, and `system_prompts/generate.py` builds both the chat's `$system_prompts` exports and the CLI's skills from it. Add or change such guidance there, never inline in one consumer: a sentence only one side should see goes in a `` / `` block, and a new file reaches both through the `TOPICS` table. The chat prompt builders under `frontend/src/lib/components/copilot/chat/` add only tool plumbing and runtime values, and shared markdown names no chat tool, since it reaches every chat mode. Rerun `generate.py` after editing; `system_prompts/README.md` has the details. -- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/mcp/session/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `session/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). What a tool *does* is written twice, in `chat/global/core.ts` and in a Rust handler: a behaviour change on one side must be mirrored on the other, and a new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `session/mod.rs` fails otherwise). For MCP Apps clients the server adds tools of its own, defined in Rust (`session/views.rs`) rather than generated: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v` view (`session/card.html`; bump `CARD_URI` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. It exists only on the MCP side, so `core.ts` has nothing to mirror. +- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/mcp/session/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `session/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). What a tool *does* is written twice, in `chat/global/core.ts` and in a Rust handler: a behaviour change on one side must be mirrored on the other, and a new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `session/mod.rs` fails otherwise). For MCP Apps clients the server adds tools of its own, defined in Rust (`session/views.rs`) rather than generated: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v` view (`session/card.html`; bump `CARD_URI` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. It exists only on the MCP side, so `core.ts` has nothing to mirror. - **Session recorder**: `frontend/src/lib/components/recording/` is also the recorder `wmill app dev --recording` serves, vendored into the CLI as `cli/src/commands/app/devRecorderBundle.gen.ts`. After changing `rawAppSnapshot.ts` or `rawAppRecording.svelte.ts`, run `bun run gen:dev-recorder` from `cli/` (`cli/test/dev_recorder_bundle_unit.test.ts` fails otherwise). - **Raw-app policy**: `frontend/src/lib/components/raw_apps/rawAppPolicy.ts` also derives the policy the server's raw-app deploy stores, vendored into the bundle job as `backend/windmill-api/src/apps_raw_policy.gen.js`. After changing it or anything it imports, run `bun run gen:app-policy` from `cli/` (`cli/test/app_policy_bundle_unit.test.ts` fails otherwise). It rides in the job rather than being read from the CLI the job runs because the images install `windmill-cli` unpinned, so an image can carry one older than its server. diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bb48df9c0..f3a0451e5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,47 @@ # Changelog +## [1.856.0](https://github.com/windmill-labs/windmill/compare/v1.855.1...v1.856.0) (2026-11-02) + + +### Features + +* accept MCP access tokens from an external OIDC issuer ([#12085](https://github.com/windmill-labs/windmill/issues/12085)) ([45f256a](https://github.com/windmill-labs/windmill/commit/45f256a5a1046b80833dda217e5884f9eeb6a3a4)) +* reference existing HashiCorp Vault secrets from secret variables ([#12078](https://github.com/windmill-labs/windmill/issues/12078)) ([6f4124e](https://github.com/windmill-labs/windmill/commit/6f4124e9a030ce790e484dd75917a2c04b889bd3)) +* sync custom workspace roles and role overrides through the CLI ([#12139](https://github.com/windmill-labs/windmill/issues/12139)) ([5956976](https://github.com/windmill-labs/windmill/commit/5956976ea5a0798b965453c3fbfed8f4476e70e7)) +* working folders and folder instructions for ai sessions ([#12036](https://github.com/windmill-labs/windmill/issues/12036)) ([6444b20](https://github.com/windmill-labs/windmill/commit/6444b20abd3abea8c41dc631a481f42f217566c9)) + + +### Bug Fixes + +* let scoped tokens reach shared_ui routes through the apps scope ([#12141](https://github.com/windmill-labs/windmill/issues/12141)) ([8e57691](https://github.com/windmill-labs/windmill/commit/8e57691cbcf1db8af4c9994d8f9486bcb0c8abd8)) + +## [1.855.1](https://github.com/windmill-labs/windmill/compare/v1.855.0...v1.855.1) (2026-10-30) + + +### Bug Fixes + +* list only the reader's own ai chats in the sidebar ([#12134](https://github.com/windmill-labs/windmill/issues/12134)) ([a8b84fc](https://github.com/windmill-labs/windmill/commit/a8b84fc21149a49304bd41af583c1cf9d2205c9c)) + +## [1.855.0](https://github.com/windmill-labs/windmill/compare/v1.854.2...v1.855.0) (2026-10-30) + + +### Features + +* link to the groups page wherever a group can be picked ([#12125](https://github.com/windmill-labs/windmill/issues/12125)) ([efcffb5](https://github.com/windmill-labs/windmill/commit/efcffb511798442b69b027ccef1e53dffa7d895a)) +* one home and ai sessions in the sidebar ([#12126](https://github.com/windmill-labs/windmill/issues/12126)) ([af836f1](https://github.com/windmill-labs/windmill/commit/af836f1ca61c663fffdb87cfada6a0399f720733)) + + +### Bug Fixes + +* **debugger:** require coding capability to sign debug sessions ([#12119](https://github.com/windmill-labs/windmill/issues/12119)) ([384295b](https://github.com/windmill-labs/windmill/commit/384295b6bc2c4089ed6356b9b512d2054524189e)) +* hide empty folder chevrons and size tree skeleton to item count ([#12128](https://github.com/windmill-labs/windmill/issues/12128)) ([2f9a493](https://github.com/windmill-labs/windmill/commit/2f9a49320be3a8490f92540658d774457adc4208)) +* keep secret values out of stored step inputs from flow_env ([#12130](https://github.com/windmill-labs/windmill/issues/12130)) ([37b1ea2](https://github.com/windmill-labs/windmill/commit/37b1ea23f93dcf052351b7cdb2fb52ace5bf6469)) +* list hand-edited session items in the session changes bar ([#12131](https://github.com/windmill-labs/windmill/issues/12131)) ([df70cd1](https://github.com/windmill-labs/windmill/commit/df70cd14c527117847916bee7f2bdab64542f756)) +* merge auto-add and instance groups into one popover ([#12100](https://github.com/windmill-labs/windmill/issues/12100)) ([633d176](https://github.com/windmill-labs/windmill/commit/633d176a3eb5a801ce76ab27d37635010aae8ac6)) +* move a session's return route only for a deploy in its workspace ([#12117](https://github.com/windmill-labs/windmill/issues/12117)) ([ac795bc](https://github.com/windmill-labs/windmill/commit/ac795bcd2564a9a14bd06a5c92aad6ef5ae517a8)) +* move leave workspace out of the settings menu ([#12123](https://github.com/windmill-labs/windmill/issues/12123)) ([1c8d60d](https://github.com/windmill-labs/windmill/commit/1c8d60dd4397e25e778cca56bab2e0cbdad8783b)) +* report a failed flow unless its failure module succeeded ([#12127](https://github.com/windmill-labs/windmill/issues/12127)) ([068f959](https://github.com/windmill-labs/windmill/commit/068f95907f264208d711c1049e2459fc59b7907b)) + ## [1.854.2](https://github.com/windmill-labs/windmill/compare/v1.854.1...v1.854.2) (2026-10-30) diff --git a/backend/.sqlx/query-3e0f2e6febdf289aeccbea6b3258be507e8c2fa86c8006bb32b5c0660497c128.json b/backend/.sqlx/query-3e0f2e6febdf289aeccbea6b3258be507e8c2fa86c8006bb32b5c0660497c128.json new file mode 100644 index 0000000000..3b8f6e370c --- /dev/null +++ b/backend/.sqlx/query-3e0f2e6febdf289aeccbea6b3258be507e8c2fa86c8006bb32b5c0660497c128.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT is_secret AND value NOT LIKE '$external:%' AS \"is_secret!\" FROM variable WHERE path = $1 AND workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "is_secret!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "3e0f2e6febdf289aeccbea6b3258be507e8c2fa86c8006bb32b5c0660497c128" +} diff --git a/backend/.sqlx/query-4985970f9ea9e0e7644e9fe3f81fc2fe29682ec0673bf29d8ee21a313bef6bd6.json b/backend/.sqlx/query-4985970f9ea9e0e7644e9fe3f81fc2fe29682ec0673bf29d8ee21a313bef6bd6.json new file mode 100644 index 0000000000..0449c10bf4 --- /dev/null +++ b/backend/.sqlx/query-4985970f9ea9e0e7644e9fe3f81fc2fe29682ec0673bf29d8ee21a313bef6bd6.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT path FROM variable WHERE workspace_id = $1 AND path = ANY($2) AND is_secret", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "TextArray" + ] + }, + "nullable": [ + false + ] + }, + "hash": "4985970f9ea9e0e7644e9fe3f81fc2fe29682ec0673bf29d8ee21a313bef6bd6" +} diff --git a/backend/.sqlx/query-0c8a3eb810c96230ba3a5466c55bf24a94eb8a52ceb82cc29dade173ad87569d.json b/backend/.sqlx/query-6c9efac7fba0e3f2f34510bb6e2a1757af5286183faf888c7313f3a657705850.json similarity index 70% rename from backend/.sqlx/query-0c8a3eb810c96230ba3a5466c55bf24a94eb8a52ceb82cc29dade173ad87569d.json rename to backend/.sqlx/query-6c9efac7fba0e3f2f34510bb6e2a1757af5286183faf888c7313f3a657705850.json index e68f16713a..02d147af11 100644 --- a/backend/.sqlx/query-0c8a3eb810c96230ba3a5466c55bf24a94eb8a52ceb82cc29dade173ad87569d.json +++ b/backend/.sqlx/query-6c9efac7fba0e3f2f34510bb6e2a1757af5286183faf888c7313f3a657705850.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT path FROM variable WHERE path = ANY($1) AND workspace_id = $2 AND is_secret = true", + "query": "SELECT path FROM variable WHERE path = ANY($1) AND workspace_id = $2 AND is_secret = true AND value NOT LIKE '$external:%'", "describe": { "columns": [ { @@ -19,5 +19,5 @@ false ] }, - "hash": "0c8a3eb810c96230ba3a5466c55bf24a94eb8a52ceb82cc29dade173ad87569d" + "hash": "6c9efac7fba0e3f2f34510bb6e2a1757af5286183faf888c7313f3a657705850" } diff --git a/backend/.sqlx/query-6445041033c95fcf52c79c33f34cf6c41fb443f8bd91f12bce0e53f6e91bfb16.json b/backend/.sqlx/query-7a24557a10d6fced22c3180827ffe7c4035f9f1b5dfe257358a5a47077d528fd.json similarity index 95% rename from backend/.sqlx/query-6445041033c95fcf52c79c33f34cf6c41fb443f8bd91f12bce0e53f6e91bfb16.json rename to backend/.sqlx/query-7a24557a10d6fced22c3180827ffe7c4035f9f1b5dfe257358a5a47077d528fd.json index abcdf7baab..89a905e2d3 100644 --- a/backend/.sqlx/query-6445041033c95fcf52c79c33f34cf6c41fb443f8bd91f12bce0e53f6e91bfb16.json +++ b/backend/.sqlx/query-7a24557a10d6fced22c3180827ffe7c4035f9f1b5dfe257358a5a47077d528fd.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "UPDATE v2_job_status SET\n flow_status = JSONB_SET(\n JSONB_SET(v2_job_status.flow_status, $2::TEXT[], $3),\n $4::TEXT[], $5\n ) - $6::TEXT[],\n flow_leaf_jobs = CASE\n WHEN $7::TEXT IS NULL\n OR COALESCE(v2_job.flow_innermost_root_job, v2_job_status.id) <> v2_job_status.id\n THEN v2_job_status.flow_leaf_jobs\n ELSE JSONB_SET(COALESCE(v2_job_status.flow_leaf_jobs, '{}'::JSONB), ARRAY[$7::TEXT], $8) END\n FROM v2_job_queue INNER JOIN v2_job ON v2_job.id = v2_job_queue.id\n LEFT JOIN job_perms ON job_perms.job_id = v2_job_queue.id\n WHERE v2_job_status.id = $1 AND v2_job_queue.id = $1\n RETURNING\n v2_job_queue.workspace_id,\n v2_job_queue.id,\n v2_job.args as \"args: sqlx::types::Json>>\",\n v2_job.parent_job,\n v2_job.created_by,\n v2_job_queue.started_at,\n v2_job_queue.runnable_settings_handle,\n v2_job_queue.scheduled_for,\n v2_job.runnable_path,\n v2_job.kind as \"kind: JobKind\",\n v2_job.runnable_id as \"runnable_id: ScriptHash\",\n v2_job_queue.canceled_reason,\n v2_job_queue.canceled_by,\n v2_job.permissioned_as,\n v2_job.permissioned_as_email,\n v2_job_status.flow_status as \"flow_status: sqlx::types::Json>\",\n v2_job.tag,\n v2_job.script_lang as \"script_lang: ScriptLang\",\n v2_job.same_worker,\n v2_job.pre_run_error,\n v2_job.concurrent_limit,\n v2_job.concurrency_time_window_s,\n v2_job.flow_innermost_root_job,\n v2_job.root_job,\n v2_job.timeout,\n v2_job.flow_step_id,\n v2_job.cache_ttl,\n v2_job_queue.cache_ignore_s3_path,\n v2_job_queue.priority,\n v2_job.preprocessed,\n v2_job.script_entrypoint_override,\n v2_job.trigger,\n v2_job.trigger_kind as \"trigger_kind: TriggerKindLabel\",\n v2_job.visible_to_owner,\n NULL as permissioned_as_end_user_email,\n job_perms.job_token_scopes", + "query": "UPDATE v2_job_status SET\n flow_status = JSONB_SET(\n JSONB_SET(v2_job_status.flow_status, $2::TEXT[], $3),\n $4::TEXT[], $5\n ) - $6::TEXT[],\n flow_leaf_jobs = CASE\n WHEN $7::TEXT IS NULL\n OR COALESCE(v2_job.flow_innermost_root_job, v2_job_status.id) <> v2_job_status.id\n THEN v2_job_status.flow_leaf_jobs\n ELSE JSONB_SET(COALESCE(v2_job_status.flow_leaf_jobs, '{}'::JSONB), ARRAY[$7::TEXT], $8) END\n FROM v2_job_queue INNER JOIN v2_job ON v2_job.id = v2_job_queue.id\n LEFT JOIN job_perms ON job_perms.job_id = v2_job_queue.id\n WHERE v2_job_status.id = $1 AND v2_job_queue.id = $1\n RETURNING\n v2_job_queue.workspace_id,\n v2_job_queue.id,\n v2_job.args as \"args: sqlx::types::Json>>\",\n v2_job.parent_job,\n v2_job.created_by,\n v2_job_queue.started_at,\n v2_job_queue.runnable_settings_handle,\n v2_job_queue.scheduled_for,\n v2_job.runnable_path,\n v2_job.kind as \"kind: JobKind\",\n v2_job.runnable_id as \"runnable_id: ScriptHash\",\n v2_job_queue.canceled_reason,\n v2_job_queue.canceled_by,\n v2_job.permissioned_as,\n v2_job.permissioned_as_email,\n v2_job_status.flow_status as \"flow_status: sqlx::types::Json>\",\n v2_job.tag,\n v2_job.script_lang as \"script_lang: ScriptLang\",\n v2_job.same_worker,\n v2_job.pre_run_error,\n v2_job.concurrent_limit,\n v2_job.concurrency_time_window_s,\n v2_job.flow_innermost_root_job,\n v2_job.root_job,\n v2_job.timeout,\n v2_job.flow_step_id,\n v2_job.cache_ttl,\n v2_job_queue.cache_ignore_s3_path,\n v2_job_queue.priority,\n v2_job.preprocessed,\n v2_job.script_entrypoint_override,\n v2_job.trigger,\n v2_job.trigger_kind as \"trigger_kind: TriggerKindLabel\",\n v2_job.visible_to_owner,\n NULL as permissioned_as_end_user_email,\n NULL::boolean as viewer_data_access,\n job_perms.job_token_scopes,\n NULL::varchar as mcp_client", "describe": { "columns": [ { @@ -272,8 +272,18 @@ }, { "ordinal": 35, + "name": "viewer_data_access", + "type_info": "Bool" + }, + { + "ordinal": 36, "name": "job_token_scopes", "type_info": "TextArray" + }, + { + "ordinal": 37, + "name": "mcp_client", + "type_info": "Varchar" } ], "parameters": { @@ -324,8 +334,10 @@ true, false, null, - true + null, + true, + null ] }, - "hash": "6445041033c95fcf52c79c33f34cf6c41fb443f8bd91f12bce0e53f6e91bfb16" + "hash": "7a24557a10d6fced22c3180827ffe7c4035f9f1b5dfe257358a5a47077d528fd" } diff --git a/backend/.sqlx/query-8c71d3c791a65892cffd9feee13a13533e8025824ae697b5be4ed43c5e4fe584.json b/backend/.sqlx/query-8c71d3c791a65892cffd9feee13a13533e8025824ae697b5be4ed43c5e4fe584.json new file mode 100644 index 0000000000..f77eda83a8 --- /dev/null +++ b/backend/.sqlx/query-8c71d3c791a65892cffd9feee13a13533e8025824ae697b5be4ed43c5e4fe584.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COUNT(DISTINCT (workspace_id, path))::BIGINT AS \"count!\"\n FROM script\n WHERE auto_kind = 'pipeline' AND archived = false AND deleted = false\n AND workspace_id NOT LIKE 'wm-fork%'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count!", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "8c71d3c791a65892cffd9feee13a13533e8025824ae697b5be4ed43c5e4fe584" +} diff --git a/backend/.sqlx/query-9926d9e05560e41aae3a1a8036db834d412ea7806eb9bc217c7c3cd98b828b5e.json b/backend/.sqlx/query-9926d9e05560e41aae3a1a8036db834d412ea7806eb9bc217c7c3cd98b828b5e.json new file mode 100644 index 0000000000..89b46c6361 --- /dev/null +++ b/backend/.sqlx/query-9926d9e05560e41aae3a1a8036db834d412ea7806eb9bc217c7c3cd98b828b5e.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT flow_status->'failure_module'->>'type' FROM v2_job_completed WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "9926d9e05560e41aae3a1a8036db834d412ea7806eb9bc217c7c3cd98b828b5e" +} diff --git a/backend/.sqlx/query-9ec675bd675c9915ed56f6cb91ca848b094b61475409156489319cb9d36ef096.json b/backend/.sqlx/query-c8d4d9816fd6a5bd466fc249ca47d6608f48bea5b2a81e086cfd3e144378aa71.json similarity index 93% rename from backend/.sqlx/query-9ec675bd675c9915ed56f6cb91ca848b094b61475409156489319cb9d36ef096.json rename to backend/.sqlx/query-c8d4d9816fd6a5bd466fc249ca47d6608f48bea5b2a81e086cfd3e144378aa71.json index bd3f00aa7d..a86053391d 100644 --- a/backend/.sqlx/query-9ec675bd675c9915ed56f6cb91ca848b094b61475409156489319cb9d36ef096.json +++ b/backend/.sqlx/query-c8d4d9816fd6a5bd466fc249ca47d6608f48bea5b2a81e086cfd3e144378aa71.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT\n v2_job_queue.workspace_id,\n v2_job_queue.id,\n v2_job.args as \"args: sqlx::types::Json>>\",\n v2_job.parent_job,\n v2_job.created_by,\n v2_job_queue.started_at,\n v2_job_queue.runnable_settings_handle,\n scheduled_for,\n runnable_path,\n kind as \"kind: JobKind\",\n runnable_id as \"runnable_id: ScriptHash\",\n canceled_reason,\n canceled_by,\n permissioned_as,\n permissioned_as_email,\n flow_status as \"flow_status: sqlx::types::Json>\",\n v2_job.tag,\n script_lang as \"script_lang: ScriptLang\",\n same_worker,\n pre_run_error,\n concurrent_limit,\n concurrency_time_window_s,\n flow_innermost_root_job,\n root_job,\n timeout,\n flow_step_id,\n cache_ttl,\n cache_ignore_s3_path,\n v2_job_queue.priority,\n preprocessed,\n script_entrypoint_override,\n trigger,\n trigger_kind as \"trigger_kind: TriggerKindLabel\",\n visible_to_owner,\n NULL as permissioned_as_end_user_email,\n NULL::boolean as viewer_data_access,\n job_perms.job_token_scopes\n FROM v2_job_queue INNER JOIN v2_job ON v2_job.id = v2_job_queue.id LEFT JOIN v2_job_status ON v2_job_status.id = v2_job_queue.id\n LEFT JOIN job_perms ON job_perms.job_id = v2_job_queue.id WHERE v2_job_queue.id = $1", + "query": "SELECT\n v2_job_queue.workspace_id,\n v2_job_queue.id,\n v2_job.args as \"args: sqlx::types::Json>>\",\n v2_job.parent_job,\n v2_job.created_by,\n v2_job_queue.started_at,\n v2_job_queue.runnable_settings_handle,\n scheduled_for,\n runnable_path,\n kind as \"kind: JobKind\",\n runnable_id as \"runnable_id: ScriptHash\",\n canceled_reason,\n canceled_by,\n permissioned_as,\n permissioned_as_email,\n flow_status as \"flow_status: sqlx::types::Json>\",\n v2_job.tag,\n script_lang as \"script_lang: ScriptLang\",\n same_worker,\n pre_run_error,\n concurrent_limit,\n concurrency_time_window_s,\n flow_innermost_root_job,\n root_job,\n timeout,\n flow_step_id,\n cache_ttl,\n cache_ignore_s3_path,\n v2_job_queue.priority,\n preprocessed,\n script_entrypoint_override,\n trigger,\n trigger_kind as \"trigger_kind: TriggerKindLabel\",\n visible_to_owner,\n NULL as permissioned_as_end_user_email,\n NULL::boolean as viewer_data_access,\n job_perms.job_token_scopes,\n job_perms.mcp_client\n FROM v2_job_queue INNER JOIN v2_job ON v2_job.id = v2_job_queue.id LEFT JOIN v2_job_status ON v2_job_status.id = v2_job_queue.id\n LEFT JOIN job_perms ON job_perms.job_id = v2_job_queue.id WHERE v2_job_queue.id = $1", "describe": { "columns": [ { @@ -279,6 +279,11 @@ "ordinal": 36, "name": "job_token_scopes", "type_info": "TextArray" + }, + { + "ordinal": 37, + "name": "mcp_client", + "type_info": "Varchar" } ], "parameters": { @@ -323,8 +328,9 @@ false, null, null, + true, true ] }, - "hash": "9ec675bd675c9915ed56f6cb91ca848b094b61475409156489319cb9d36ef096" + "hash": "c8d4d9816fd6a5bd466fc249ca47d6608f48bea5b2a81e086cfd3e144378aa71" } diff --git a/backend/.sqlx/query-da49cdc6f47685c719cb07fc3b120d7f2d589d294fb1beeeba6b47a99210f241.json b/backend/.sqlx/query-da49cdc6f47685c719cb07fc3b120d7f2d589d294fb1beeeba6b47a99210f241.json new file mode 100644 index 0000000000..7022df5899 --- /dev/null +++ b/backend/.sqlx/query-da49cdc6f47685c719cb07fc3b120d7f2d589d294fb1beeeba6b47a99210f241.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT username FROM usr WHERE workspace_id = $1 AND email = $2 AND NOT disabled", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "username", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "da49cdc6f47685c719cb07fc3b120d7f2d589d294fb1beeeba6b47a99210f241" +} diff --git a/backend/.sqlx/query-fd04f65015069792f23edbfce320af6e69ee32b27a8f0a020e251eb2c79e43cd.json b/backend/.sqlx/query-dd548c53f2498d0554584d4fb94183c6826279e1f35dbc3b389f7e3a274ec50f.json similarity index 81% rename from backend/.sqlx/query-fd04f65015069792f23edbfce320af6e69ee32b27a8f0a020e251eb2c79e43cd.json rename to backend/.sqlx/query-dd548c53f2498d0554584d4fb94183c6826279e1f35dbc3b389f7e3a274ec50f.json index 4801a9b5da..0d53a1d0fc 100644 --- a/backend/.sqlx/query-fd04f65015069792f23edbfce320af6e69ee32b27a8f0a020e251eb2c79e43cd.json +++ b/backend/.sqlx/query-dd548c53f2498d0554584d4fb94183c6826279e1f35dbc3b389f7e3a274ec50f.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT email, username, is_admin, is_operator, groups, folders, end_user_email,\n job_token_scopes, viewer_data_access\n FROM job_perms WHERE job_id = $1 AND workspace_id = $2", + "query": "SELECT email, username, is_admin, is_operator, groups, folders, end_user_email,\n job_token_scopes, viewer_data_access, mcp_client\n FROM job_perms WHERE job_id = $1 AND workspace_id = $2", "describe": { "columns": [ { @@ -47,6 +47,11 @@ "ordinal": 8, "name": "viewer_data_access", "type_info": "Bool" + }, + { + "ordinal": 9, + "name": "mcp_client", + "type_info": "Varchar" } ], "parameters": { @@ -64,8 +69,9 @@ false, true, true, - false + false, + true ] }, - "hash": "fd04f65015069792f23edbfce320af6e69ee32b27a8f0a020e251eb2c79e43cd" + "hash": "dd548c53f2498d0554584d4fb94183c6826279e1f35dbc3b389f7e3a274ec50f" } diff --git a/backend/.sqlx/query-0600f2a9179f83502c6b13e8e4284f85ca82636f274f5dce47da5a8320a60088.json b/backend/.sqlx/query-e2c7dcf549dba16f2a36d6495b4c0a550a03af01798dacce24d42fbe01b51f36.json similarity index 77% rename from backend/.sqlx/query-0600f2a9179f83502c6b13e8e4284f85ca82636f274f5dce47da5a8320a60088.json rename to backend/.sqlx/query-e2c7dcf549dba16f2a36d6495b4c0a550a03af01798dacce24d42fbe01b51f36.json index e5aec65b91..ac9ba13b0a 100644 --- a/backend/.sqlx/query-0600f2a9179f83502c6b13e8e4284f85ca82636f274f5dce47da5a8320a60088.json +++ b/backend/.sqlx/query-e2c7dcf549dba16f2a36d6495b4c0a550a03af01798dacce24d42fbe01b51f36.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT workspace_id, path FROM variable WHERE is_secret = true", + "query": "SELECT workspace_id, path FROM variable WHERE is_secret = true AND value NOT LIKE '$external:%'", "describe": { "columns": [ { @@ -22,5 +22,5 @@ false ] }, - "hash": "0600f2a9179f83502c6b13e8e4284f85ca82636f274f5dce47da5a8320a60088" + "hash": "e2c7dcf549dba16f2a36d6495b4c0a550a03af01798dacce24d42fbe01b51f36" } diff --git a/backend/.sqlx/query-095fa75c60724664f0355cd6e3a64f84a0f1a31cd6732c0ab994a2d6ac3c3eec.json b/backend/.sqlx/query-f470d4475ebd131af74be49434dea44c7939bc7b97c4e1104fae6d9b57b7c960.json similarity index 85% rename from backend/.sqlx/query-095fa75c60724664f0355cd6e3a64f84a0f1a31cd6732c0ab994a2d6ac3c3eec.json rename to backend/.sqlx/query-f470d4475ebd131af74be49434dea44c7939bc7b97c4e1104fae6d9b57b7c960.json index 852ce508ff..c52bf8fd56 100644 --- a/backend/.sqlx/query-095fa75c60724664f0355cd6e3a64f84a0f1a31cd6732c0ab994a2d6ac3c3eec.json +++ b/backend/.sqlx/query-f470d4475ebd131af74be49434dea44c7939bc7b97c4e1104fae6d9b57b7c960.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH inserted_job AS (\n INSERT INTO v2_job (\n id, -- 1\n workspace_id, -- 2\n raw_code, -- 3\n raw_lock, -- 4\n raw_flow, -- 5\n tag, -- 6\n parent_job, -- 7\n created_by, -- 8\n permissioned_as, -- 9\n runnable_id, -- 10\n runnable_path, -- 11\n args, -- 12\n kind, -- 13\n trigger, -- 14\n script_lang, -- 15\n same_worker, -- 16\n pre_run_error, -- 17\n permissioned_as_email, -- 18\n visible_to_owner, -- 19\n flow_innermost_root_job, -- 20\n root_job, -- 38\n concurrent_limit, -- 21\n concurrency_time_window_s, -- 22\n timeout, -- 23\n flow_step_id, -- 24\n cache_ttl, -- 25\n priority, -- 26\n trigger_kind, -- 39\n script_entrypoint_override, -- 12\n preprocessed, -- 27,\n labels -- 44\n ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18,\n $19, $20, $38, $21, $22, $23, $24, $25, $26, $39::job_trigger_kind,\n ($12::JSONB)->>'_ENTRYPOINT_OVERRIDE', $27,\n -- $44 (payload labels) merged with the labels of the runnable's folder, if any\n -- ($45/$46 are runnable_path/workspace_id again, kept separate to avoid parameter type conflicts)\n (SELECT CASE WHEN fl.labels IS NULL THEN $44\n ELSE (SELECT array_agg(DISTINCT lbl) FROM unnest(COALESCE($44, ARRAY[]::TEXT[]) || fl.labels) lbl)\n END\n FROM folder_labels($46, $45) AS fl(labels)))\n ),\n inserted_runtime AS (\n INSERT INTO v2_job_runtime (id, ping) VALUES ($1, null)\n ),\n inserted_job_perms AS (\n INSERT INTO job_perms (job_id, email, username, is_admin, is_operator, folders, groups, workspace_id, end_user_email, job_token_scopes)\n values ($1, $32, $33, $34, $35, $36, $37, $2, $41, $47)\n ON CONFLICT (job_id) DO UPDATE SET email = EXCLUDED.email, username = EXCLUDED.username, is_admin = EXCLUDED.is_admin, is_operator = EXCLUDED.is_operator, folders = EXCLUDED.folders, groups = EXCLUDED.groups, workspace_id = EXCLUDED.workspace_id, end_user_email = EXCLUDED.end_user_email, job_token_scopes = EXCLUDED.job_token_scopes\n )\n INSERT INTO v2_job_queue\n (workspace_id, id, running, scheduled_for, started_at, tag, priority, cache_ignore_s3_path, runnable_settings_handle)\n VALUES ($2, $1, $28, COALESCE($29, now()), CASE WHEN $27 OR $40 THEN now() END, $30, $31, $42, $43)", + "query": "WITH inserted_job AS (\n INSERT INTO v2_job (\n id, -- 1\n workspace_id, -- 2\n raw_code, -- 3\n raw_lock, -- 4\n raw_flow, -- 5\n tag, -- 6\n parent_job, -- 7\n created_by, -- 8\n permissioned_as, -- 9\n runnable_id, -- 10\n runnable_path, -- 11\n args, -- 12\n kind, -- 13\n trigger, -- 14\n script_lang, -- 15\n same_worker, -- 16\n pre_run_error, -- 17\n permissioned_as_email, -- 18\n visible_to_owner, -- 19\n flow_innermost_root_job, -- 20\n root_job, -- 38\n concurrent_limit, -- 21\n concurrency_time_window_s, -- 22\n timeout, -- 23\n flow_step_id, -- 24\n cache_ttl, -- 25\n priority, -- 26\n trigger_kind, -- 39\n script_entrypoint_override, -- 12\n preprocessed, -- 27,\n labels -- 44\n ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18,\n $19, $20, $38, $21, $22, $23, $24, $25, $26, $39::job_trigger_kind,\n ($12::JSONB)->>'_ENTRYPOINT_OVERRIDE', $27,\n -- $44 (payload labels) merged with the labels of the runnable's folder, if any\n -- ($45/$46 are runnable_path/workspace_id again, kept separate to avoid parameter type conflicts)\n (SELECT CASE WHEN fl.labels IS NULL THEN $44\n ELSE (SELECT array_agg(DISTINCT lbl) FROM unnest(COALESCE($44, ARRAY[]::TEXT[]) || fl.labels) lbl)\n END\n FROM folder_labels($46, $45) AS fl(labels)))\n ),\n inserted_runtime AS (\n INSERT INTO v2_job_runtime (id, ping) VALUES ($1, null)\n ),\n inserted_job_perms AS (\n INSERT INTO job_perms (job_id, email, username, is_admin, is_operator, folders, groups, workspace_id, end_user_email, job_token_scopes, mcp_client)\n values ($1, $32, $33, $34, $35, $36, $37, $2, $41, $47, $48)\n ON CONFLICT (job_id) DO UPDATE SET email = EXCLUDED.email, username = EXCLUDED.username, is_admin = EXCLUDED.is_admin, is_operator = EXCLUDED.is_operator, folders = EXCLUDED.folders, groups = EXCLUDED.groups, workspace_id = EXCLUDED.workspace_id, end_user_email = EXCLUDED.end_user_email, job_token_scopes = EXCLUDED.job_token_scopes, mcp_client = EXCLUDED.mcp_client\n )\n INSERT INTO v2_job_queue\n (workspace_id, id, running, scheduled_for, started_at, tag, priority, cache_ignore_s3_path, runnable_settings_handle)\n VALUES ($2, $1, $28, COALESCE($29, now()), CASE WHEN $27 OR $40 THEN now() END, $30, $31, $42, $43)", "describe": { "columns": [], "parameters": { @@ -143,10 +143,11 @@ "TextArray", "Text", "Text", - "TextArray" + "TextArray", + "Varchar" ] }, "nullable": [] }, - "hash": "095fa75c60724664f0355cd6e3a64f84a0f1a31cd6732c0ab994a2d6ac3c3eec" + "hash": "f470d4475ebd131af74be49434dea44c7939bc7b97c4e1104fae6d9b57b7c960" } diff --git a/backend/.sqlx/query-fd44d54a93499ce1dab09759cdfcd633774f770c34f5ef70a0583f2a210ef5b1.json b/backend/.sqlx/query-fd44d54a93499ce1dab09759cdfcd633774f770c34f5ef70a0583f2a210ef5b1.json new file mode 100644 index 0000000000..16f9a8696e --- /dev/null +++ b/backend/.sqlx/query-fd44d54a93499ce1dab09759cdfcd633774f770c34f5ef70a0583f2a210ef5b1.json @@ -0,0 +1,32 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COALESCE(j.trigger_kind::text, 'none') AS \"trigger!\",\n (CASE WHEN c.status = 'failure' THEN COALESCE(\n (SELECT rc.status FROM v2_job r\n JOIN native_retry_attempt n ON n.job_id = r.id\n JOIN v2_job_completed rc ON rc.id = r.id\n WHERE r.parent_job = j.id\n ORDER BY n.attempt DESC LIMIT 1),\n c.status) ELSE c.status END)::text AS \"status!\",\n COUNT(*)::BIGINT AS \"count!\"\n FROM (SELECT DISTINCT workspace_id, path FROM script\n WHERE auto_kind = 'pipeline' AND archived = false AND deleted = false\n AND workspace_id NOT LIKE 'wm-fork%') p\n CROSS JOIN LATERAL (\n SELECT id, trigger_kind FROM v2_job\n WHERE workspace_id = p.workspace_id AND runnable_path = p.path\n AND parent_job IS NULL AND kind = 'script'\n AND created_at >= CURRENT_DATE - INTERVAL '1 day'\n AND created_at < CURRENT_DATE\n ) j\n JOIN v2_job_completed c ON c.id = j.id\n GROUP BY 1, 2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "trigger!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "status!", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "count!", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null, + null, + null + ] + }, + "hash": "fd44d54a93499ce1dab09759cdfcd633774f770c34f5ef70a0583f2a210ef5b1" +} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index 0bfa440344..944a20df40 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2858,9 +2858,9 @@ checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" [[package]] name = "crc32fast" -version = "1.5.3" +version = "1.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" dependencies = [ "cfg-if", ] @@ -3088,7 +3088,23 @@ dependencies = [ "cpufeatures 0.2.17", "curve25519-dalek-derive", "digest 0.10.7", - "fiat-crypto", + "fiat-crypto 0.2.9", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "curve25519-dalek-derive", + "digest 0.11.3", + "fiat-crypto 0.3.0", "rustc_version", "subtle", "zeroize", @@ -4053,11 +4069,11 @@ dependencies = [ "cbc", "const-oid 0.9.6", "ctr", - "curve25519-dalek", + "curve25519-dalek 4.1.3", "deno_core", "deno_crypto_provider", "deno_error", - "ecdsa", + "ecdsa 0.16.9", "elliptic-curve 0.13.8", "fips203", "fips205", @@ -4065,8 +4081,8 @@ dependencies = [ "num-traits", "ocb3", "once_cell", - "p256", - "p384", + "p256 0.13.2", + "p384 0.13.1", "p521", "rand 0.8.5", "rsa", @@ -4512,7 +4528,7 @@ dependencies = [ "const-oid 0.9.6", "der_derive", "flagset", - "pem-rfc7468", + "pem-rfc7468 0.7.0", "zeroize", ] @@ -4523,6 +4539,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" dependencies = [ "const-oid 0.10.2", + "pem-rfc7468 1.0.0", "zeroize", ] @@ -5022,11 +5039,26 @@ dependencies = [ "der 0.7.10", "digest 0.10.7", "elliptic-curve 0.13.8", - "rfc6979", + "rfc6979 0.4.0", "signature 2.2.0", "spki 0.7.3", ] +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der 0.8.3", + "digest 0.11.3", + "elliptic-curve 0.14.3", + "rfc6979 0.6.0", + "signature 3.0.0", + "spki 0.8.1", + "zeroize", +] + [[package]] name = "ed25519" version = "2.2.3" @@ -5037,14 +5069,24 @@ dependencies = [ "signature 2.2.0", ] +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "pkcs8 0.11.0", + "signature 3.0.0", +] + [[package]] name = "ed25519-dalek" version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ - "curve25519-dalek", - "ed25519", + "curve25519-dalek 4.1.3", + "ed25519 2.2.3", "rand_core 0.6.4", "serde", "sha2 0.10.9", @@ -5053,6 +5095,21 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek 5.0.0", + "ed25519 3.0.0", + "serde", + "sha2 0.11.1", + "signature 3.0.0", + "subtle", + "zeroize", +] + [[package]] name = "ed448" version = "0.5.0" @@ -5114,7 +5171,7 @@ dependencies = [ "generic-array", "group 0.13.0", "hkdf", - "pem-rfc7468", + "pem-rfc7468 0.7.0", "pkcs8 0.10.2", "rand_core 0.6.4", "sec1 0.7.3", @@ -5133,9 +5190,11 @@ dependencies = [ "base16ct 1.0.0", "crypto-bigint 0.7.10", "crypto-common 0.2.2", + "digest 0.11.3", "ff 0.14.0", "group 0.14.0", "hybrid-array", + "pem-rfc7468 1.0.0", "pkcs8 0.11.0", "rand_core 0.10.1", "sec1 0.8.1", @@ -5396,6 +5455,12 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + [[package]] name = "filetime" version = "0.2.29" @@ -7171,15 +7236,6 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" -[[package]] -name = "itertools" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.11.0" @@ -7343,9 +7399,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -7859,9 +7915,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.34" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "loom" @@ -8493,8 +8549,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "879011babc47a1c7fdf5a935ae3cfe94f34645ca0cac1c7f6424b36fc743d1bf" dependencies = [ "data-encoding", - "ed25519", - "ed25519-dalek", + "ed25519 2.2.3", + "ed25519-dalek 2.2.0", "getrandom 0.2.17", "log", "rand 0.8.5", @@ -8991,21 +9047,22 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] name = "openidconnect" -version = "4.0.1" +version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c6709ba2ea764bbed26bce1adf3c10517113ddea6f2d4196e4851757ef2b2" +checksum = "df0d098a59353679624d406825940139e2b2d554a52b64c9fb1b1bc42a11fe5c" dependencies = [ - "base64 0.21.7", + "base64 0.22.1", "chrono", "dyn-clone", - "ed25519-dalek", + "ed25519-dalek 3.0.0", + "getrandom 0.4.3", "hmac 0.12.1", "http 1.5.0", - "itertools 0.10.5", + "itertools 0.14.0", "log", "oauth2", - "p256", - "p384", + "p256 0.14.0", + "p384 0.14.0", "rand 0.8.5", "rsa", "serde", @@ -9022,9 +9079,9 @@ dependencies = [ [[package]] name = "openssl" -version = "0.10.81" +version = "0.10.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2" dependencies = [ "bitflags 2.13.2", "cfg-if", @@ -9068,9 +9125,9 @@ dependencies = [ [[package]] name = "openssl-sys" -version = "0.9.117" +version = "0.9.118" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae" dependencies = [ "cc", "libc", @@ -9374,24 +9431,51 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" dependencies = [ - "ecdsa", + "ecdsa 0.16.9", "elliptic-curve 0.13.8", - "primeorder", + "primeorder 0.13.6", "sha2 0.10.9", ] +[[package]] +name = "p256" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" +dependencies = [ + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.1", +] + [[package]] name = "p384" version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" dependencies = [ - "ecdsa", + "ecdsa 0.16.9", "elliptic-curve 0.13.8", - "primeorder", + "primeorder 0.13.6", "sha2 0.10.9", ] +[[package]] +name = "p384" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f" +dependencies = [ + "ecdsa 0.17.0", + "elliptic-curve 0.14.3", + "fiat-crypto 0.3.0", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.1", +] + [[package]] name = "p521" version = "0.13.3" @@ -9399,9 +9483,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fc9e2161f1f215afdfce23677034ae137bbd45016a880c2eb3ba8eb95f085b2" dependencies = [ "base16ct 0.2.0", - "ecdsa", + "ecdsa 0.16.9", "elliptic-curve 0.13.8", - "primeorder", + "primeorder 0.13.6", "rand_core 0.6.4", "sha2 0.10.9", ] @@ -9543,6 +9627,15 @@ dependencies = [ "base64ct", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "pep440_rs" version = "0.7.3" @@ -10051,6 +10144,20 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint 0.7.10", + "crypto-common 0.2.2", + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "primeorder" version = "0.13.6" @@ -10060,6 +10167,19 @@ dependencies = [ "elliptic-curve 0.13.8", ] +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve 0.14.3", + "once_cell", + "primefield", + "serdect 0.4.3", + "wnaf", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -11008,6 +11128,16 @@ dependencies = [ "subtle", ] +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint 0.7.10", + "hmac 0.13.0", +] + [[package]] name = "ring" version = "0.16.20" @@ -14895,9 +15025,9 @@ dependencies = [ [[package]] name = "unicode-properties" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" [[package]] name = "unicode-segmentation" @@ -15200,12 +15330,11 @@ checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" [[package]] name = "wasm-bindgen" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "serde", "wasm-bindgen-macro", @@ -15214,9 +15343,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.79" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", "tokio", @@ -15225,9 +15354,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -15235,9 +15364,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", @@ -15248,20 +15377,19 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] [[package]] name = "wasm-bindgen-test" -version = "0.3.79" +version = "0.3.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42" +checksum = "5b4913c0ade07e01ab574b20d2741538f070efa12cb7a1a1e2d5df6ea41cf522" dependencies = [ - "async-trait", "cast", "js-sys", "libm", @@ -15279,9 +15407,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-test-macro" -version = "0.3.79" +version = "0.3.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f" +checksum = "238071aa4c5b268e57d21018621a2e2403c29dd11c55dbdf790ed47fdb9241c0" dependencies = [ "proc-macro2", "quote", @@ -15290,9 +15418,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-test-shared" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe" +checksum = "9ab365ce29ba0232367502b2894556ae77a9c214d33dbf453fdba7f586905918" [[package]] name = "wasm-streams" @@ -15346,9 +15474,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -15496,7 +15624,7 @@ dependencies = [ [[package]] name = "windmill" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-nats", @@ -15586,7 +15714,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.854.2" +version = "1.856.0" dependencies = [ "async-stream", "async-trait", @@ -15621,7 +15749,7 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -15634,7 +15762,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "argon2", @@ -15656,7 +15784,7 @@ dependencies = [ "cron", "dashmap", "datafusion", - "ed25519-dalek", + "ed25519-dalek 2.2.0", "eventsource-stream", "flate2", "futures", @@ -15677,7 +15805,7 @@ dependencies = [ "native-tls", "openidconnect", "openssl", - "p256", + "p256 0.13.2", "pin-project", "postgres-native-tls 0.5.3", "prometheus", @@ -15777,7 +15905,7 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -15801,7 +15929,7 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -15818,7 +15946,7 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "axum", @@ -15844,7 +15972,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.854.2" +version = "1.856.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -15854,7 +15982,7 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -15871,12 +15999,12 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "base64 0.22.1", "chrono", - "ed25519-dalek", + "ed25519-dalek 2.2.0", "hex", "lazy_static", "serde", @@ -15893,7 +16021,7 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "axum", @@ -15916,7 +16044,7 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -15932,7 +16060,7 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -15954,7 +16082,7 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -15976,7 +16104,7 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -15990,7 +16118,7 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-nats", @@ -16026,7 +16154,7 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "axum", @@ -16052,7 +16180,7 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -16080,7 +16208,7 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "axum", @@ -16102,7 +16230,7 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -16122,7 +16250,7 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "axum", @@ -16164,14 +16292,14 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "axum", "base64 0.22.1", "bytes", "chrono", - "ed25519-dalek", + "ed25519-dalek 2.2.0", "futures", "lazy_static", "regex", @@ -16194,7 +16322,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.854.2" +version = "1.856.0" dependencies = [ "lazy_static", "serde", @@ -16206,7 +16334,7 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.854.2" +version = "1.856.0" dependencies = [ "argon2", "axum", @@ -16230,7 +16358,7 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -16245,7 +16373,7 @@ dependencies = [ [[package]] name = "windmill-api-workspaces" -version = "1.854.2" +version = "1.856.0" dependencies = [ "axum", "chrono", @@ -16284,7 +16412,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.854.2" +version = "1.856.0" dependencies = [ "chrono", "lazy_static", @@ -16299,7 +16427,7 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "axum", @@ -16318,7 +16446,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.854.2" +version = "1.856.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -16374,7 +16502,7 @@ dependencies = [ "opentelemetry-otlp 0.30.0", "opentelemetry-semantic-conventions 0.30.0", "opentelemetry_sdk 0.30.0", - "p256", + "p256 0.13.2", "pep440_rs", "phf 0.11.3", "pin-project-lite", @@ -16436,7 +16564,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.854.2" +version = "1.856.0" dependencies = [ "chrono", "futures", @@ -16456,7 +16584,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.854.2" +version = "1.856.0" dependencies = [ "regex", "serde", @@ -16473,7 +16601,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -16500,7 +16628,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "futures", @@ -16517,7 +16645,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.854.2" +version = "1.856.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -16533,7 +16661,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -16555,7 +16683,7 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -16586,7 +16714,7 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "arc-swap", @@ -16611,7 +16739,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-stream", @@ -16647,7 +16775,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "futures", @@ -16666,7 +16794,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.854.2" +version = "1.856.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -16675,7 +16803,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -16687,7 +16815,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "serde_json", @@ -16699,7 +16827,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "gosyn", @@ -16711,7 +16839,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -16723,7 +16851,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "serde_json", @@ -16735,7 +16863,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "nu-parser", @@ -16746,7 +16874,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16757,7 +16885,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16769,7 +16897,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16780,7 +16908,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-recursion", @@ -16803,7 +16931,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "serde_json", @@ -16815,7 +16943,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -16829,7 +16957,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16846,7 +16974,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -16859,7 +16987,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "serde", @@ -16871,7 +16999,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -16889,7 +17017,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16905,7 +17033,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -16922,7 +17050,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -16936,7 +17064,7 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-recursion", @@ -16975,7 +17103,7 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "const_format", @@ -17013,7 +17141,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.854.2" +version = "1.856.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -17024,7 +17152,7 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-recursion", @@ -17059,7 +17187,7 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17083,7 +17211,7 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17116,7 +17244,7 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17143,7 +17271,7 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17176,7 +17304,7 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17196,7 +17324,7 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17230,7 +17358,7 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17267,7 +17395,7 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17290,7 +17418,7 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17314,7 +17442,7 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-nats", @@ -17338,7 +17466,7 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17373,7 +17501,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17401,7 +17529,7 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-trait", @@ -17427,7 +17555,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -17446,7 +17574,7 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-once-cell", @@ -17564,7 +17692,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.854.2" +version = "1.856.0" dependencies = [ "bytes", "futures", @@ -18126,6 +18254,18 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "primefield", +] + [[package]] name = "writeable" version = "0.6.4" @@ -18147,7 +18287,7 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" dependencies = [ - "curve25519-dalek", + "curve25519-dalek 4.1.3", "rand_core 0.6.4", "serde", "zeroize", @@ -18423,18 +18563,18 @@ dependencies = [ [[package]] name = "zstd" -version = "0.13.3" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +checksum = "cdb02c3132d251ab1606e9fc913a7da6c6ed08cc263df15edf082e1dc497d157" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "7.3.0" +version = "7.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +checksum = "1c8ea04668f5de8d8d51051714ba560c9536519cadcdb8829bba4fe2ad159b03" dependencies = [ "zstd-sys", ] diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 90d078cd20..7b7b7ccc83 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.854.2" +version = "1.856.0" authors.workspace = true edition.workspace = true @@ -88,7 +88,7 @@ members = [ exclude = ["./windmill-duckdb-ffi-internal", "./parsers/windmill-parser-wasm"] [workspace.package] -version = "1.854.2" +version = "1.856.0" authors = ["Ruben Fiszel "] edition = "2021" diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 17bdde30cb..44a2ea704c 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -26663361632280a25b964e6f3944e503dca2a366 +303e60fa90f55b08fa04d5c71319c96392f3fc6c diff --git a/backend/migrations/20261028160214_mcp_client_on_jobs.down.sql b/backend/migrations/20261028160214_mcp_client_on_jobs.down.sql new file mode 100644 index 0000000000..0b943547c0 --- /dev/null +++ b/backend/migrations/20261028160214_mcp_client_on_jobs.down.sql @@ -0,0 +1 @@ +ALTER TABLE job_perms DROP COLUMN IF EXISTS mcp_client; diff --git a/backend/migrations/20261028160214_mcp_client_on_jobs.up.sql b/backend/migrations/20261028160214_mcp_client_on_jobs.up.sql new file mode 100644 index 0000000000..a69c935baf --- /dev/null +++ b/backend/migrations/20261028160214_mcp_client_on_jobs.up.sql @@ -0,0 +1 @@ +ALTER TABLE job_perms ADD COLUMN IF NOT EXISTS mcp_client VARCHAR(255); diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index 62042c5a6b..1c9737d9cd 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.854.2" +version = "1.856.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -6430,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.854.2" +version = "1.856.0" dependencies = [ "proc-macro2", "quote", @@ -6442,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.854.2" +version = "1.856.0" dependencies = [ "convert_case", "serde", @@ -6451,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -6463,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "serde_json", @@ -6475,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "gosyn", @@ -6487,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -6499,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "serde_json", @@ -6511,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "nu-parser", @@ -6522,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6533,7 +6533,7 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6545,7 +6545,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-asset" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6556,7 +6556,7 @@ dependencies = [ [[package]] name = "windmill-parser-py-imports" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "async-recursion", @@ -6579,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "serde_json", @@ -6591,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -6605,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "convert_case", @@ -6622,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -6635,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "serde", @@ -6647,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -6665,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6681,7 +6681,7 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "ruff_python_ast", @@ -6698,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6730,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "lazy_static", @@ -6744,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.854.2" +version = "1.856.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index faaf0264ef..4213ae64e5 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.854.2" +version = "1.856.0" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/src/main.rs b/backend/src/main.rs index 4ffc55aff5..0b3a06a15d 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -2053,6 +2053,9 @@ async fn process_notify_event( MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING => { load_mcp_disable_token_query_param(db).await; } + windmill_common::global_settings::MCP_EXTERNAL_IDP_SETTING => { + crate::monitor::load_mcp_external_idp(db).await; + } API_BASE_URL_SETTING => { load_api_base_url(db).await; } diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index 8ec3c33bb0..9ee707113a 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -311,6 +311,11 @@ pub async fn initial_load( false, |v| async move { apply_mcp_disable_token_query_param(v) }, ); + pass.setting( + windmill_common::global_settings::MCP_EXTERNAL_IDP_SETTING, + false, + |v| async move { apply_mcp_external_idp(v) }, + ); pass.setting(API_BASE_URL_SETTING, false, |v| async move { apply_api_base_url(v) }); @@ -1746,6 +1751,31 @@ pub fn apply_mcp_disable_token_query_param(value: Option) { }; } +pub async fn load_mcp_external_idp(db: &DB) { + match load_value_from_global_settings( + db, + windmill_common::global_settings::MCP_EXTERNAL_IDP_SETTING, + ) + .await + { + Ok(v) => apply_mcp_external_idp(v), + Err(e) => tracing::error!("Error loading mcp_external_idp setting: {e:#}"), + }; +} + +pub fn apply_mcp_external_idp(value: Option) { + use windmill_common::global_settings::{parse_mcp_external_idp, MCP_EXTERNAL_IDP}; + match parse_mcp_external_idp(value.as_ref()) { + Ok(idp) => MCP_EXTERNAL_IDP.store(idp.map(std::sync::Arc::new)), + // Refused at write time, so only a hand-written row lands here: keep no issuer + // rather than one half-read. + Err(e) => { + tracing::error!("Invalid mcp_external_idp setting, external MCP tokens disabled: {e}"); + MCP_EXTERNAL_IDP.store(None); + } + } +} + pub async fn load_api_base_url(db: &DB) { match load_value_from_global_settings(db, API_BASE_URL_SETTING).await { Ok(v) => apply_api_base_url(v), diff --git a/backend/tests/access_view.rs b/backend/tests/access_view.rs index fd62e0b2c4..38b2dde5e7 100644 --- a/backend/tests/access_view.rs +++ b/backend/tests/access_view.rs @@ -31,6 +31,26 @@ async fn test_member_cannot_read_another_members_access(db: Pool) -> a .await?; assert_eq!(resp.status(), 200, "{}", resp.text().await?); + // A scoped token reaches the route only if `/access` maps to a scope domain. + let scoped = client + .post(format!( + "http://localhost:{}/api/users/tokens/create", + server.addr.port() + )) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .json(&serde_json::json!({ "label": "scoped", "scopes": ["acls:read"], "workspace_id": "test-workspace" })) + .send() + .await? + .text() + .await?; + let resp = client + .get(&url) + .query(&[("principal", "u/test-user-2")]) + .header("Authorization", format!("Bearer {scoped}")) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + Ok(()) } diff --git a/backend/tests/end_user_email.rs b/backend/tests/end_user_email.rs index 7fad5ab5ef..bde142ef69 100644 --- a/backend/tests/end_user_email.rs +++ b/backend/tests/end_user_email.rs @@ -359,6 +359,7 @@ async fn test_job_token_run_keeps_end_user_email(db: Pool) -> anyhow:: folders: vec![], scopes: None, token_prefix: None, + mcp_client: None, }, "test-workspace", 3600, diff --git a/backend/tests/inline_preview_auth.rs b/backend/tests/inline_preview_auth.rs index 231e71e92a..ec7042a4af 100644 --- a/backend/tests/inline_preview_auth.rs +++ b/backend/tests/inline_preview_auth.rs @@ -77,6 +77,7 @@ async fn operator_job_token(job_id: uuid::Uuid) -> String { folders: vec![], scopes: None, token_prefix: None, + mcp_client: None, }; create_jwt_token( authed, diff --git a/backend/tests/postgres_trigger_scope.rs b/backend/tests/postgres_trigger_scope.rs index 1080138eb0..7171812fa9 100644 --- a/backend/tests/postgres_trigger_scope.rs +++ b/backend/tests/postgres_trigger_scope.rs @@ -26,6 +26,7 @@ fn scoped_authed(scopes: Vec<&str>) -> ApiAuthed { read_only: false, job_id: None, credential_expiry: None, + mcp_client: None, } } diff --git a/backend/tests/reserved_control_args.rs b/backend/tests/reserved_control_args.rs index a733546e51..6e019cd591 100644 --- a/backend/tests/reserved_control_args.rs +++ b/backend/tests/reserved_control_args.rs @@ -90,6 +90,7 @@ fn trigger_authed() -> windmill_api_auth::ApiAuthed { read_only: false, job_id: None, credential_expiry: None, + mcp_client: None, } } diff --git a/backend/tests/trigger_listener_queries.rs b/backend/tests/trigger_listener_queries.rs index 0af99136e7..88dcab82ac 100644 --- a/backend/tests/trigger_listener_queries.rs +++ b/backend/tests/trigger_listener_queries.rs @@ -179,6 +179,7 @@ fn make_authed() -> windmill_api_auth::ApiAuthed { read_only: false, job_id: None, credential_expiry: None, + mcp_client: None, } } diff --git a/backend/tests/wm_token_confinement.rs b/backend/tests/wm_token_confinement.rs index e15d33354e..af5974f85a 100644 --- a/backend/tests/wm_token_confinement.rs +++ b/backend/tests/wm_token_confinement.rs @@ -51,6 +51,7 @@ async fn wm_token(email: &str, is_admin: bool) -> String { folders: vec![], scopes: None, token_prefix: None, + mcp_client: None, }; create_jwt_token( authed, @@ -1127,6 +1128,7 @@ async fn test_privilege_gates_reject_a_job_token_directly( read_only: false, job_id, credential_expiry: None, + mcp_client: None, } } diff --git a/backend/windmill-api-assets/tests/dbt_pinned_graph.rs b/backend/windmill-api-assets/tests/dbt_pinned_graph.rs index ebeee49ecc..ac9b5b740c 100644 --- a/backend/windmill-api-assets/tests/dbt_pinned_graph.rs +++ b/backend/windmill-api-assets/tests/dbt_pinned_graph.rs @@ -36,6 +36,7 @@ fn outsider() -> ApiAuthed { read_only: false, job_id: None, credential_expiry: None, + mcp_client: None, } } diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index a4a9d41a50..9a9ef691fb 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -347,6 +347,7 @@ impl AuthCache { read_only: false, job_id: None, credential_expiry: Some(credential_expiry), + mcp_client: None, }; AUTH_CACHE.insert( key, @@ -392,6 +393,7 @@ impl AuthCache { read_only: false, job_id: None, credential_expiry: None, + mcp_client: claims.mcp_client, }; // Fail closed: a `job_id` claim that does not parse must reject // the token rather than resolve to `None`, which would clear the @@ -523,6 +525,7 @@ impl AuthCache { read_only, job_id: None, credential_expiry: None, + mcp_client: None, }) } else { tracing::warn!( @@ -577,6 +580,7 @@ impl AuthCache { read_only, job_id: None, credential_expiry: None, + mcp_client: None, }) } else { tracing::warn!( @@ -676,6 +680,7 @@ impl AuthCache { read_only, job_id: None, credential_expiry: None, + mcp_client: None, }) } None if super_admin => { @@ -701,6 +706,7 @@ impl AuthCache { read_only, job_id: None, credential_expiry: None, + mcp_client: None, }), Err(e) => { tracing::error!( @@ -739,6 +745,7 @@ impl AuthCache { read_only, job_id: None, credential_expiry: None, + mcp_client: None, }) } None => None, @@ -759,6 +766,7 @@ impl AuthCache { read_only, job_id: None, credential_expiry: None, + mcp_client: None, }) } } @@ -798,6 +806,7 @@ impl AuthCache { read_only: false, job_id: None, credential_expiry: None, + mcp_client: None, }; Some(OptJobAuthed { authed, job_id: None }) } else { @@ -1172,6 +1181,7 @@ fn no_auth_admin_authed() -> ApiAuthed { read_only: false, job_id: None, credential_expiry: None, + mcp_client: None, } } diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index 6a09710b5e..e3f4b8f6d9 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -90,6 +90,9 @@ pub struct ApiAuthed { /// 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`. 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`. + pub mcp_client: Option, } impl ApiAuthed { @@ -157,6 +160,7 @@ impl From for Authed { folders: value.folders, scopes: value.scopes, token_prefix: value.token_prefix, + mcp_client: value.mcp_client, } } } @@ -178,6 +182,7 @@ impl From for ApiAuthed { read_only: false, job_id: None, credential_expiry: None, + mcp_client: value.mcp_client, } } } @@ -1099,6 +1104,7 @@ pub async fn fetch_api_authed_from_permissioned_as( read_only: false, job_id: None, credential_expiry: None, + mcp_client: None, }; API_AUTHED_CACHE.insert( diff --git a/backend/windmill-api-auth/src/scopes.rs b/backend/windmill-api-auth/src/scopes.rs index bdbab1bfe7..b5f082a6b4 100644 --- a/backend/windmill-api-auth/src/scopes.rs +++ b/backend/windmill-api-auth/src/scopes.rs @@ -1473,6 +1473,19 @@ mod tests { ); } + #[test] + fn test_shared_ui_routes_use_apps_scopes() { + let scopes = |s: &[&str]| s.iter().map(|s| s.to_string()).collect::>(); + for route in ["shared_ui/get", "shared_ui/list", "shared_ui/version"] { + let route = format!("/api/w/ws/{route}"); + assert!(check_route_access(&scopes(&["apps:read"]), &route, "GET").is_ok()); + assert!(check_route_access(&scopes(&["scripts:read"]), &route, "GET").is_err()); + } + let put = "/api/w/ws/shared_ui"; + assert!(check_route_access(&scopes(&["apps:write"]), put, "PUT").is_ok()); + assert!(check_route_access(&scopes(&["apps:read"]), put, "PUT").is_err()); + } + #[test] fn test_flow_conversations_scope_access() { let read_scopes = vec!["flow_conversations:read".to_string()]; diff --git a/backend/windmill-api-flow-conversations/src/lib.rs b/backend/windmill-api-flow-conversations/src/lib.rs index 2ed3531cca..69eda7d2d8 100644 --- a/backend/windmill-api-flow-conversations/src/lib.rs +++ b/backend/windmill-api-flow-conversations/src/lib.rs @@ -68,6 +68,8 @@ pub enum ConversationKind { pub struct ListConversationsQuery { pub flow_path: Option, pub kind: Option, + /// Only the caller's own chats: an admin otherwise lists every user's. + pub mine: Option, } #[derive(Deserialize)] @@ -103,6 +105,10 @@ async fn list_conversations( sqlb.and_where_eq("flow_path", "?".bind(flow_path)); } + if query.mine.unwrap_or(false) { + sqlb.and_where_eq("created_by", "?".bind(&authed.username)); + } + match query.kind.unwrap_or_default() { ConversationKind::Test => { sqlb.and_where_eq("is_test", "true"); diff --git a/backend/windmill-api-groups/src/access.rs b/backend/windmill-api-groups/src/access.rs index 11d726341c..e67b67a240 100644 --- a/backend/windmill-api-groups/src/access.rs +++ b/backend/windmill-api-groups/src/access.rs @@ -225,7 +225,8 @@ fn check_principal<'a>(authed: &ApiAuthed, principal: &'a str) -> Result<(&'a st }; if !allowed { return Err(Error::PermissionDenied( - "only workspace admins can view another member's access".into(), + "only workspace admins can view the access of another member or of a group you are not in" + .into(), )); } Ok((prefix, name)) @@ -278,7 +279,10 @@ async fn get_access( } }; - let target = fetch_authed_from_permissioned_as(&principal, &email, &w_id, &db).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(); if target.is_admin { return Ok(Json(AccessReport { @@ -353,12 +357,10 @@ async fn get_access( }) .collect(); - let mut groups = target.groups; - groups.sort(); Ok(Json(AccessReport { principal, is_admin: false, - groups, + groups: target.groups, folders, items, })) diff --git a/backend/windmill-api-integration-tests/tests/flow_env_secret_refs.rs b/backend/windmill-api-integration-tests/tests/flow_env_secret_refs.rs new file mode 100644 index 0000000000..0cefff6342 --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/flow_env_secret_refs.rs @@ -0,0 +1,104 @@ +//! A secret reached through `flow_env` is stored on the step job as a reference (exact +//! `flow_env.X` read) or encrypted (computed from it), and still resolves when the step runs. +//! A subflow step, which resolves nothing in its args, gets a secret entry as a reference or +//! encrypted, and the resolved value of a non-secret one. +//! +//! cargo test -p windmill-api-integration-tests --features deno_core --test flow_env_secret_refs +#![cfg(feature = "deno_core")] + +use serde_json::json; +use sqlx::{Pool, Postgres}; +use windmill_common::{flows::FlowValue, jobs::JobPayload}; +use windmill_test_utils::*; + +async fn api_create(port: u16, kind: &str, body: serde_json::Value) { + let resp = reqwest::Client::new() + .post(format!( + "http://localhost:{port}/api/w/test-workspace/{kind}/create" + )) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&body) + .send() + .await + .unwrap(); + assert_eq!( + resp.status(), + 201, + "{}", + resp.text().await.unwrap_or_default() + ); +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_flow_env_secret_kept_out_of_step_args(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let secret = "flow_env_secret_value_8k2q"; + for (path, value, is_secret) in [ + ("u/test-user/tok", secret, true), + ("u/test-user/host", "example.com", false), + ] { + let body = json!({"path": path, "value": value, "is_secret": is_secret, "description": ""}); + api_create(port, "variables", body).await; + } + // A flow without steps returns its own inputs. + let sub = json!({"path": "u/test-user/sub", "summary": "", "description": "", + "schema": {"type": "object", "properties": {}}, "value": {"modules": []}}); + api_create(port, "flows", sub).await; + + let flow: FlowValue = serde_json::from_value(json!({ + "flow_env": {"TOKEN": "$var:u/test-user/tok", "HOST": "$var:u/test-user/host"}, + "modules": [ + {"id": "a", "value": { + "type": "rawscript", + "language": "bash", + "content": "tok=\"$1\"\nhdr=\"$2\"\nurl=\"$3\"\necho \"{\\\"tok\\\":\\\"$tok\\\",\\\"hdr\\\":\\\"$hdr\\\",\\\"url\\\":\\\"$url\\\"}\" > result.json", + "input_transforms": { + "tok": {"type": "javascript", "expr": "flow_env.TOKEN"}, + "hdr": {"type": "javascript", "expr": "\"Bearer \" + flow_env.TOKEN"}, + "url": {"type": "javascript", "expr": "\"https://\" + flow_env.HOST"} + } + }}, + {"id": "s", "value": { + "type": "flow", + "path": "u/test-user/sub", + "input_transforms": { + "tok": {"type": "javascript", "expr": "flow_env.TOKEN"}, + "hdr": {"type": "javascript", "expr": "\"Bearer \" + flow_env.TOKEN"}, + "host": {"type": "javascript", "expr": "flow_env.HOST"} + } + }} + ] + }))?; + + let flow_job = + RunJob::from(JobPayload::RawFlow { value: flow, path: None, restarted_from: None }) + .run_until_complete(&db, false, port) + .await; + let sub_args = flow_job.json_result().unwrap(); + assert_eq!(sub_args["tok"], "$var:u/test-user/tok"); + assert!(sub_args["hdr"].as_str().unwrap().starts_with("$encrypted:")); + assert_eq!(sub_args["host"], "example.com"); + + let (step_args, step_result): (serde_json::Value, serde_json::Value) = sqlx::query_as( + "SELECT j.args, c.result FROM v2_job j JOIN v2_job_completed c ON c.id = j.id + WHERE j.parent_job = $1 AND j.kind <> 'flow'", + ) + .bind(flow_job.id) + .fetch_one(&db) + .await?; + assert_eq!( + step_result, + json!({"tok": secret, "hdr": format!("Bearer {secret}"), "url": "https://example.com"}) + ); + assert_eq!(step_args["tok"], "$var:u/test-user/tok"); + assert!(step_args["hdr"] + .as_str() + .unwrap() + .starts_with("$encrypted:")); + assert_eq!(step_args["url"], "https://example.com"); + assert!(!step_args.to_string().contains(secret)); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/native_triggers.rs b/backend/windmill-api-integration-tests/tests/native_triggers.rs index 285d560588..df4efea019 100644 --- a/backend/windmill-api-integration-tests/tests/native_triggers.rs +++ b/backend/windmill-api-integration-tests/tests/native_triggers.rs @@ -67,6 +67,7 @@ fn test_authed() -> ApiAuthed { read_only: false, job_id: None, credential_expiry: None, + mcp_client: None, } } diff --git a/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs b/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs index a1bb7876c6..43342907d6 100644 --- a/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs +++ b/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs @@ -105,6 +105,7 @@ async fn test_preview_on_behalf_of(db: Pool) -> anyhow::Result<()> { folders: vec![], scopes: None, token_prefix: None, + mcp_client: None, }, "test-workspace", 3600, diff --git a/backend/windmill-api-jobs/src/execution.rs b/backend/windmill-api-jobs/src/execution.rs index 9a63e392d0..22af9b641b 100644 --- a/backend/windmill-api-jobs/src/execution.rs +++ b/backend/windmill-api-jobs/src/execution.rs @@ -1054,7 +1054,7 @@ pub async fn run_flow<'c>( ( &obo.email, obo.permissioned_as.clone(), - None, + authed.mcp_client.is_some().then(|| authed.clone().into()), PushIsolationLevel::IsolatedRoot(db.clone()), ) } else { @@ -1286,7 +1286,7 @@ pub async fn push_script_job_by_path_into_queue<'c>( ( on_behalf_of.email.as_str(), on_behalf_of.permissioned_as.clone(), - None, + authed.mcp_client.is_some().then(|| authed.clone().into()), PushIsolationLevel::IsolatedRoot(db.clone()), ) } else { diff --git a/backend/windmill-api-settings/src/lib.rs b/backend/windmill-api-settings/src/lib.rs index 7efb0c75da..6ed4e5ae48 100644 --- a/backend/windmill-api-settings/src/lib.rs +++ b/backend/windmill-api-settings/src/lib.rs @@ -1286,6 +1286,10 @@ async fn run_setting_pre_write_hook( windmill_common::global_settings::validate_api_base_url_applies_to(value) .map_err(|e| error::Error::BadRequest(format!("{key}: {e}")))?; } + windmill_common::global_settings::MCP_EXTERNAL_IDP_SETTING => { + windmill_common::global_settings::parse_mcp_external_idp(Some(value)) + .map_err(|e| error::Error::BadRequest(format!("{key}: {e}")))?; + } MAX_TOKEN_EXPIRATION_DAYS_SETTING => { windmill_common::global_settings::parse_max_token_expiration_days(Some(value)) .map_err(|e| { diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index df59d80ba1..2b1e88292e 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -772,7 +772,8 @@ async fn whoami( authed: ApiAuthed, ) -> JsonResult { let is_guest = windmill_api_auth::scopes::has_guest_sentinel(authed.scopes.as_deref()); - let ApiAuthed { username, email, is_admin, is_operator, groups, folders, .. } = authed; + let ApiAuthed { username, email, is_admin, is_operator, groups, folders, mcp_client, .. } = + authed; // A guest would otherwise fall through to the non-member branch below and be // handed a `superadmin` role. Answer it here, as the operator-shaped identity it is. if is_guest { @@ -804,10 +805,23 @@ async fn whoami( // The frontend gates pages on `operator`, so it reports what `caller_capabilities` // decides rather than the raw column: an admin (or superadmin) whose row still carries // `operator` holds everything. - Ok(Json(UserInfo { - operator: is_operator && !is_admin, - ..user - })) + let user = UserInfo { operator: is_operator && !is_admin, ..user }; + // An external MCP token brings its own groups, which the request and the jobs it starts + // act with, so report those rather than the stored memberships. + if mcp_client.is_some() { + return Ok(Json(UserInfo { + groups, + folders_read: folders.iter().map(|x| x.0.clone()).collect(), + folders_owners: folders + .iter() + .filter(|x| x.2) + .map(|x| x.0.clone()) + .collect(), + folders: folders.into_iter().filter(|x| x.1).map(|x| x.0).collect(), + ..user + })); + } + Ok(Json(user)) } else { Ok(Json(UserInfo { workspace_id: w_id, diff --git a/backend/windmill-api-workspaces/src/datatable_clone.rs b/backend/windmill-api-workspaces/src/datatable_clone.rs index 067a248aa7..398766b19e 100644 --- a/backend/windmill-api-workspaces/src/datatable_clone.rs +++ b/backend/windmill-api-workspaces/src/datatable_clone.rs @@ -111,7 +111,7 @@ pub(crate) async fn connection_snapshot( .fetch_optional(&mut *conn) .await?; if let Some((stored, true)) = &row { - if windmill_common::secret_backend::is_external_stored_value(stored) { + if windmill_common::secret_backend::resolves_externally(stored) { let secret = windmill_common::secret_backend::get_secret_value( db, w_id, var, stored, ) diff --git a/backend/windmill-api-workspaces/src/workspace_roles.rs b/backend/windmill-api-workspaces/src/workspace_roles.rs index 58bf4e1904..b78c9c0deb 100644 --- a/backend/windmill-api-workspaces/src/workspace_roles.rs +++ b/backend/windmill-api-workspaces/src/workspace_roles.rs @@ -67,7 +67,7 @@ async fn list_roles( })) } -async fn update_role_overrides( +pub(crate) async fn update_role_overrides( authed: ApiAuthed, Path(w_id): Path, Extension(db): Extension, diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 1691e19982..4cb0c18895 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -77,7 +77,8 @@ use serde::{Deserialize, Serialize}; use sqlx::{FromRow, Postgres, Row, Transaction}; use windmill_common::oauth2::InstanceEvent; use windmill_common::secret_backend::{ - get_secret_backend, is_external_stored_value, is_vault_backend_configured, + get_secret_backend, is_external_ref_value, is_external_stored_value, + is_vault_backend_configured, }; use windmill_common::utils::not_found_if_none; @@ -6772,7 +6773,9 @@ async fn set_encryption_key( .await?; for variable in all_variables { - if !variable.is_secret { + if !variable.is_secret + || windmill_common::secret_backend::resolves_externally(&variable.value) + { continue; } let decrypted_value = @@ -14297,6 +14300,7 @@ async fn load_workspace_authed( read_only: base_authed.read_only, job_id: base_authed.job_id, credential_expiry: base_authed.credential_expiry, + mcp_client: base_authed.mcp_client.clone(), }); }; @@ -14337,6 +14341,7 @@ async fn load_workspace_authed( read_only: base_authed.read_only, job_id: base_authed.job_id, credential_expiry: base_authed.credential_expiry, + mcp_client: base_authed.mcp_client.clone(), }) } @@ -14933,8 +14938,12 @@ async fn compare_two_variables( { // A secret's ciphertext is randomized on every write, so equal secrets are compared // by plaintext, each decrypted with its own workspace's key. An external backend - // reference is the same text on both sides but names a per-workspace entry. + // reference is the same text on both sides but names a per-workspace entry. An + // `$external:` reference is compared as written: two references resolving to equal + // values still point at different secrets. has_changes = !source.is_secret + || is_external_ref_value(&source.value) + || is_external_ref_value(&target.value) || !matches!( tokio::try_join!( decrypt_secret_value(db, source_workspace_id, path, source.value.clone()), @@ -15762,6 +15771,8 @@ pub enum SettingsEdit { DefaultApp, Color, OperatorSettings, + /// Body: the workspace's role overrides as a whole, `{ "": { label?, capabilities } }`. + RoleOverrides, Datatable, SlackCommand, SetSlackOAuth, @@ -15826,6 +15837,10 @@ pub async fn apply_settings_edit( ) .await? } + RoleOverrides => { + crate::workspace_roles::update_role_overrides(a, p, d, settings_edit_body(edit, body)?) + .await? + } Datatable => { let Json(result) = edit_datatable_config(a, d, p, settings_edit_body(edit, body)?).await?; diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index e10e1625ca..1a33bf06b1 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.854.2 + version: 1.856.0 title: Windmill API contact: @@ -7828,6 +7828,24 @@ paths: schema: type: string + /w/{workspace}/variables/external_secret_prefixes: + get: + summary: list the external secret prefixes allowed for this workspace (admin only) + operationId: listExternalSecretPrefixes + tags: + - variable + parameters: + - $ref: "#/components/parameters/WorkspaceId" + responses: + "200": + description: allowed prefixes, such as vault://secret/team + content: + application/json: + schema: + type: array + items: + type: string + /w/{workspace}/variables/delete/{path}: delete: summary: delete variable @@ -13732,6 +13750,11 @@ paths: - test - deployed - all + - name: mine + description: only list the caller's own conversations (an admin otherwise lists every user's) + in: query + schema: + type: boolean responses: "200": description: flow conversations list @@ -30114,14 +30137,13 @@ components: type: object required: - address - - mount_path properties: address: type: string description: HashiCorp Vault server address (e.g., https://vault.company.com:8200) mount_path: type: string - description: KV v2 secrets engine mount path (e.g., windmill) + description: KV v2 secrets engine mount path (e.g., windmill). Empty to test the connection used for `$external:vault://` references, which checks only that Vault accepts Windmill's token. kv_secret_path_prefix: type: string description: Optional path prefix inserted between the KV data/metadata segment and the workspace id (e.g., "apps/windmill"). When set, secrets are stored at `/data///`, allowing a Vault policy scoped to exactly `/data//*`. @@ -30131,6 +30153,12 @@ components: jwt_mount_path: type: string description: Mount path for the JWT auth method in Vault (optional, defaults to "jwt"). Set this when the JWT auth method is mounted at a non-default path, e.g. via `vault auth enable -path= jwt`. + approle_role_id: + type: string + description: AppRole role_id (optional). When set and no static token is given, Windmill logs in with AppRole; the secret_id is read from the `VAULT_APPROLE_SECRET_ID` environment variable of servers and workers. + approle_mount_path: + type: string + description: Mount path of the AppRole auth method (optional, defaults to "approle"). namespace: type: string description: Vault Enterprise namespace (optional) @@ -32457,6 +32485,9 @@ components: format: date-time operator: type: boolean + role: + type: string + description: The member's workspace role by name (`developer`, `operator` or a custom role). Admin is the separate `is_admin` flag. disabled: type: boolean groups: @@ -33006,7 +33037,13 @@ components: description: The path to the variable value: type: string - description: The value of the variable + description: > + The value of the variable. For a secret, `$external:vault://#` + stores a reference to an existing secret in the instance's external + HashiCorp Vault (path as `vault kv get` takes it) instead of a value; without + `#` it reads the whole secret as a JSON object of its fields. It is + resolved on each read, only under the path prefixes a superadmin allowed for + the workspace, and is returned as-is when the secret is not decrypted. is_secret: type: boolean description: Whether the variable is a secret @@ -33055,7 +33092,7 @@ components: description: The path to the variable value: type: string - description: The new value of the variable + description: The new value of the variable. Accepts an `$external:vault://[#]` reference for a secret, as in CreateVariable. is_secret: type: boolean description: Whether the variable is a secret diff --git a/backend/windmill-api/src/agent_runs.rs b/backend/windmill-api/src/agent_runs.rs index 74f910a5b2..2258a2acd7 100644 --- a/backend/windmill-api/src/agent_runs.rs +++ b/backend/windmill-api/src/agent_runs.rs @@ -81,7 +81,7 @@ pub(crate) async fn run_agent_as( ( &obo.email, obo.permissioned_as.clone(), - None, + authed.mcp_client.is_some().then(|| authed.clone().into()), PushIsolationLevel::IsolatedRoot(db.clone()), ) } else { diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index 4f1d75c2f7..9e9fdcfaa3 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -7902,7 +7902,7 @@ pub async fn run_workflow_as_code( ( on_behalf_of.email.as_str(), on_behalf_of.permissioned_as.clone(), - None, + authed.mcp_client.is_some().then(|| authed.clone().into()), PushIsolationLevel::IsolatedRoot(db.clone()), ) } else { @@ -8218,7 +8218,7 @@ pub async fn run_wait_result_job_by_path_get( ( on_behalf_of.email.as_str(), on_behalf_of.permissioned_as.clone(), - None, + authed.mcp_client.is_some().then(|| authed.clone().into()), PushIsolationLevel::IsolatedRoot(db.clone()), ) } else { @@ -8369,7 +8369,7 @@ pub async fn run_wait_result_script_by_path_internal( ( on_behalf_of.email.as_str(), on_behalf_of.permissioned_as.clone(), - None, + authed.mcp_client.is_some().then(|| authed.clone().into()), PushIsolationLevel::IsolatedRoot(db.clone()), ) } else { @@ -8488,7 +8488,7 @@ pub async fn run_wait_result_script_by_hash( ( &obo.email, obo.permissioned_as.clone(), - None, + authed.mcp_client.is_some().then(|| authed.clone().into()), PushIsolationLevel::IsolatedRoot(db.clone()), ) } else { @@ -9126,7 +9126,7 @@ fn preview_push_identity( Some(obo) => ( obo.email.clone(), obo.permissioned_as.clone(), - None, + authed.mcp_client.is_some().then(|| authed.clone().into()), PushIsolationLevel::IsolatedRoot(db.clone()), ), None => ( @@ -10824,7 +10824,7 @@ pub async fn run_job_by_hash_inner( ( &obo.email, obo.permissioned_as.clone(), - None, + authed.mcp_client.is_some().then(|| authed.clone().into()), PushIsolationLevel::IsolatedRoot(db.clone()), ) } else { @@ -12856,6 +12856,7 @@ mod approval_view_gate_tests { read_only: false, job_id: None, credential_expiry: None, + mcp_client: None, } } diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 9d3d4d6706..5e88107d1b 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -395,6 +395,7 @@ async fn inject_agent_authed( read_only: false, job_id: None, credential_expiry: None, + mcp_client: None, }, job_id: None, }); @@ -585,15 +586,19 @@ pub async fn run_server( ) .await?; // Workspace-scoped MCP router + let external_idp_auth = + || axum::middleware::from_fn(mcp::external_idp::external_idp_auth); let workspaced_mcp_router = mcp_router .clone() .route_layer(from_extractor::()) + .layer(external_idp_auth()) .layer(axum::middleware::from_fn(reject_token_query_param)) .layer(axum::middleware::from_fn(add_www_authenticate_header)) .layer(axum::middleware::from_fn(extract_and_store_workspace_id)); // Gateway MCP router — resolves workspace from token let gateway_mcp_router = mcp_router .route_layer(from_extractor::()) + .layer(external_idp_auth()) .layer(axum::middleware::from_fn(extract_workspace_from_token)) .layer(axum::middleware::from_fn(reject_token_query_param)) .layer(axum::middleware::from_fn( @@ -602,6 +607,7 @@ pub async fn run_server( // The workspace server. Its tools name their workspace; the token bounds which. let gateway_session_router = session_router .route_layer(from_extractor::()) + .layer(external_idp_auth()) .layer(axum::middleware::from_fn(extract_workspace_from_token)) .layer(axum::middleware::from_fn(reject_token_query_param)) .layer(axum::middleware::from_fn( diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index 8124b6d2bb..32bfe1d26a 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -108,6 +108,16 @@ impl WindmillBackend { impl McpBackend for WindmillBackend { type Auth = ApiAuthed; + async fn after_tool_call( + &self, + auth: &ApiAuthed, + workspace_id: &str, + tool: &str, + refusal: Option<&str>, + ) { + super::external_idp::audit_tool_call(&self.db, auth, workspace_id, tool, refusal).await; + } + async fn list_scripts( &self, auth: &ApiAuthed, @@ -540,9 +550,14 @@ pub async fn extract_and_store_workspace_id( /// a client requests: without it, Claude requests every scope the metadata lists, read-only /// included, and the consent page would then default to read-only access. fn www_authenticate_value(base_url: &str, endpoint: &str) -> String { + let scope = if super::external_idp::configured().is_some() { + super::external_idp::REQUESTED_SCOPES + } else { + "mcp:all" + }; format!( "Bearer resource_metadata=\"{base_url}/.well-known/oauth-protected-resource{endpoint}\", \ - scope=\"mcp:all\"" + scope=\"{scope}\"" ) } diff --git a/backend/windmill-api/src/mcp/external_idp.rs b/backend/windmill-api/src/mcp/external_idp.rs new file mode 100644 index 0000000000..4381e452a2 --- /dev/null +++ b/backend/windmill-api/src/mcp/external_idp.rs @@ -0,0 +1,540 @@ +//! MCP access with an access token issued by an external OIDC provider (`mcp_external_idp`). +//! +//! The token names an OAuth client of that provider and the user who signed in through it. +//! The client is mapped to a workspace and a selection of tools; the request then runs as the +//! user's own Windmill account limited to that selection, so a tool is offered only when the +//! client has it and the user can see it. Windmill-issued tokens never reach this path: it is +//! taken only for a JWT whose `iss` is the configured issuer. + +use std::{ + collections::HashMap, + sync::Arc, + time::{Duration, Instant}, +}; + +use axum::{ + extract::Request, + middleware::Next, + response::{IntoResponse, Response}, + Extension, +}; +use base64::Engine; +use http::StatusCode; +use jsonwebtoken::{jwk::JwkSet, DecodingKey, Validation}; +use serde_json::Value; +use windmill_api_auth::{ApiAuthed, OptJobAuthed}; +use windmill_audit::{audit_oss::audit_log, ActionKind}; +use windmill_common::{ + audit::AuditAuthor, + db::{GatewayWorkspaceId, DB}, + global_settings::{client_access, McpExternalIdp}, + utils::HTTP_CLIENT, +}; +use windmill_mcp::server::NoEndpointTools; +use windmill_mcp::WorkspaceId; + +use super::core::McpSelection; + +/// What an MCP client is told to request from the external issuer: standard OIDC scopes, +/// which every provider knows, and which carry the user's email. +pub const REQUESTED_SCOPES: &str = "openid profile email"; + +/// The issuer configuration when external tokens are on: EE only. +pub fn configured() -> Option> { + #[cfg(feature = "enterprise")] + { + windmill_common::global_settings::MCP_EXTERNAL_IDP.load_full() + } + #[cfg(not(feature = "enterprise"))] + { + None + } +} + +struct Jwks { + issuer: String, + keys: JwkSet, + fetched_at: Instant, +} + +/// A token resolved to its Windmill identity, kept until it expires or for a minute at most, +/// so a user's group changes and a removed client still take effect without a new sign-in. +#[derive(Clone)] +struct Resolved { + authed: ApiAuthed, + workspace_id: String, + until: Instant, +} + +const RESOLVED_TTL: Duration = Duration::from_secs(60); +/// Keys are fetched again for an unknown `kid` (a rotation), but not more often than this. +const JWKS_REFRESH_MIN_INTERVAL: Duration = Duration::from_secs(30); +/// A key the issuer withdrew stops verifying tokens at most this long after. +const JWKS_MAX_AGE: Duration = Duration::from_secs(600); + +lazy_static::lazy_static! { + static ref JWKS: tokio::sync::RwLock> = tokio::sync::RwLock::new(None); + static ref RESOLVED: quick_cache::sync::Cache = + quick_cache::sync::Cache::new(1000); +} + +/// The `iss` of a JWT, read without verifying it: only used to pick the verification path. +fn unverified_issuer(token: &str) -> Option { + let payload = token.split('.').nth(1)?; + let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(payload.trim_end_matches('=')) + .ok()?; + serde_json::from_slice::(&bytes) + .ok()? + .get("iss")? + .as_str() + .map(str::to_string) +} + +async fn fetch_jwks(issuer: &str) -> anyhow::Result { + let discovery: Value = HTTP_CLIENT + .get(format!( + "{}/.well-known/openid-configuration", + issuer.trim_end_matches('/') + )) + .send() + .await? + .error_for_status()? + .json() + .await?; + let jwks_uri = discovery + .get("jwks_uri") + .and_then(Value::as_str) + .ok_or_else(|| anyhow::anyhow!("discovery document of {issuer} has no jwks_uri"))?; + Ok(HTTP_CLIENT + .get(jwks_uri) + .send() + .await? + .error_for_status()? + .json() + .await?) +} + +async fn decoding_key( + issuer: &str, + kid: &str, + header_alg: jsonwebtoken::Algorithm, +) -> anyhow::Result<(DecodingKey, jsonwebtoken::Algorithm)> { + let find = |jwks: &Option| { + jwks.as_ref() + .filter(|j| j.issuer == issuer && j.fetched_at.elapsed() < JWKS_MAX_AGE) + .and_then(|j| j.keys.find(kid).cloned()) + }; + let mut jwk = find(&*JWKS.read().await); + if jwk.is_none() { + let mut guard = JWKS.write().await; + jwk = find(&*guard); + let stale = guard.as_ref().is_none_or(|j| { + j.issuer != issuer || j.fetched_at.elapsed() > JWKS_REFRESH_MIN_INTERVAL + }); + if jwk.is_none() && stale { + *guard = Some(Jwks { + issuer: issuer.to_string(), + keys: fetch_jwks(issuer).await?, + fetched_at: Instant::now(), + }); + jwk = find(&*guard); + } + } + let jwk = jwk.ok_or_else(|| anyhow::anyhow!("no key {kid} at {issuer}"))?; + // Some issuers (Entra) publish keys without `alg`: the token's own header then names it, + // but never an HMAC one, whose "key" would be the public JWK itself. + use jsonwebtoken::Algorithm::{HS256, HS384, HS512}; + let alg = windmill_common::jwt::jwk_algorithm(&jwk) + .or(Some(header_alg).filter(|a| !matches!(a, HS256 | HS384 | HS512))) + .ok_or_else(|| anyhow::anyhow!("key {kid} names no signing algorithm"))?; + Ok((DecodingKey::from_jwk(&jwk)?, alg)) +} + +async fn verify(idp: &McpExternalIdp, token: &str) -> anyhow::Result<(Value, u64)> { + let header = jsonwebtoken::decode_header(token)?; + let kid = header + .kid + .clone() + .ok_or_else(|| anyhow::anyhow!("token has no kid"))?; + let (key, alg) = decoding_key(&idp.issuer, &kid, header.alg).await?; + let mut validation = Validation::new(alg); + validation.set_issuer(&[&idp.issuer]); + validation.validate_nbf = true; + match &idp.audience { + Some(aud) => validation.set_audience(&[aud]), + None => validation.validate_aud = false, + } + let claims = jsonwebtoken::decode::(token, &key, &validation)?.claims; + // Without an audience to check, an ID token of the same client would pass for an access + // token: the token must then name itself one (RFC 9068 `at+jwt`, or Keycloak's `Bearer`). + if claims.get("typ").and_then(Value::as_str) == Some("ID") { + anyhow::bail!("an ID token is not an access token"); + } + if idp.audience.is_none() { + let header_typ = header.typ.as_deref().unwrap_or_default(); + let claim_typ = claims + .get("typ") + .and_then(Value::as_str) + .unwrap_or_default(); + if !header_typ.eq_ignore_ascii_case("at+jwt") && !claim_typ.eq_ignore_ascii_case("Bearer") { + anyhow::bail!("not marked as an access token; configure an audience to accept it"); + } + } + let exp = claims.get("exp").and_then(Value::as_u64).unwrap_or(0); + Ok((claims, exp)) +} + +/// Why a verified token was not served. Answered with 403, not 401: signing in again with +/// the same client and account would not change the answer. +struct Refusal { + client: Option, + email: Option, + workspace_id: Option, + reason: String, +} + +fn claim_str(claims: &Value, name: &str) -> Option { + claims + .get(name) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) +} + +async fn resolve( + db: &DB, + idp: &McpExternalIdp, + claims: &Value, + url_workspace: Option<&str>, +) -> Result<(ApiAuthed, String), Refusal> { + let client_id = claim_str(claims, &idp.client_claim); + let email = claim_str(claims, &idp.email_claim) + .map(|e| windmill_common::oauth2::normalize_external_email(&e)); + let refuse = |workspace_id: Option<&str>, reason: String| Refusal { + client: client_id.clone(), + email: email.clone(), + workspace_id: workspace_id.map(str::to_string), + reason, + }; + + let client = client_id + .as_deref() + .and_then(|id| idp.client(id)) + .ok_or_else(|| { + refuse( + url_workspace, + format!( + "OAuth client {} is not configured for MCP access", + client_id.as_deref().unwrap_or("(none)") + ), + ) + })?; + let w_id = client.workspace_id.as_str(); + if url_workspace.is_some_and(|w| w != w_id) { + return Err(refuse( + url_workspace, + format!( + "OAuth client {} serves workspace {w_id} only", + client.client_id + ), + )); + } + // A client-credentials token carries the client alone. A client acts only for a user, + // within that user's own rights. + let email = email.clone().ok_or_else(|| { + refuse( + Some(w_id), + format!( + "the token carries no `{}` claim: a client can only act for a signed-in user", + idp.email_claim + ), + ) + })?; + // Some issuers send the flag as a string. + let unverified = match claims.get("email_verified") { + Some(Value::Bool(b)) => !b, + Some(Value::String(s)) => s.eq_ignore_ascii_case("false"), + _ => false, + }; + if unverified { + return Err(refuse( + Some(w_id), + format!("{email} is not verified at the issuer"), + )); + } + + // Instance deactivation sets `password.disabled` and revokes Windmill's own tokens; this + // path has none to revoke, so it reads the flag itself. + let deactivated: Option = + sqlx::query_scalar("SELECT disabled FROM password WHERE email = $1") + .bind(&email) + .fetch_optional(db) + .await + .map_err(|e| refuse(Some(w_id), e.to_string()))?; + if deactivated == Some(true) { + return Err(refuse(Some(w_id), format!("{email} is deactivated"))); + } + + let username = sqlx::query_scalar!( + "SELECT username FROM usr WHERE workspace_id = $1 AND email = $2 AND NOT disabled", + w_id, + &email + ) + .fetch_optional(db) + .await + .map_err(|e| refuse(Some(w_id), e.to_string()))? + .ok_or_else(|| { + refuse( + Some(w_id), + format!( + "{email} is not a member of workspace {w_id}. Users must sign in to Windmill once \ + before using an MCP client" + ), + ) + })?; + + let mut authed: ApiAuthed = windmill_common::auth::fetch_authed_from_permissioned_as( + &format!("u/{username}"), + &email, + w_id, + db, + ) + .await + .map_err(|e| refuse(Some(w_id), e.to_string()))? + .into(); + // The groups the IdP manages come from the token alone, for this request only: one the + // token no longer lists, or an absent claim, stops granting at once, and nothing is stored. + if let Some(idp_groups) = token_groups(db, claims) + .await + .map_err(|e| refuse(Some(w_id), e))? + { + let err = |e: sqlx::Error| refuse(Some(w_id), e.to_string()); + // Workspace groups and unmanaged instance groups as stored, by source rather than by + // name: a workspace group may share its name with a managed instance group. + let mut groups: Vec = sqlx::query_scalar( + "SELECT group_ FROM usr_to_group WHERE usr = $1 AND workspace_id = $2 \ + UNION ALL SELECT igroup FROM email_to_igroup JOIN instance_group ON name = igroup \ + WHERE email = $3 AND external_id IS NULL", + ) + .bind(&authed.username) + .bind(w_id) + .bind(&email) + .fetch_all(db) + .await + .map_err(err)?; + groups.extend(idp_groups); + authed.folders = + windmill_common::auth::get_folders_for_user(w_id, &authed.username, &groups, db) + .await + .map_err(|e| refuse(Some(w_id), e.to_string()))?; + authed.groups = groups; + } + let mut scopes = client.scopes.clone(); + // Every MCP URL then serves the session's toolset, as for a Windmill token approved with + // an access level, rather than the tools server with its endpoint tools. + if client_access(&scopes) == Ok(true) && !scopes.iter().any(|s| s == "mcp:session") { + scopes.push("mcp:session".to_string()); + } + authed.scopes = Some(scopes); + authed.mcp_client = Some(client.client_id.clone()); + Ok((authed, w_id.to_string())) +} + +/// The instance groups the token's groups claim maps to through their `external_id`, or +/// `None` when `sso_groups_claim` is unset and the stored memberships apply alone. +#[cfg(all(feature = "enterprise", feature = "private", feature = "oauth2"))] +async fn token_groups(db: &DB, claims: &Value) -> Result>, String> { + let Some(claim) = crate::oauth2_ee::sso_groups_claim(db) + .await + .map_err(|e| e.to_string())? + else { + return Ok(None); + }; + let values: Vec = match claims.get(&claim) { + Some(Value::Array(v)) => v + .iter() + .filter_map(|x| x.as_str().map(str::to_string)) + .collect(), + Some(Value::String(s)) => vec![s.clone()], + // Entra leaves out a list too long for the token and points to it here: reading that + // as "no groups" would silently strip the user's rights. + None if claims + .get("_claim_names") + .and_then(|c| c.get(&claim)) + .is_some() => + { + return Err(format!( + "the token's `{claim}` claim was left out for listing too many groups: \ + limit it to the groups assigned to the client" + )); + } + _ => vec![], + }; + let values = crate::scim_ee::with_ancestor_paths(crate::scim_ee::usable_claim_values(&values)); + sqlx::query_scalar("SELECT name FROM instance_group WHERE external_id = ANY($1)") + .bind(&values) + .fetch_all(db) + .await + .map(Some) + .map_err(|e| e.to_string()) +} + +#[cfg(not(all(feature = "enterprise", feature = "private", feature = "oauth2")))] +async fn token_groups(_db: &DB, _claims: &Value) -> Result>, String> { + Ok(None) +} + +async fn audit_refusal(db: &DB, refusal: &Refusal) { + let email = refusal.email.clone().unwrap_or_default(); + let author = + AuditAuthor { username: email.clone(), email, username_override: None, token_prefix: None }; + let client = refusal.client.clone().unwrap_or_default(); + let params = HashMap::from([ + ("mcp_client", client.as_str()), + ("outcome", "refused"), + ("reason", refusal.reason.as_str()), + ]); + if let Err(e) = audit_log( + db, + &author, + "mcp.external_token", + ActionKind::Execute, + refusal.workspace_id.as_deref().unwrap_or("global"), + Some(&client), + Some(params), + ) + .await + { + tracing::error!("Could not audit a refused MCP token: {e:#}"); + } +} + +/// Records a tool call made through an external client, allowed or refused, with both +/// identities: the user as author, the client in the parameters. +pub async fn audit_tool_call( + db: &DB, + authed: &ApiAuthed, + w_id: &str, + tool: &str, + refusal: Option<&str>, +) { + let Some(client) = authed.mcp_client.as_deref() else { + return; + }; + let outcome = if refusal.is_some() { "refused" } else { "ok" }; + windmill_common::feature_usage::log_feature_usage("mcp_external_client", "tool_call", outcome); + let mut params = HashMap::from([("mcp_client", client), ("outcome", outcome)]); + if let Some(reason) = refusal { + params.insert("reason", reason); + } + if let Err(e) = audit_log( + db, + authed, + "mcp.tool_call", + ActionKind::Execute, + w_id, + Some(tool), + Some(params), + ) + .await + { + tracing::error!("Could not audit an MCP tool call: {e:#}"); + } +} + +fn bearer(request: &Request) -> Option<&str> { + request + .headers() + .get(http::header::AUTHORIZATION)? + .to_str() + .ok()? + .strip_prefix("Bearer ") +} + +/// Authenticates a request carrying a token of the configured issuer, ahead of the usual +/// token lookup, and binds it to its client's workspace as a workspace-bound selection token +/// is. Every other request passes through untouched. +pub async fn external_idp_auth( + Extension(db): Extension, + mut request: Request, + next: Next, +) -> Response { + let Some(idp) = configured() else { + return next.run(request).await; + }; + let Some(token) = bearer(&request).map(str::to_string) else { + return next.run(request).await; + }; + if unverified_issuer(&token).as_deref() != Some(idp.issuer.as_str()) { + return next.run(request).await; + } + let url_workspace = request + .extensions() + .get::() + .map(|w| w.0.clone()); + + let cache_key = windmill_common::auth::hash_token(&token); + let resolved = match RESOLVED + .get(&cache_key) + .filter(|r| r.until > Instant::now()) + { + Some(r) => r, + None => { + let (claims, exp) = match verify(&idp, &token).await { + Ok(v) => v, + Err(e) => { + tracing::debug!("External MCP token refused: {e:#}"); + return (StatusCode::UNAUTHORIZED, "Invalid or expired access token") + .into_response(); + } + }; + match resolve(&db, &idp, &claims, url_workspace.as_deref()).await { + Ok((authed, workspace_id)) => { + let exp = std::time::UNIX_EPOCH + Duration::from_secs(exp); + let left = exp + .duration_since(std::time::SystemTime::now()) + .unwrap_or_default(); + let r = Resolved { + authed, + workspace_id, + until: Instant::now() + left.min(RESOLVED_TTL), + }; + RESOLVED.insert(cache_key, r.clone()); + r + } + Err(refusal) => { + audit_refusal(&db, &refusal).await; + return (StatusCode::FORBIDDEN, refusal.reason).into_response(); + } + } + } + }; + if url_workspace + .as_deref() + .is_some_and(|w| w != resolved.workspace_id) + { + return ( + StatusCode::FORBIDDEN, + format!( + "This OAuth client serves workspace {} only", + resolved.workspace_id + ), + ) + .into_response(); + } + + let extensions = request.extensions_mut(); + let selection = + client_access(resolved.authed.scopes.as_deref().unwrap_or_default()) != Ok(true); + extensions.insert(OptJobAuthed { job_id: None, authed: resolved.authed.clone() }); + extensions.insert(resolved.authed); + extensions.insert(GatewayWorkspaceId(resolved.workspace_id.clone())); + extensions.insert(WorkspaceId(resolved.workspace_id)); + if selection { + extensions.insert(McpSelection); + extensions.insert(NoEndpointTools); + } + next.run(request).await +} diff --git a/backend/windmill-api/src/mcp/mod.rs b/backend/windmill-api/src/mcp/mod.rs index 20c5532b29..05449d1b93 100644 --- a/backend/windmill-api/src/mcp/mod.rs +++ b/backend/windmill-api/src/mcp/mod.rs @@ -5,6 +5,7 @@ mod auto_generated_endpoints; mod core; +pub mod external_idp; mod session; mod utils; diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index 9598ca907b..b7a7a06a47 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -276,10 +276,22 @@ fn build_protected_resource_metadata( oauth_prefix: &str, base_url: &str, ) -> ProtectedResourceMetadata { + // With an external issuer configured, clients sign in there: Windmill's own server keeps + // honouring the tokens it issued, but no longer hands out new ones to MCP clients. + let (authorization_server, scopes) = match super::external_idp::configured() { + Some(idp) => ( + idp.issuer.clone(), + super::external_idp::REQUESTED_SCOPES + .split(' ') + .map(str::to_string) + .collect(), + ), + None => (format!("{}{}", base_url, oauth_prefix), granting_scopes()), + }; ProtectedResourceMetadata { resource: format!("{}{}", base_url, resource_path), - authorization_servers: vec![format!("{}{}", base_url, oauth_prefix)], - scopes_supported: Some(granting_scopes()), + authorization_servers: vec![authorization_server], + scopes_supported: Some(scopes), bearer_methods_supported: Some(vec!["header".to_string()]), } } diff --git a/backend/windmill-api/src/mcp/utils.rs b/backend/windmill-api/src/mcp/utils.rs index 6e125eefc6..9decf6993b 100644 --- a/backend/windmill-api/src/mcp/utils.rs +++ b/backend/windmill-api/src/mcp/utils.rs @@ -1489,6 +1489,7 @@ mod tests { read_only: false, job_id, credential_expiry: None, + mcp_client: None, } } diff --git a/backend/windmill-api/src/workspace_settings_document.rs b/backend/windmill-api/src/workspace_settings_document.rs index 5f0f062d10..a30314e3ee 100644 --- a/backend/windmill-api/src/workspace_settings_document.rs +++ b/backend/windmill-api/src/workspace_settings_document.rs @@ -25,6 +25,7 @@ use windmill_common::{ read_role_catalog, DatatableRoleCluster, ADMIN_DATATABLE_ROLE, NO_DEFAULT_DATATABLE_ROLE, }, error::{Error, JsonResult, Result}, + roles::{load_role_overrides, RoleOverrides}, utils::require_admin, variables::build_crypt, workspaces::{ @@ -260,6 +261,12 @@ fn datatable_permissions_document(datatable: Option<&Value>, roles: &DatatableNa /// Protection rules by name, their rules in a fixed order so a reordered file is no change. The /// dev workspace lock is left out: the dev workspace setting creates and removes it. +/// The workspace's role overrides keyed by role name, sorted so a pulled file is stable. +fn role_overrides_document(overrides: &RoleOverrides) -> Value { + let sorted: BTreeMap<&String, _> = overrides.iter().collect(); + serde_json::to_value(sorted).unwrap_or_else(|_| json!({})) +} + async fn protection_rules_document(conn: &mut PgConnection, w_id: &str) -> Result { let rows = sqlx::query_as::<_, (String, i32, Vec, Vec, Value)>( "SELECT name, rules, bypass_groups, bypass_users, fork_role_mapping FROM workspace_protection_rule @@ -352,6 +359,7 @@ pub async fn load_settings_document( }; let datatable_permissions = datatable_permissions_document(row.datatable.as_ref(), &role_names); let protection_rules = protection_rules_document(&mut *conn, w_id).await?; + let role_overrides = role_overrides_document(&load_role_overrides(&mut *conn, w_id).await?); let git_sync = redact_git_sync(row.git_sync); let git_sync = match fork_parent(&mut *conn, w_id).await? { Some(parent) => fork_git_sync_document(git_sync, parent.git_sync), @@ -361,7 +369,7 @@ pub async fn load_settings_document( // In the order `wmill sync pull` has always written settings.yaml. A key that predates the // document and is not marked `always` is written only when set, as it always was; a key // added since is always written, so a pulled file states it and from then on manages it. - let entries: [(&str, Option, bool); 31] = [ + let entries: [(&str, Option, bool); 32] = [ ("auto_invite", row.auto_invite, false), ("webhook", row.webhook.map(Value::String), false), ("error_handler", row.error_handler, true), @@ -384,6 +392,7 @@ pub async fn load_settings_document( ), ("color", row.color.map(Value::String), false), ("operator_settings", row.operator_settings, false), + ("role_overrides", Some(role_overrides), true), ( "datatable", windmill_common::workspaces::strip_datatable_permissions(row.datatable), @@ -704,6 +713,7 @@ const KNOWN_KEYS: &[&str] = &[ "mute_critical_alerts", "color", "operator_settings", + "role_overrides", "datatable", "slack_team_id", "slack_name", @@ -1432,6 +1442,23 @@ fn plan_document( } } + // Stated as a whole, after `operator_settings`: a role the map omits loses its override, and + // the `operator` override it states wins over the legacy key. + if let Some(desired) = p.managed("role_overrides") { + let desired = if desired.is_null() { + json!({}) + } else { + desired + }; + let overrides: RoleOverrides = serde_json::from_value(desired) + .map_err(|e| Error::BadRequest(format!("Invalid role_overrides: {e}")))?; + let desired = role_overrides_document(&overrides); + if p.differs("role_overrides", &desired) { + p.record("role_overrides", desired.clone()); + p.write(Target::Edit(SettingsEdit::RoleOverrides), desired); + } + } + let datatable = p.legacy("datatable"); p.simple( "datatable", @@ -2180,6 +2207,51 @@ mod tests { assert!(plan_document(cur, d, true, &mc, &roles).is_err()); } + #[test] + fn role_overrides_are_applied_as_a_whole_after_operator_settings() { + let mc = WorkspaceCrypt::new("k"); + let mut cur = current(); + cur.insert( + "role_overrides".into(), + json!({ "operator": { "capabilities": { "manage_schedules": false } } }), + ); + cur.insert("operator_settings".into(), json!({ "runs": true })); + + // Unchanged: no write. + let d = doc(json!({ "role_overrides": { + "operator": { "capabilities": { "manage_schedules": false } }, + } })); + let p = plan_document(cur.clone(), d, false, &mc, &DatatableNames::default()).unwrap(); + assert!(keys(&p).is_empty()); + + // A custom role added next to the legacy key: role_overrides is written last. + let d = doc(json!({ + "operator_settings": { "runs": false }, + "role_overrides": { + "operator": { "capabilities": { "manage_schedules": false } }, + "reviewer": { "label": "Reviewer", "capabilities": { "code": false } }, + }, + })); + let p = plan_document(cur.clone(), d, false, &mc, &DatatableNames::default()).unwrap(); + assert_eq!(keys(&p), ["operator_settings", "role_overrides"]); + assert!(matches!( + p.writes.last().unwrap().target, + Target::Edit(SettingsEdit::RoleOverrides) + )); + + // An empty map is stated, so it clears the workspace's overrides. + let p = plan_document( + cur, + doc(json!({ "role_overrides": {} })), + false, + &mc, + &DatatableNames::default(), + ) + .unwrap(); + assert_eq!(keys(&p), ["role_overrides"]); + assert_eq!(p.writes[0].body, json!({})); + } + #[test] fn protection_rules_are_diffed_by_name() { let mc = WorkspaceCrypt::new("k"); diff --git a/backend/windmill-api/src/workspace_shared_ui.rs b/backend/windmill-api/src/workspace_shared_ui.rs index 810ea3420f..6df4ff6ddb 100644 --- a/backend/windmill-api/src/workspace_shared_ui.rs +++ b/backend/windmill-api/src/workspace_shared_ui.rs @@ -7,6 +7,7 @@ */ use crate::db::{ApiAuthed, DB}; +use crate::utils::check_scopes; use axum::{ extract::{Extension, Json, Path}, routing::{get, put}, @@ -152,6 +153,9 @@ async fn update_shared_ui( Json(payload): Json, ) -> Result { require_admin(authed.is_admin, &authed.username)?; + // The route layer matches `apps:write:` too; the store is workspace-wide, so + // only a grant spanning every app path may replace it. + check_scopes(&authed, || "apps:write".to_string())?; let files_json = serde_json::to_value(&payload.files) .map_err(|e| Error::internal_err(format!("serializing files: {e}")))?; diff --git a/backend/windmill-api/src/workspaces_export.rs b/backend/windmill-api/src/workspaces_export.rs index 46b7a7a8dd..ceaea724da 100644 --- a/backend/windmill-api/src/workspaces_export.rs +++ b/backend/windmill-api/src/workspaces_export.rs @@ -986,6 +986,10 @@ pub(crate) async fn tarball_workspace( if plain_secret.or(plain_secrets).unwrap_or(false) && var.value.is_some() && var.is_secret + && !var + .value + .as_deref() + .is_some_and(windmill_common::secret_backend::is_external_ref_value) { var.value = Some(decrypt(&mc, var.value.unwrap()).map_err(|e| { Error::internal_err(format!("Error decrypting variable {}: {}", var.path, e)) @@ -1462,26 +1466,26 @@ pub(crate) async fn tarball_workspace( } if include_users.unwrap_or(false) { - let users = sqlx::query!( - "SELECT workspace_id, username, email, is_admin, created_at, operator, disabled, role, added_via FROM usr + // `role` is the member's workspace role by name, so a custom role survives the round trip. + // Admin is a flag on top of the role and is written as `admin`, as it always was. + let users = sqlx::query_as::<_, (String, String, bool, bool, bool, Option)>( + "SELECT username, email, is_admin, operator, disabled, workspace_role FROM usr WHERE workspace_id = $1", - &w_id ) + .bind(&w_id) .fetch_all(&mut *tx) .await?; - for user in users { + for (username, email, is_admin, operator, disabled, workspace_role) in users { let user = SimplifiedUser { - username: user.username, - role: if user.is_admin { + username, + role: if is_admin { "admin".to_string() - } else if user.operator { - "operator".to_string() } else { - "developer".to_string() + windmill_common::roles::resolve_role_name(workspace_role, operator) }, - disabled: user.disabled, - email: user.email, + disabled, + email, }; let user_str = &to_string_without_metadata(&user, ExtraPermsBehavior::Drop, Some(vec!["email"])) diff --git a/backend/windmill-common/src/auth.rs b/backend/windmill-common/src/auth.rs index 78d3b98c48..d2641b5e78 100644 --- a/backend/windmill-common/src/auth.rs +++ b/backend/windmill-common/src/auth.rs @@ -324,6 +324,10 @@ pub struct JWTAuthClaims { pub job_id: Option, pub scopes: Option>, pub audit_span: Option, + /// [`Authed::mcp_client`], so a request the caller's tools make on its behalf still + /// records the client on the runs it starts. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mcp_client: Option, } impl JWTAuthClaims { @@ -370,6 +374,9 @@ pub struct JobPerms { /// role, and the object storage advanced permission rules it is checked against. #[serde(default)] pub viewer_data_access: bool, + /// The OAuth client of an external issuer the root run was started through. + #[serde(default)] + pub mcp_client: Option, } impl From for Authed { @@ -387,6 +394,7 @@ impl From for Authed { .collect(), scopes: None, token_prefix: None, + mcp_client: value.mcp_client, } } } @@ -579,6 +587,7 @@ async fn fetch_authed_from_permissioned_as_inner( folders, scopes: None, token_prefix: None, + mcp_client: None, }) } else { let groups = vec![name.to_string()]; @@ -592,6 +601,7 @@ async fn fetch_authed_from_permissioned_as_inner( folders, scopes: None, token_prefix: None, + mcp_client: None, }) } } else { @@ -613,6 +623,7 @@ async fn fetch_authed_from_permissioned_as_inner( folders: vec![], scopes: None, token_prefix: None, + mcp_client: None, }) } } @@ -670,7 +681,7 @@ pub async fn get_job_perms<'a, E: sqlx::PgExecutor<'a>>( sqlx::query_as!( JobPerms, "SELECT email, username, is_admin, is_operator, groups, folders, end_user_email, - job_token_scopes, viewer_data_access + job_token_scopes, viewer_data_access, mcp_client FROM job_perms WHERE job_id = $1 AND workspace_id = $2", job_id, w_id @@ -824,6 +835,7 @@ pub async fn create_jwt_token( job_id: job_id.map(|id| id.to_string()), scopes, audit_span, + mcp_client: authed.mcp_client.clone(), }; let token = jwt::encode_with_internal_secret(&payload) @@ -962,6 +974,7 @@ mod tests { job_id: None, scopes: None, audit_span: None, + mcp_client: None, }; // Signature is irrelevant — the gate decodes without verifying — so any key works. let token = jsonwebtoken::encode( diff --git a/backend/windmill-common/src/db.rs b/backend/windmill-common/src/db.rs index dc22b37157..edda7fca07 100644 --- a/backend/windmill-common/src/db.rs +++ b/backend/windmill-common/src/db.rs @@ -20,6 +20,8 @@ pub struct Authed { pub folders: Vec<(String, bool, bool)>, pub scopes: Option>, pub token_prefix: Option, + /// See `ApiAuthed::mcp_client`. + pub mcp_client: Option, } impl Authed { diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index 371eff43dd..82a807c31b 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -113,6 +113,9 @@ pub const DISABLE_PASSWORD_LOGIN_SETTING: &str = "disable_password_login"; /// in. A URL-borne credential ends up in browser history, proxy logs and referrers, so an /// instance that cares sends MCP clients through the OAuth flow instead. pub const MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING: &str = "mcp_disable_token_query_param"; +/// An external OIDC issuer whose access tokens the MCP endpoints accept, and the OAuth clients +/// of that issuer they serve. Read and validated by [`parse_mcp_external_idp`]. +pub const MCP_EXTERNAL_IDP_SETTING: &str = "mcp_external_idp"; /// Ceiling, in days, on how far ahead a token minted through `POST /users/tokens/create` or /// `POST /users/tokens/impersonate` may expire; a request asking for more, or for no /// expiration at all, is shortened to it rather than refused. On those routes only: server-side @@ -177,6 +180,7 @@ pub const APP_WORKSPACED_ROUTE_SETTING: &str = "app_workspaced_route"; pub const HTTP_ROUTE_WORKSPACED_ROUTE_SETTING: &str = "http_route_workspaced_route"; pub const HTTP_ROUTE_DEFAULT_ALLOWED_ORIGINS_SETTING: &str = "http_route_default_allowed_origins"; pub const SECRET_BACKEND_SETTING: &str = "secret_backend"; +pub const EXTERNAL_SECRETS_SETTING: &str = "external_secrets"; pub const MIN_KEEP_ALIVE_VERSION_SETTING: &str = "min_keep_alive_version"; pub const GITHUB_ENTERPRISE_APP_SETTING: &str = "github_enterprise_app"; /// Base URL GitHub delivers git-sync repository webhooks to. Falls back to @@ -513,6 +517,7 @@ pub const AGENT_WORKER_BLOCKED_SETTINGS: &[&str] = &[ SCIM_TOKEN_SETTING, SAML_METADATA_SETTING, SECRET_BACKEND_SETTING, + EXTERNAL_SECRETS_SETTING, GITHUB_ENTERPRISE_APP_SETTING, OBJECT_STORE_CONFIG_SETTING, AI_CONFIG_SETTING, @@ -546,6 +551,9 @@ lazy_static::lazy_static! { pub static ref HTTP_ROUTE_WORKSPACED_ROUTE: AtomicBool = AtomicBool::new(false); pub static ref DISABLE_PASSWORD_LOGIN: AtomicBool = AtomicBool::new(false); pub static ref MCP_DISABLE_TOKEN_QUERY_PARAM: AtomicBool = AtomicBool::new(false); + /// `None` when [`MCP_EXTERNAL_IDP_SETTING`] is unset or has no issuer. + pub static ref MCP_EXTERNAL_IDP: arc_swap::ArcSwapOption = + arc_swap::ArcSwapOption::empty(); /// Empty means unset. See [`API_BASE_URL_SETTING`]. pub static ref API_BASE_URL: arc_swap::ArcSwap = arc_swap::ArcSwap::from_pointee(String::new()); @@ -557,6 +565,129 @@ lazy_static::lazy_static! { arc_swap::ArcSwap::from_pointee(vec![]); } +/// [`MCP_EXTERNAL_IDP_SETTING`]: the MCP endpoints accept an access token signed by `issuer` +/// when its `client_claim` names one of `clients`, acting as the Windmill user whose email is +/// in `email_claim`, limited to that client's selection in that client's workspace. +#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct McpExternalIdp { + pub issuer: String, + /// Checked against the token's `aud` when set. Many issuers stamp an audience the + /// resource server cannot choose, so it is optional. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub audience: Option, + #[serde(default = "default_mcp_client_claim")] + pub client_claim: String, + #[serde(default = "default_mcp_email_claim")] + pub email_claim: String, + #[serde(default)] + pub clients: Vec, +} + +#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct McpExternalClient { + pub client_id: String, + pub workspace_id: String, + /// Selection scopes, as a token scoped to runnables-as-tools carries them. + pub scopes: Vec, +} + +fn default_mcp_client_claim() -> String { + "azp".to_string() +} + +fn default_mcp_email_claim() -> String { + "email".to_string() +} + +impl McpExternalIdp { + pub fn client(&self, client_id: &str) -> Option<&McpExternalClient> { + self.clients.iter().find(|c| c.client_id == client_id) + } +} + +/// Reads [`MCP_EXTERNAL_IDP_SETTING`]; `None` when unset. A client may only be given +/// individual tools: `mcp:all` would hand it the whole session toolset and endpoint scopes +/// the raw API, neither of which the user's own grant to the client is meant to cover. +pub fn parse_mcp_external_idp( + value: Option<&serde_json::Value>, +) -> Result, String> { + let value = match value { + None | Some(serde_json::Value::Null) => return Ok(None), + Some(v) => v, + }; + let idp: McpExternalIdp = serde_json::from_value(value.clone()).map_err(|e| e.to_string())?; + if idp.issuer.trim().is_empty() { + return if idp.clients.is_empty() { + Ok(None) + } else { + Err("clients need an issuer".to_string()) + }; + } + // Its keys are fetched from it: over plain http anyone on the path could forge tokens. + let url = url::Url::parse(&idp.issuer).map_err(|e| format!("issuer: {e}"))?; + let local = matches!(url.host_str(), Some("localhost" | "127.0.0.1")); + if !(url.scheme() == "https" || url.scheme() == "http" && local) { + return Err("issuer must be an https URL".to_string()); + } + if idp.client_claim.trim().is_empty() || idp.email_claim.trim().is_empty() { + return Err("claim names must not be empty".to_string()); + } + for (i, client) in idp.clients.iter().enumerate() { + if client.client_id.trim().is_empty() || client.workspace_id.trim().is_empty() { + return Err("every client needs a client id and a workspace".to_string()); + } + // Recorded on every run it starts, in a VARCHAR(255) column. + if client.client_id.len() > 255 { + return Err(format!("client id {} is too long", client.client_id)); + } + if idp.clients[..i] + .iter() + .any(|c| c.client_id == client.client_id) + { + return Err(format!("client {} is listed twice", client.client_id)); + } + client_access(&client.scopes).map_err(|e| format!("client {}: {e}", client.client_id))?; + } + Ok(Some(idp)) +} + +/// Whether an external MCP client's scopes give the AI session's toolset (`mcp:all`, alone or +/// narrowed by `mcp:read_only` / `mcp:read_run`) rather than a selection of scripts, flows and +/// hub scripts. Endpoint scopes, path-narrowed `mcp:all` and `mcp:workspaces:` are refused: +/// a client reaches its one workspace, and only through these two shapes. +pub fn client_access(scopes: &[String]) -> Result { + // Markers the token form adds; they grant nothing. + let scopes: Vec<&str> = scopes + .iter() + .map(String::as_str) + .filter(|s| !["mcp:runnables_as_tools", "mcp:session"].contains(s)) + .collect(); + if scopes.contains(&"mcp:all") { + let narrowed: Vec<&str> = scopes.iter().copied().filter(|s| *s != "mcp:all").collect(); + return match narrowed.as_slice() { + [] | ["mcp:read_only"] | ["mcp:read_run"] => Ok(true), + other => Err(format!( + "mcp:all takes at most one of mcp:read_only and mcp:read_run, not {}", + other.join(" ") + )), + }; + } + if scopes.is_empty() { + return Err("selects no tools".to_string()); + } + if let Some(scope) = scopes.iter().find(|s| { + !(**s == "mcp:favorites" + || ["mcp:scripts:", "mcp:flows:", "mcp:hub:"] + .iter() + .any(|p| s.strip_prefix(p).is_some_and(|rest| !rest.is_empty()))) + }) { + return Err(format!( + "{scope} is not an access level nor a selection of scripts, flows or hub scripts" + )); + } + Ok(false) +} + /// [`API_BASE_URL_SETTING`] when it applies to MCP, else `base_url`. The MCP gateway builds every URL it hands a /// client to call from it: its resource identifier, the authorization server it names, and /// that server's issuer, token and registration endpoints. Not the authorization endpoint: @@ -1026,6 +1157,47 @@ mod tests { assert!(validate_api_base_url_applies_to(&json!("mcp")).is_err()); } + #[test] + fn mcp_external_clients_get_an_access_level_or_a_selection() { + let with_scopes = |scopes: &[&str]| { + parse_mcp_external_idp(Some(&serde_json::json!({ + "issuer": "https://idp.example.com/realms/main", + "clients": [{ "client_id": "a", "workspace_id": "w", "scopes": scopes }] + }))) + }; + let idp = with_scopes(&["mcp:flows:f/x/run", "mcp:scripts:f/x/*", "mcp:favorites"]) + .unwrap() + .unwrap(); + assert_eq!( + (idp.client_claim.as_str(), idp.email_claim.as_str()), + ("azp", "email") + ); + for (scopes, session) in [ + (&["mcp:all"][..], true), + (&["mcp:all", "mcp:read_run", "mcp:session"], true), + (&["mcp:favorites", "mcp:runnables_as_tools"], false), + ] { + let scopes: Vec = scopes.iter().map(|s| s.to_string()).collect(); + assert_eq!(client_access(&scopes), Ok(session), "{scopes:?}"); + } + for refused in [ + &["mcp:all", "mcp:read_only", "mcp:read_run"][..], + &["mcp:all", "mcp:scripts:f/x/run"], + &["mcp:all", "mcp:workspaces:a,b"], + &["mcp:all:f/x/*"], + &["mcp:endpoints:listJobs"], + &["mcp:scripts:"], + &[], + ] { + assert!(with_scopes(refused).is_err(), "{refused:?}"); + } + assert_eq!(parse_mcp_external_idp(None), Ok(None)); + assert_eq!( + parse_mcp_external_idp(Some(&serde_json::json!({"issuer": ""}))), + Ok(None) + ); + } + // `frontend/src/lib/tokenExpiration.test.ts` holds the same table for the token form's // parser; the two must stay in step. #[test] @@ -1265,6 +1437,7 @@ mod tests { SCIM_TOKEN_SETTING, SAML_METADATA_SETTING, SECRET_BACKEND_SETTING, + EXTERNAL_SECRETS_SETTING, GITHUB_ENTERPRISE_APP_SETTING, OBJECT_STORE_CONFIG_SETTING, AI_CONFIG_SETTING, diff --git a/backend/windmill-common/src/instance_config.rs b/backend/windmill-common/src/instance_config.rs index 3fe79417ee..338afbfac6 100644 --- a/backend/windmill-common/src/instance_config.rs +++ b/backend/windmill-common/src/instance_config.rs @@ -1241,7 +1241,10 @@ fn mask_nested_sensitive(key: &str, value: &serde_json::Value) -> serde_json::Va } } // Settings that are maps-of-objects where each child has a sensitive sub-field. - const NESTED_MAP_SENSITIVE: &[(&str, &[&str])] = &[("oauths", &["secret", "signing_secret"])]; + const NESTED_MAP_SENSITIVE: &[(&str, &[&str])] = &[ + ("oauths", &["secret", "signing_secret"]), + ("external_secrets", &["token"]), + ]; for &(parent_key, child_fields) in NESTED_MAP_SENSITIVE { if key == parent_key { if let serde_json::Value::Object(entries) = value { @@ -1591,6 +1594,10 @@ pub async fn sync_global_settings_declarative( crate::global_settings::parse_max_token_expiration_days(desired.get(max_expiration_key)) .map_err(|e| anyhow::anyhow!("{max_expiration_key}: {e}"))?; + let idp_key = crate::global_settings::MCP_EXTERNAL_IDP_SETTING; + crate::global_settings::parse_mcp_external_idp(desired.get(idp_key)) + .map_err(|e| anyhow::anyhow!("{idp_key}: {e}"))?; + let mut diff = diff_global_settings(current, desired, ApplyMode::Replace); let roles_key = crate::global_settings::WORKSPACE_ROLES_SETTING; let roles_written = diff.upserts.iter().any(|(k, _)| k == roles_key) diff --git a/backend/windmill-common/src/scopes.rs b/backend/windmill-common/src/scopes.rs index 2f58485896..8549e673ba 100644 --- a/backend/windmill-common/src/scopes.rs +++ b/backend/windmill-common/src/scopes.rs @@ -381,7 +381,9 @@ impl ScopeDomain { "data_metrics" => Some(Self::DataMetrics), "flows" => Some(Self::Flows), "flow_conversations" => Some(Self::FlowConversations), - "apps" | "apps_u" => Some(Self::Apps), + // `shared_ui` is the workspace `ui/` folder raw apps import from, so a token + // that syncs apps reaches it without a scope of its own. + "apps" | "apps_u" | "shared_ui" => Some(Self::Apps), "variables" => Some(Self::Variables), "resources" => Some(Self::Resources), "schedules" => Some(Self::Schedules), @@ -422,7 +424,8 @@ impl ScopeDomain { "concurrency_groups" => Some(Self::ConcurrencyGroups), "oidc" => Some(Self::Oidc), "openapi" => Some(Self::Openapi), - "acls" => Some(Self::Acls), + // `/access` reports which grants reach a principal, so `acls` scopes cover it. + "acls" | "access" => Some(Self::Acls), "raw_apps" => Some(Self::RawApps), "agent_workers" => Some(Self::AgentWorkers), "mcp" => Some(Self::Mcp), diff --git a/backend/windmill-common/src/secret_backend/external_ref.rs b/backend/windmill-common/src/secret_backend/external_ref.rs new file mode 100644 index 0000000000..375bbbb14f --- /dev/null +++ b/backend/windmill-common/src/secret_backend/external_ref.rs @@ -0,0 +1,359 @@ +/* + * Author: Ruben Fiszel + * Copyright: Windmill Labs, Inc 2026 + * This file and its contents are licensed under the AGPLv3 License. + * Please see the included NOTICE for copyright information and + * LICENSE-AGPL for a copy of the license. + */ + +//! References from a secret variable to a secret that already exists in an +//! external store: the variable stores `$external:://#` and +//! the value is read from the store each time the variable is read. Unlike the +//! `$vault:`/`$aws_sm:`/`$azure_kv:` markers of a managed secret backend, +//! nothing is ever written to the store. Only `vault://` resolves, with `` +//! written as `vault kv get` takes it. +//! +//! The instance's identity in the store can usually read far more than any one +//! workspace should, so a reference resolves only under a prefix a superadmin +//! allowed for that workspace in the `external_secrets` setting. The check runs +//! on save and again on every read, so narrowing the list takes effect on +//! existing references. + +use serde::{Deserialize, Serialize}; + +use crate::{ + db::DB, + error::{Error, Result}, + global_settings::{ + load_value_from_global_settings, EXTERNAL_SECRETS_SETTING, SECRET_BACKEND_SETTING, + }, + secret_backend::{SecretBackendConfig, VaultSettings}, +}; + +pub const EXTERNAL_REF_MARKER: &str = "$external:"; + +/// The `external_secrets` instance setting: the connections references are +/// read through, and where they may point. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] +pub struct ExternalSecretsSettings { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub vault: Option, + #[serde(default)] + pub allowed: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct ExternalSecretAllowedPrefix { + /// `://`, the path matched on whole segments. + pub prefix: String, + /// Workspaces that may reference under `prefix`; empty means all. + #[serde(default)] + pub workspaces: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExternalSecretBackend { + Vault, +} + +impl ExternalSecretBackend { + fn scheme(self) -> &'static str { + match self { + Self::Vault => "vault", + } + } + + fn from_scheme(scheme: &str) -> Result { + match scheme { + "vault" => Ok(Self::Vault), + _ => Err(Error::BadRequest(format!( + "Unsupported external secret backend `{scheme}://`: only `vault://` is supported" + ))), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExternalSecretRef { + pub backend: ExternalSecretBackend, + /// Normalized: no surrounding or doubled slashes. + pub path: String, + /// `None` reads the whole secret, as a JSON object of its fields. + pub key: Option, +} + +pub fn is_external_ref_value(value: &str) -> bool { + value.starts_with(EXTERNAL_REF_MARKER) +} + +/// A stored secret value whose plaintext is not workspace ciphertext but lives +/// in an external store: a managed backend entry or an `$external:` reference. +pub fn resolves_externally(value: &str) -> bool { + super::is_external_stored_value(value) || is_external_ref_value(value) +} + +fn path_segments(path: &str) -> Result> { + let segments: Vec<&str> = path.trim().trim_matches('/').split('/').collect(); + // The URL parser treats `\` as `/` and drops tabs and newlines, so either would let a + // `..` segment slip past this check and the allow-list. + if segments.iter().any(|s| { + s.is_empty() + || *s == "." + || *s == ".." + || s.contains(['?', '%', '#', '\\']) + || s.contains(char::is_control) + }) { + return Err(Error::BadRequest(format!( + "Invalid external secret path `{path}`: expected segments like `secret/team/app`" + ))); + } + Ok(segments) +} + +fn split_scheme(uri: &str) -> Result<(ExternalSecretBackend, &str)> { + let (scheme, rest) = uri.trim().split_once("://").ok_or_else(|| { + Error::BadRequest(format!( + "Invalid external secret reference `{uri}`: expected `://[#]`, e.g. `vault://secret/team/app#token`" + )) + })?; + Ok((ExternalSecretBackend::from_scheme(scheme)?, rest)) +} + +/// Parses `$external:://[#]` (the marker is optional). +pub fn parse_external_ref(value: &str) -> Result { + let uri = value.strip_prefix(EXTERNAL_REF_MARKER).unwrap_or(value); + let (backend, rest) = split_scheme(uri)?; + let (path, key) = match rest.split_once('#') { + Some((_, key)) if key.trim().is_empty() => { + return Err(Error::BadRequest(format!( + "Invalid external secret reference `{uri}`: the key after `#` is empty" + ))) + } + Some((path, key)) => (path, Some(key.trim().to_string())), + None => (rest, None), + }; + Ok(ExternalSecretRef { backend, path: path_segments(path)?.join("/"), key }) +} + +fn applies_to(a: &ExternalSecretAllowedPrefix, w_id: &str) -> bool { + a.workspaces.is_empty() || a.workspaces.iter().any(|w| w == w_id) +} + +/// The prefixes `w_id` may reference, as a superadmin wrote them. +pub async fn allowed_prefixes(db: &DB, w_id: &str) -> Result> { + Ok(load_settings(db) + .await? + .allowed + .into_iter() + .filter(|a| applies_to(a, w_id)) + .map(|a| a.prefix) + .collect()) +} + +fn is_allowed(settings: &ExternalSecretsSettings, w_id: &str, r: &ExternalSecretRef) -> bool { + let path: Vec<&str> = r.path.split('/').collect(); + settings.allowed.iter().any(|a| { + applies_to(a, w_id) + && split_scheme(&a.prefix).is_ok_and(|(backend, prefix)| { + backend == r.backend && path_segments(prefix).is_ok_and(|p| path.starts_with(&p)) + }) + }) +} + +async fn load_settings(db: &DB) -> Result { + match load_value_from_global_settings(db, EXTERNAL_SECRETS_SETTING).await? { + Some(value) => serde_json::from_value(value).map_err(|e| { + Error::internal_err(format!("Invalid {EXTERNAL_SECRETS_SETTING} setting: {e}")) + }), + None => Ok(ExternalSecretsSettings::default()), + } +} + +fn vault_segments(s: Option<&str>) -> Vec<&str> { + s.unwrap_or_default() + .split('/') + .filter(|s| !s.trim().is_empty()) + .collect() +} + +/// Whether `path`, read through `conn`, lands in the storage of the managed Vault +/// backend `managed`. The namespace is folded into the path because Vault also +/// takes a namespace as a path prefix, so `ns/kv/x` with no namespace header +/// reaches the same secret as `kv/x` under namespace `ns`. +fn is_managed_storage(managed: &VaultSettings, conn: &VaultSettings, path: &str) -> bool { + let address = |s: &VaultSettings| s.address.trim().trim_end_matches('/').to_lowercase(); + let mount = vault_segments(Some(&managed.mount_path)); + if mount.is_empty() || address(managed) != address(conn) { + return false; + } + let mut storage = vault_segments(managed.namespace.as_deref()); + storage.extend(mount); + storage.extend(vault_segments(managed.kv_secret_path_prefix.as_deref())); + let mut target = vault_segments(conn.namespace.as_deref()); + target.extend(vault_segments(Some(path))); + target.starts_with(&storage) +} + +/// Parses a reference, checks it is allowed for `w_id`, and returns the Vault +/// connection to read it through: the `external_secrets` one, or else the +/// managed backend's when that is Vault. +async fn authorize( + db: &DB, + w_id: &str, + value: &str, +) -> Result<(Option, ExternalSecretRef)> { + let r = parse_external_ref(value)?; + let settings = load_settings(db).await?; + if !is_allowed(&settings, w_id, &r) { + let allowed: Vec<_> = settings + .allowed + .iter() + .filter(|a| applies_to(a, w_id)) + .map(|a| format!("`{}/**`", a.prefix.trim_end_matches('/'))) + .collect(); + let target = format!("External secret `{}://{}`", r.backend.scheme(), r.path); + return Err(Error::PermissionDenied(if allowed.is_empty() { + format!("{target} is not allowed: no Vault paths are allowed for workspace {w_id} (instance settings > Secret storage)") + } else { + format!( + "{target} is outside the paths allowed for workspace {w_id}: {}", + allowed.join(", ") + ) + })); + } + let managed = match load_value_from_global_settings(db, SECRET_BACKEND_SETTING) + .await? + .and_then(|v| serde_json::from_value(v).ok()) + { + Some(SecretBackendConfig::HashiCorpVault(managed)) => Some(managed), + _ => None, + }; + let conn = settings.vault.or_else(|| managed.clone()); + // The managed backend's storage holds every workspace's secrets, so no + // allow-list entry may open it. + if let (Some(managed), Some(conn)) = (&managed, &conn) { + if is_managed_storage(managed, conn, &r.path) { + return Err(Error::PermissionDenied(format!( + "External secret `vault://{}` points into the storage of Windmill's own Vault secret backend", + r.path + ))); + } + } + Ok((conn, r)) +} + +/// Write-time check of an `$external:` value. Does not contact the store, so a +/// reference may be saved before its secret exists. +pub async fn check_external_ref(db: &DB, w_id: &str, value: &str) -> Result<()> { + authorize(db, w_id, value).await.map(|_| ()) +} + +pub(crate) async fn resolve_external_ref( + db: &DB, + w_id: &str, + variable_path: &str, + value: &str, +) -> Result { + let (conn, r) = authorize(db, w_id, value).await?; + let read = match r.backend { + ExternalSecretBackend::Vault => { + let vault = conn.as_ref().ok_or_else(|| { + Error::BadRequest( + "No Vault connection is configured for external secrets (instance settings > Secret storage)" + .to_string(), + ) + })?; + super::read_vault_external_secret(db, vault, &r.path, r.key.as_deref()).await + } + }; + read.map_err(|e| match e { + Error::NotFound(m) => Error::NotFound(format!("{m} (variable {variable_path})")), + Error::PermissionDenied(m) => { + Error::PermissionDenied(format!("{m} (variable {variable_path})")) + } + e => e, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn settings(allowed: &[(&str, &[&str])]) -> ExternalSecretsSettings { + serde_json::from_value(serde_json::json!({ + "allowed": allowed + .iter() + .map(|(p, w)| serde_json::json!({"prefix": p, "workspaces": w})) + .collect::>(), + })) + .unwrap() + } + + fn allowed(s: &ExternalSecretsSettings, w_id: &str, value: &str) -> bool { + is_allowed(s, w_id, &parse_external_ref(value).unwrap()) + } + + #[test] + fn parses_references() { + assert_eq!( + parse_external_ref("$external:vault:///secret/team/app/#token").unwrap(), + ExternalSecretRef { + backend: ExternalSecretBackend::Vault, + path: "secret/team/app".to_string(), + key: Some("token".to_string()) + } + ); + assert_eq!( + parse_external_ref("$external:vault://secret/team/app") + .unwrap() + .key, + None + ); + for bad in [ + "$external:secret/app#k", + "$external:vault://secret/app#", + "$external:vault://secret//app#k", + "$external:vault://secret/../sys#k", + "$external:vault://secret/team/..\\other/app#k", + "$external:vault://secret/app?list=true#k", + "$external:aws-sm://secret/app#k", + ] { + assert!(parse_external_ref(bad).is_err(), "{bad}"); + } + } + + #[test] + fn allow_list_matches_whole_segments_and_workspaces() { + let s = settings(&[ + ("vault://secret/team", &["ws1"]), + ("vault://kv/shared/", &[]), + ]); + assert!(allowed(&s, "ws1", "vault://secret/team/app#k")); + assert!(allowed(&s, "ws1", "vault://secret/team#k")); + assert!(!allowed(&s, "ws1", "vault://secret/team-other/app#k")); + assert!(!allowed(&s, "ws2", "vault://secret/team/app#k")); + assert!(allowed(&s, "ws2", "vault://kv/shared/x#k")); + assert!(!allowed(&s, "ws2", "vault://kv#k")); + } + + #[test] + fn refuses_the_managed_backend_storage() { + let vault = |address: &str, mount: &str, prefix: Option<&str>, ns: Option<&str>| { + serde_json::from_value::(serde_json::json!({ + "address": address, "mount_path": mount, + "kv_secret_path_prefix": prefix, "namespace": ns, + })) + .unwrap() + }; + let managed = vault("https://vault:8200", "kv", Some("/apps/wm/"), Some("ns")); + let same = vault("https://vault:8200/", "", None, Some("ns")); + assert!(is_managed_storage(&managed, &same, "kv/apps/wm/ws1/f/x")); + assert!(is_managed_storage(&managed, &same, "kv/apps/wm")); + assert!(!is_managed_storage(&managed, &same, "kv/apps/other/x")); + assert!(!is_managed_storage(&managed, &same, "secret/apps/wm/x")); + let root = vault("https://vault:8200", "", None, None); + assert!(is_managed_storage(&managed, &root, "ns/kv/apps/wm/ws1/x")); + let other = vault("https://other:8200", "", None, Some("ns")); + assert!(!is_managed_storage(&managed, &other, "kv/apps/wm/ws1/x")); + } +} diff --git a/backend/windmill-common/src/secret_backend/mod.rs b/backend/windmill-common/src/secret_backend/mod.rs index 9fd117c235..a721f0fb39 100644 --- a/backend/windmill-common/src/secret_backend/mod.rs +++ b/backend/windmill-common/src/secret_backend/mod.rs @@ -14,8 +14,10 @@ pub mod database; pub mod resolver; +pub mod external_ref; pub use resolver::*; +pub use external_ref::*; #[cfg(feature = "private")] pub mod vault_ee; @@ -138,7 +140,9 @@ impl Default for SecretBackendConfig { pub struct VaultSettings { /// Vault server address (e.g., "https://vault.company.com:8200") pub address: String, - /// KV v2 mount path (e.g., "windmill") + /// KV v2 mount path (e.g., "windmill"). Empty for the external-secrets + /// connection, which reads whatever mount a reference names. + #[serde(default)] pub mount_path: String, /// Optional path prefix inserted between the KV `data`/`metadata` segment /// and the workspace id, e.g. "apps/windmill". When set, secrets live at @@ -156,6 +160,15 @@ pub struct VaultSettings { /// e.g. via `vault auth enable -path=my-mount jwt`. #[serde(skip_serializing_if = "Option::is_none")] pub jwt_mount_path: Option, + /// AppRole role_id. When set (and no static token), Windmill logs in with + /// AppRole; the secret_id is read from the `VAULT_APPROLE_SECRET_ID` + /// environment variable of servers and workers, never from settings, and + /// is omitted when unset (a role with `bind_secret_id=false`). + #[serde(skip_serializing_if = "Option::is_none")] + pub approle_role_id: Option, + /// Mount path of the AppRole auth method (defaults to "approle"). + #[serde(skip_serializing_if = "Option::is_none")] + pub approle_mount_path: Option, /// Vault Enterprise namespace (optional) #[serde(skip_serializing_if = "Option::is_none")] pub namespace: Option, diff --git a/backend/windmill-common/src/secret_backend/resolver.rs b/backend/windmill-common/src/secret_backend/resolver.rs index 4a9a65bc0d..fff58528c1 100644 --- a/backend/windmill-common/src/secret_backend/resolver.rs +++ b/backend/windmill-common/src/secret_backend/resolver.rs @@ -298,6 +298,9 @@ pub async fn get_secret_value( path: &str, encrypted_value: &str, ) -> Result { + if super::is_external_ref_value(encrypted_value) { + return super::resolve_external_ref(db, workspace_id, path, encrypted_value).await; + } let backend = get_secret_backend(db).await?; match backend.backend_name() { diff --git a/backend/windmill-common/src/secret_backend/tests.rs b/backend/windmill-common/src/secret_backend/tests.rs index 8f04a755b7..d749e8f27e 100644 --- a/backend/windmill-common/src/secret_backend/tests.rs +++ b/backend/windmill-common/src/secret_backend/tests.rs @@ -28,6 +28,8 @@ mod tests { kv_secret_path_prefix: None, jwt_role: Some("windmill-secrets".to_string()), jwt_mount_path: None, + approle_role_id: None, + approle_mount_path: None, namespace: None, token: Some("test-root-token".to_string()), skip_ssl_verify: None, diff --git a/backend/windmill-common/src/secret_backend/vault_oss.rs b/backend/windmill-common/src/secret_backend/vault_oss.rs index a20738f118..8ee486dd11 100644 --- a/backend/windmill-common/src/secret_backend/vault_oss.rs +++ b/backend/windmill-common/src/secret_backend/vault_oss.rs @@ -129,3 +129,15 @@ pub async fn generate_vault_jwt(_db: &DB, _vault_address: &str) -> Result, +) -> Result { + Err(Error::internal_err( + "HashiCorp Vault integration requires Enterprise Edition".to_string(), + )) +} diff --git a/backend/windmill-common/src/sensitive_log_masks.rs b/backend/windmill-common/src/sensitive_log_masks.rs index f01ca2427e..4c1c73e277 100644 --- a/backend/windmill-common/src/sensitive_log_masks.rs +++ b/backend/windmill-common/src/sensitive_log_masks.rs @@ -220,6 +220,31 @@ pub fn unregister_running_job(job_id: Uuid) { } } +/// `secret` and, when it spans several lines, each of them: `handle_child` masks a log +/// line by line, so a multi-line secret such as a PEM key never matches as a whole. Masks +/// apply to every running job, so lines any job may print are left out: PEM armor, and the +/// lines of a JSON document (`"type": "service_account",`). +fn mask_patterns(secret: &str) -> impl Iterator { + let split = secret.contains('\n') && !secret.trim_start().starts_with(['{', '[']); + let lines = split.then(|| { + secret + .lines() + .map(str::trim) + .filter(|l| !l.starts_with("-----")) + }); + std::iter::once(secret) + .chain(lines.into_iter().flatten()) + .filter(|s| s.len() >= MIN_SECRET_LENGTH) +} + +fn insert_masks(job: &mut JobMasks, secret: &str) { + for pattern in mask_patterns(secret) { + if job.secrets.insert(pattern.to_string()) { + job.compiled = None; + } + } +} + /// Register a secret value for ALL currently running jobs. /// Used when a secret is fetched via the embedded server (we don't know which job triggered it). pub fn register_secret_for_all_running_jobs(secret: &str) { @@ -236,13 +261,42 @@ pub fn register_secret_for_all_running_jobs(secret: &str) { let mut masks = SENSITIVE_MASKS.write().unwrap_or_else(|e| e.into_inner()); for job_id in job_ids { if let Some(job) = masks.get_mut(&job_id) { - if job.secrets.insert(secret.to_string()) { - job.compiled = None; - } + insert_masks(job, secret); } } } +/// Like [`register_secret_for_all_running_jobs`], and when `secret` is a JSON object or +/// array also each string in it: `$jsonvar:` hands a job the parsed value, which can then +/// print one field on its own. Only for values whose every field is secret, such as a whole +/// Vault secret: masks apply to every running job, and a JSON variable's other fields +/// (`"user": "postgres"`) would mask unrelated logs. +pub fn register_secret_and_fields_for_all_running_jobs(secret: &str) { + register_secret_for_all_running_jobs(secret); + for field in json_strings(secret) { + register_secret_for_all_running_jobs(&field); + } +} + +/// Every string inside `secret` when it is a JSON object or array. +fn json_strings(secret: &str) -> Vec { + fn walk(v: serde_json::Value, out: &mut Vec) { + match v { + serde_json::Value::String(s) => out.push(s), + serde_json::Value::Array(a) => a.into_iter().for_each(|v| walk(v, out)), + serde_json::Value::Object(o) => o.into_iter().for_each(|(_, v)| walk(v, out)), + _ => {} + } + } + let mut out = vec![]; + if secret.trim_start().starts_with(['{', '[']) { + if let Ok(v) = serde_json::from_str(secret) { + walk(v, &mut out); + } + } + out +} + /// Register a secret value for a specific job. /// Used for the job's own token and for `$encrypted:` args, where we know the job ID. pub fn register_secret_for_job(job_id: Uuid, secret: &str) { @@ -251,9 +305,7 @@ pub fn register_secret_for_job(job_id: Uuid, secret: &str) { } let mut masks = SENSITIVE_MASKS.write().unwrap_or_else(|e| e.into_inner()); if let Some(job) = masks.get_mut(&job_id) { - if job.secrets.insert(secret.to_string()) { - job.compiled = None; - } + insert_masks(job, secret); } } @@ -281,6 +333,32 @@ mod tests { unregister_running_job(job_id); } + /// Logs are masked line by line, so a multi-line secret must be masked one line at a time. + #[test] + fn masks_each_line_of_a_multi_line_secret() { + let job_id = Uuid::new_v4(); + register_running_job(job_id); + register_secret_for_job( + job_id, + "-----BEGIN KEY-----\nfirstlineofkey\nsecondlineofkey\n", + ); + let snap = snapshot(&job_id).expect("secret registered"); + for line in ["firstlineofkey", "secondlineofkey"] { + assert!(!snap.mask(line).contains(line), "{line}"); + } + assert_eq!(snap.mask("-----BEGIN KEY-----"), "-----BEGIN KEY-----"); + unregister_running_job(job_id); + } + + #[test] + fn finds_each_string_of_a_whole_secret() { + assert_eq!( + json_strings(r#"{"a":"secretvalue1","b":["secretvalue2"],"n":12345678}"#), + ["secretvalue1", "secretvalue2"] + ); + assert!(json_strings("not json").is_empty()); + } + /// A line-by-line sink must not repeat the notice on every line, and must still /// pick up a secret registered after the masker was built. #[test] @@ -341,4 +419,22 @@ mod tests { unregister_running_job(job_id); } + + /// A secret containing another must be masked whole (`LeftmostLongest`), or its + /// tail leaks; the kept prefix/suffix must be cut by char, or multi-byte secrets panic. + #[test] + fn overlapping_and_multibyte_secrets_are_masked_whole() { + let job_id = Uuid::new_v4(); + register_running_job(job_id); + register_secret_for_job(job_id, "password"); + register_secret_for_job(job_id, "password-and-more"); + register_secret_for_job(job_id, "🔑éàü-secret-value-ñ€😀"); + + let masked = snapshot(&job_id) + .expect("secrets registered") + .mask("password-and-more 🔑éàü-secret-value-ñ€😀"); + assert_eq!(masked, format!("p*****e 🔑éà*****ñ€😀\n{MASKED_NOTICE}")); + + unregister_running_job(job_id); + } } diff --git a/backend/windmill-common/src/variables.rs b/backend/windmill-common/src/variables.rs index f3ee17769b..3e17b5140d 100644 --- a/backend/windmill-common/src/variables.rs +++ b/backend/windmill-common/src/variables.rs @@ -9,7 +9,7 @@ use crate::db::{Authable, UserDB}; use crate::error::{self, Error}; use crate::scripts::ScriptHash; -use crate::secret_backend::{get_secret_value, is_external_stored_value}; +use crate::secret_backend::{get_secret_value, resolves_externally}; use crate::utils::{strip_json_nul, WarnAfterExt}; use crate::worker::{to_raw_value, Connection}; use crate::workspace_crypt::CipherFormat; @@ -490,7 +490,7 @@ pub async fn decrypt_secret_value( ) -> crate::error::Result { if value.is_empty() { Ok(value) - } else if is_external_stored_value(&value) { + } else if resolves_externally(&value) { get_secret_value(db, w_id, path, &value).await } else { let mc = build_crypt(db, w_id).await?; @@ -687,7 +687,7 @@ async fn upgrade_workspace_secret_variables(db: &DB, w_id: &str) -> error::Resul .await?; let last_page = (rows.len() as i64) < LEGACY_SECRET_UPGRADE_BATCH; for (path, value) in rows { - if value.is_empty() || is_external_stored_value(&value) || mc.is_v2(&value) { + if value.is_empty() || resolves_externally(&value) || mc.is_v2(&value) { after = path; continue; } @@ -1029,7 +1029,7 @@ pub async fn get_variable_or_self( if let Some(record) = record { let mut value = record.value; if record.is_secret { - if is_external_stored_value(&value) { + if resolves_externally(&value) { value = get_secret_value(db, w_id, &path, &value).await?; } else { let mc = build_crypt(db, w_id).await?; @@ -1078,7 +1078,7 @@ pub async fn get_variable_or_self_as( if let Some(record) = record { let mut value = record.value; if record.is_secret { - if is_external_stored_value(&value) { + if resolves_externally(&value) { value = get_secret_value(db, w_id, &var_path, &value).await?; } else { let mc = build_crypt(db, w_id).await?; diff --git a/backend/windmill-common/src/worker.rs b/backend/windmill-common/src/worker.rs index e6a44054d9..2f18ed262c 100644 --- a/backend/windmill-common/src/worker.rs +++ b/backend/windmill-common/src/worker.rs @@ -825,7 +825,7 @@ fn format_pull_query(peek: String) -> String { j.script_entrypoint_override, j.preprocessed, p.job_token_scopes, COALESCE(pj.runnable_path, j.args->>'_FLOW_PATH') as parent_runnable_path, COALESCE(p.email, j.permissioned_as_email) as permissioned_as_email, p.username as permissioned_as_username, p.is_admin as permissioned_as_is_admin, p.is_operator as permissioned_as_is_operator, p.groups as permissioned_as_groups, p.folders as permissioned_as_folders, p.end_user_email as permissioned_as_end_user_email, - p.viewer_data_access + p.viewer_data_access, p.mcp_client FROM q, j LEFT JOIN v2_job_status f USING (id) LEFT JOIN job_perms p ON p.job_id = j.id diff --git a/backend/windmill-common/src/workspaces.rs b/backend/windmill-common/src/workspaces.rs index 7f4c60faa3..0a3bf0ac6f 100644 --- a/backend/windmill-common/src/workspaces.rs +++ b/backend/windmill-common/src/workspaces.rs @@ -11,7 +11,7 @@ use crate::{ error::{self, to_anyhow, Error, Result}, get_database_url, roles::{caller_capabilities, AuthorLevel, RoleCapabilities}, - secret_backend::{get_secret_value, is_external_stored_value}, + secret_backend::{get_secret_value, resolves_externally}, utils::{get_custom_pg_instance_password, get_custom_pg_instance_replication_password}, variables::{build_crypt, decrypt}, PgDatabase, DB, @@ -3813,7 +3813,7 @@ async fn transform_json_unchecked( .map_err(to_anyhow)? .ok_or_else(|| Error::NotFound(format!("variable {path} does not exist")))?; let value = if is_secret { - if is_external_stored_value(&value) { + if resolves_externally(&value) { get_secret_value(db, w_id, &s[5..], &value).await? } else { let mc = build_crypt(&db, &w_id).await?; diff --git a/backend/windmill-common/tests/secret_backend_integration.rs b/backend/windmill-common/tests/secret_backend_integration.rs index a94a67e336..1a861a297c 100644 --- a/backend/windmill-common/tests/secret_backend_integration.rs +++ b/backend/windmill-common/tests/secret_backend_integration.rs @@ -79,6 +79,8 @@ mod tests { kv_secret_path_prefix: None, jwt_role: None, // Static token mode jwt_mount_path: None, + approle_role_id: None, + approle_mount_path: None, namespace: None, token: Some( std::env::var("VAULT_TOKEN").unwrap_or_else(|_| "test-root-token".to_string()), @@ -96,6 +98,8 @@ mod tests { kv_secret_path_prefix: None, jwt_role: Some("windmill-secrets".to_string()), // JWT mode jwt_mount_path: None, + approle_role_id: None, + approle_mount_path: None, namespace: None, token: None, // No static token - use JWT skip_ssl_verify: None, diff --git a/backend/windmill-common/tests/secret_backend_migration.rs b/backend/windmill-common/tests/secret_backend_migration.rs index 5a4086fa1b..2a6981794c 100644 --- a/backend/windmill-common/tests/secret_backend_migration.rs +++ b/backend/windmill-common/tests/secret_backend_migration.rs @@ -37,6 +37,8 @@ fn test_vault_settings() -> VaultSettings { kv_secret_path_prefix: None, jwt_role: Some("windmill-secrets".to_string()), jwt_mount_path: None, + approle_role_id: None, + approle_mount_path: None, namespace: None, token: Some(std::env::var("VAULT_TOKEN").unwrap_or_else(|_| "test-root-token".to_string())), skip_ssl_verify: None, diff --git a/backend/windmill-mcp/src/server/backend.rs b/backend/windmill-mcp/src/server/backend.rs index 9a305843d2..76613525db 100644 --- a/backend/windmill-mcp/src/server/backend.rs +++ b/backend/windmill-mcp/src/server/backend.rs @@ -97,6 +97,17 @@ pub trait McpBackend: Send + Sync + Clone + 'static { /// The authentication context type type Auth: McpAuth; + /// Called once a tool call in a workspace has an outcome: `refusal` is the error the + /// caller receives, `None` when it succeeded. + async fn after_tool_call( + &self, + _auth: &Self::Auth, + _workspace_id: &str, + _tool: &str, + _refusal: Option<&str>, + ) { + } + // ───────────────────────────────────────────────────────────────── // Listing Operations // ───────────────────────────────────────────────────────────────── diff --git a/backend/windmill-mcp/src/server/runner.rs b/backend/windmill-mcp/src/server/runner.rs index e2ce8b6c04..6e18f36c7b 100644 --- a/backend/windmill-mcp/src/server/runner.rs +++ b/backend/windmill-mcp/src/server/runner.rs @@ -637,16 +637,22 @@ impl ServerHandler for Runner { // client for input, so the MRTR variants of `CallToolResponse` are never built. let result = match mode { McpMode::Single(workspace_id) => { - self.call_tool_single( - &auth, - &workspace_id, - &scope_config, - read_only, - request.name.clone(), - args, - &mcp_request, - ) - .await + let result = self + .call_tool_single( + &auth, + &workspace_id, + &scope_config, + read_only, + request.name.clone(), + args, + &mcp_request, + ) + .await; + let refusal = result.as_ref().err().map(|e| e.message.as_ref()); + self.backend + .after_tool_call(&auth, &workspace_id, &request.name, refusal) + .await; + result } McpMode::Multi(token) => { self.call_tool_multi( @@ -951,12 +957,32 @@ impl Runner { let named = self .name_runnables(auth, workspace_id, scope_config, filter, filter) .await?; - let (tool_type, path, _) = named - .into_iter() - .find(|(_, _, n)| n == name.as_ref()) - .ok_or_else(|| { - ErrorData::internal_error(format!("No tool named '{}'", name), None) - })?; + let Some((tool_type, path, _)) = named.into_iter().find(|(_, _, n)| n == name.as_ref()) + else { + // Says which side refused: the token's selection, or the user's own rights. + let message = if scope_config.granular + && self + .name_runnables( + auth, + workspace_id, + &crate::common::scope::McpScopeConfig { + scripts: vec!["*".to_string()], + flows: vec!["*".to_string()], + ..Default::default() + }, + filter, + filter, + ) + .await? + .iter() + .any(|(_, _, n)| n == name.as_ref()) + { + format!("Access denied: tool '{name}' is outside this token's selection") + } else { + format!("No tool named '{name}' is available to this user") + }; + return Err(ErrorData::internal_error(message, None)); + }; (tool_type, path, false) } else { // The `s-`/`f-`/`hs-` encoding: what hub scripts and items whose short diff --git a/backend/windmill-mcp/src/server/session.rs b/backend/windmill-mcp/src/server/session.rs index d9bb9e829b..4632541d0c 100644 --- a/backend/windmill-mcp/src/server/session.rs +++ b/backend/windmill-mcp/src/server/session.rs @@ -374,7 +374,7 @@ impl ServerHandler for SessionRunner { let text = self.backend.workspace_context(&auth, &workspace_id).await; return Ok(CallToolResult::success(vec![ContentBlock::text(text)]).into()); } - let mut result = self + let result = self .backend .call_session_tool( &auth, @@ -384,7 +384,12 @@ impl ServerHandler for SessionRunner { access(&auth, &caller.scope), caller.origin.as_deref(), ) - .await?; + .await; + let refusal = result.as_ref().err().map(|e| e.message.as_ref()); + self.backend + .after_tool_call(&auth, &workspace_id, &request.name, refusal) + .await; + let mut result = result?; for block in result.content.iter_mut() { if let Some(text) = block.as_text() { *block = ContentBlock::text(truncate_tool_result(text.text.clone())); diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index 289724c777..e357150cd2 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -3858,6 +3858,9 @@ pub struct MiniPulledJob { /// unrestricted token. #[serde(default)] pub job_token_scopes: Option>, + /// `job_perms.mcp_client`, read only on pull: see `ApiAuthed::mcp_client`. + #[serde(default)] + pub mcp_client: Option, } impl MiniPulledJob { @@ -3930,6 +3933,7 @@ impl MiniPulledJob { concurrent_limit: None, concurrency_time_window_s: None, job_token_scopes: None, + mcp_client: None, } } } @@ -4244,6 +4248,7 @@ impl PulledJob { end_user_email: self.job.permissioned_as_end_user_email.clone(), job_token_scopes: self.job.job_token_scopes.clone(), viewer_data_access: self.job.viewer_data_access.unwrap_or(false), + mcp_client: self.job.mcp_client.clone(), }), _ => None, }; @@ -4352,7 +4357,8 @@ pub async fn get_mini_pulled_job<'c>( visible_to_owner, NULL as permissioned_as_end_user_email, NULL::boolean as viewer_data_access, - job_perms.job_token_scopes + job_perms.job_token_scopes, + job_perms.mcp_client FROM v2_job_queue INNER JOIN v2_job ON v2_job.id = v2_job_queue.id LEFT JOIN v2_job_status ON v2_job_status.id = v2_job_queue.id LEFT JOIN job_perms ON job_perms.job_id = v2_job_queue.id WHERE v2_job_queue.id = $1", job_id, @@ -7780,7 +7786,8 @@ async fn push_inner<'c, 'd>( authed.clone() } _ => { - if authed.is_some() { + // An on-behalf-of run passes its MCP caller only to record the client. + if authed.is_some_and(|a| a.mcp_client.is_none()) { tracing::warn!("Authed passed to push is not the same as permissioned_as, refetching direclty permissions for job {job_id}...") } windmill_common::auth::fetch_authed_from_permissioned_as( @@ -7914,9 +7921,9 @@ async fn push_inner<'c, 'd>( INSERT INTO v2_job_runtime (id, ping) VALUES ($1, null) ), inserted_job_perms AS ( - INSERT INTO job_perms (job_id, email, username, is_admin, is_operator, folders, groups, workspace_id, end_user_email, job_token_scopes) - values ($1, $32, $33, $34, $35, $36, $37, $2, $41, $47) - ON CONFLICT (job_id) DO UPDATE SET email = EXCLUDED.email, username = EXCLUDED.username, is_admin = EXCLUDED.is_admin, is_operator = EXCLUDED.is_operator, folders = EXCLUDED.folders, groups = EXCLUDED.groups, workspace_id = EXCLUDED.workspace_id, end_user_email = EXCLUDED.end_user_email, job_token_scopes = EXCLUDED.job_token_scopes + INSERT INTO job_perms (job_id, email, username, is_admin, is_operator, folders, groups, workspace_id, end_user_email, job_token_scopes, mcp_client) + values ($1, $32, $33, $34, $35, $36, $37, $2, $41, $47, $48) + ON CONFLICT (job_id) DO UPDATE SET email = EXCLUDED.email, username = EXCLUDED.username, is_admin = EXCLUDED.is_admin, is_operator = EXCLUDED.is_operator, folders = EXCLUDED.folders, groups = EXCLUDED.groups, workspace_id = EXCLUDED.workspace_id, end_user_email = EXCLUDED.end_user_email, job_token_scopes = EXCLUDED.job_token_scopes, mcp_client = EXCLUDED.mcp_client ) INSERT INTO v2_job_queue (workspace_id, id, running, scheduled_for, started_at, tag, priority, cache_ignore_s3_path, runnable_settings_handle) @@ -7972,6 +7979,9 @@ async fn push_inner<'c, 'd>( runnable_path, workspace_id, job_token_scopes.as_deref() as Option<&[String]>, + // From the pusher's identity, not `job_authed`: a run on behalf of another identity + // re-fetches its permissions, but was still started through the same client. + authed.and_then(|a| a.mcp_client.as_deref()), ) .execute(&mut *tx) .warn_after_seconds(1) @@ -8024,6 +8034,9 @@ async fn push_inner<'c, 'd>( let uuid_str = uuid_string.as_str(); let mut hm = HashMap::from([("uuid", uuid_str), ("permissioned_as", &permissioned_as)]); + if let Some(client) = authed.and_then(|a| a.mcp_client.as_deref()) { + hm.insert("mcp_client", client); + } let s: String; let operation_name = match job_kind { @@ -8969,7 +8982,7 @@ pub async fn get_same_worker_job( COALESCE(pj.runnable_path, v2_job.args->>'_FLOW_PATH') as parent_runnable_path, p.email as permissioned_as_email, p.username as permissioned_as_username, p.is_admin as permissioned_as_is_admin, p.is_operator as permissioned_as_is_operator, p.groups as permissioned_as_groups, p.folders as permissioned_as_folders, p.end_user_email as permissioned_as_end_user_email, - p.viewer_data_access + p.viewer_data_access, p.mcp_client FROM v2_job_queue INNER JOIN v2_job ON v2_job.id = v2_job_queue.id LEFT JOIN v2_job_status ON v2_job_status.id = v2_job_queue.id diff --git a/backend/windmill-queue/tests/debounce_test.rs b/backend/windmill-queue/tests/debounce_test.rs index 692a1108b3..2c4993ba75 100644 --- a/backend/windmill-queue/tests/debounce_test.rs +++ b/backend/windmill-queue/tests/debounce_test.rs @@ -3460,6 +3460,7 @@ mod debounce { viewer_data_access: None, runnable_settings_handle: rs_handle, job_token_scopes: None, + mcp_client: None, }; let pulled = PulledJob { @@ -3703,6 +3704,7 @@ mod debounce { viewer_data_access: None, runnable_settings_handle: rs_handle, job_token_scopes: None, + mcp_client: None, }; let pulled = PulledJob { diff --git a/backend/windmill-queue/tests/schedule_push.rs b/backend/windmill-queue/tests/schedule_push.rs index e79d4ff976..9e86386107 100644 --- a/backend/windmill-queue/tests/schedule_push.rs +++ b/backend/windmill-queue/tests/schedule_push.rs @@ -65,6 +65,7 @@ mod schedule_push { folders: vec![], scopes: None, token_prefix: None, + mcp_client: None, } } diff --git a/backend/windmill-store/src/secret_backend_ext.rs b/backend/windmill-store/src/secret_backend_ext.rs index 16d8ae5a93..af0380a5ab 100644 --- a/backend/windmill-store/src/secret_backend_ext.rs +++ b/backend/windmill-store/src/secret_backend_ext.rs @@ -23,9 +23,10 @@ use windmill_common::{ }; pub use windmill_common::secret_backend::{ - get_secret_backend, get_secret_value, is_aws_sm_stored_value, is_azure_kv_stored_value, - is_external_stored_value, is_http_store_stored_value, is_vault_backend_configured, - is_vault_stored_value, + check_external_ref, get_secret_backend, get_secret_value, is_aws_sm_stored_value, + is_azure_kv_stored_value, is_external_ref_value, is_external_stored_value, + is_http_store_stored_value, is_vault_backend_configured, is_vault_stored_value, + parse_external_ref, resolves_externally, }; /// The HTTP store's key is derived from the variable path, so moving a reference would point it diff --git a/backend/windmill-store/src/variables.rs b/backend/windmill-store/src/variables.rs index b9e4d078d5..ef70e59bb7 100644 --- a/backend/windmill-store/src/variables.rs +++ b/backend/windmill-store/src/variables.rs @@ -14,9 +14,9 @@ use windmill_common::db::{Authable, DB}; use windmill_common::workspaces::{check_deploy_rules, operator_can_draft, RuleCheckResult}; use crate::secret_backend_ext::{ - delete_secret_from_backend, get_secret_value, http_store_rename_error, - is_external_stored_value, is_http_store_stored_value, is_vault_stored_value, - rename_vault_secret, store_managed_secret_value, store_secret_value, + check_external_ref, delete_secret_from_backend, get_secret_value, http_store_rename_error, + is_external_ref_value, is_http_store_stored_value, is_vault_stored_value, parse_external_ref, + rename_vault_secret, resolves_externally, store_managed_secret_value, store_secret_value, }; use windmill_common::utils::{ check_proper_path, escape_ilike_pattern, sanitize_db_error, BulkDeleteRequest, @@ -39,12 +39,13 @@ use windmill_common::{ db::{DbWithOptAuthed, UserDB}, error::{Error, JsonResult, Result}, scripts::ScriptHash, + secret_backend::allowed_prefixes, user_drafts::{ decrypt_draft_secret_value, delete_all_drafts_for_path, delete_own_draft_for_path, fetch_draft_only, fetch_draft_only_list_rows, maybe_overlay_draft, UserDraftItemKind, WithDraftOverlay, ENCRYPTED_DRAFT_PREFIX, }, - utils::{not_found_if_none, paginate, Pagination, StripPath, WarnAfterExt}, + utils::{not_found_if_none, paginate, require_admin, Pagination, StripPath, WarnAfterExt}, variables::{ build_crypt, get_reserved_variables, ContextualVariable, CreateVariable, ListableVariable, }, @@ -76,6 +77,10 @@ pub fn workspaced_service() -> Router { .route("/delete_bulk", delete(delete_variables_bulk)) .route("/create", post(create_variable)) .route("/encrypt", post(encrypt_value)) + .route( + "/external_secret_prefixes", + get(list_external_secret_prefixes), + ) } async fn list_contextual_variables( @@ -139,7 +144,8 @@ async fn list_variables( .fields(&[ "variable.workspace_id", "variable.path", - "CASE WHEN is_secret IS TRUE THEN null ELSE variable.value::text END as value", + // An `$external:` reference names where the secret lives, not the secret. + "CASE WHEN is_secret IS TRUE AND variable.value NOT LIKE '$external:%' THEN null ELSE variable.value::text END as value", "is_secret", "variable.description", "variable.extra_perms", @@ -426,7 +432,7 @@ async fn get_variable( } else if !value.is_empty() && decrypt_secret { // Use secret backend for decryption (supports both DB and Vault) Some(get_secret_value(&db, &w_id, &variable.path, &value).await?) - } else if q.include_encrypted.unwrap_or(false) { + } else if q.include_encrypted.unwrap_or(false) || is_external_ref_value(&value) { Some(value) } else { None @@ -580,7 +586,7 @@ async fn check_path_conflict(db: &DB, w_id: &str, path: &str) -> Result<()> { /// Values stored by an external backend ($vault:/$aws_sm:/$azure_kv:/$http_store: markers) /// are not workspace ciphertext and are passed through untouched. fn validate_already_encrypted_secret(path: &str, value: &str) -> Result<()> { - if is_external_stored_value(value) { + if resolves_externally(value) { return Ok(()); } let looks_like_ciphertext = STANDARD @@ -597,6 +603,71 @@ fn validate_already_encrypted_secret(path: &str, value: &str) -> Result<()> { Ok(()) } +/// Creating, repointing or removing an `$external:` reference takes a workspace +/// admin. Every reference resolves with the instance's one store identity, so +/// the allow-list cannot tell users apart: any writer could point a variable at +/// a secret under an allowed prefix and read it. +fn check_external_ref_change( + is_admin: bool, + old_ref: Option<&str>, + new_ref: Option<&str>, +) -> Result<()> { + if !is_admin && old_ref != new_ref { + return Err(Error::PermissionDenied( + "Only workspace admins can create, repoint or remove an external secret reference" + .to_string(), + )); + } + Ok(()) +} + +/// The `value` column for a secret sent to create or update, replacing +/// `old_ref` when the variable currently holds a reference. An `$external:` +/// reference is checked against the workspace's allowed prefixes and kept +/// verbatim, including when pushed as already encrypted by sync; any other +/// value goes to the configured secret backend, or with `windmill_writes` +/// (an OAuth token Windmill refreshes) to [`store_managed_secret_value`]. +async fn secret_value_to_store( + db: &DB, + w_id: &str, + path: &str, + value: String, + already_encrypted: bool, + op: &'static str, + is_admin: bool, + old_ref: Option<&str>, + windmill_writes: bool, +) -> Result { + if already_encrypted && !is_external_ref_value(&value) { + check_external_ref_change(is_admin, old_ref, None)?; + // Stored verbatim, so it must be ciphertext and not plaintext mislabeled as encrypted. + validate_already_encrypted_secret(path, &value)?; + return Ok(value); + } + // A restored draft sends the `$encrypted:` marker as-is; decrypt it back + // (validating against the workspace key) before storing it. + let value = if value.starts_with(ENCRYPTED_DRAFT_PREFIX) { + decrypt_draft_secret_value(db, w_id, &value).await? + } else { + value + }; + check_external_ref_change( + is_admin, + old_ref, + is_external_ref_value(&value).then_some(value.as_str()), + )?; + if is_external_ref_value(&value) { + check_external_ref(db, w_id, &value).await?; + windmill_common::feature_usage::log_feature_usage("external_secret_ref", "saved", op); + return Ok(value); + } + if windmill_writes { + store_managed_secret_value(db, w_id, path, &value).await + } else { + store_secret_value(db, w_id, path, &value).await + } +} + async fn create_variable( authed: ApiAuthed, Extension(db): Extension, @@ -644,7 +715,7 @@ pub async fn create_variable_with_account( user_db: UserDB, webhook: &WebhookShared, w_id: String, - variable: CreateVariable, + mut variable: CreateVariable, already_encrypted: bool, account: Option, ) -> Result> { @@ -680,25 +751,21 @@ pub async fn create_variable_with_account( let authed = maybe_refresh_folders(&variable.path, &w_id, authed, &db).await; check_path_conflict(&db, &w_id, &variable.path).await?; - let value = if variable.is_secret && !already_encrypted { - // A restored draft sends the `$encrypted:` marker as-is; decrypt it back - // (validating against the workspace key) before the secret backend re-stores it. - let plain = if variable.value.starts_with(ENCRYPTED_DRAFT_PREFIX) { - decrypt_draft_secret_value(&db, &w_id, &variable.value).await? - } else { - variable.value.clone() - }; - if account.is_some() { - store_managed_secret_value(&db, &w_id, &variable.path, &plain).await? - } else { - store_secret_value(&db, &w_id, &variable.path, &plain).await? - } + let value = if variable.is_secret { + let value = std::mem::take(&mut variable.value); + secret_value_to_store( + &db, + &w_id, + &variable.path, + value, + already_encrypted, + "create", + authed.is_admin, + None, + account.is_some(), + ) + .await? } else { - if variable.is_secret { - // already_encrypted == true: value is stored verbatim, so it must be - // ciphertext and not plaintext mislabeled as encrypted. - validate_already_encrypted_secret(&variable.path, &variable.value)?; - } variable.value }; @@ -788,6 +855,15 @@ pub async fn create_variable_with_account( Ok(account_id) } +async fn list_external_secret_prefixes( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, +) -> JsonResult> { + require_admin(authed.is_admin, &authed.username)?; + Ok(Json(allowed_prefixes(&db, &w_id).await?)) +} + async fn encrypt_value( Extension(db): Extension, Path(w_id): Path, @@ -821,9 +897,10 @@ async fn delete_variable( return Err(Error::PermissionDenied(msg)); } - // Check if variable is a secret before deleting (for Vault cleanup) + // Check if variable is a secret before deleting (for Vault cleanup). An external reference + // is excluded: its path may name a secret Windmill does not own. let is_secret = sqlx::query_scalar!( - "SELECT is_secret FROM variable WHERE path = $1 AND workspace_id = $2", + r#"SELECT is_secret AND value NOT LIKE '$external:%' AS "is_secret!" FROM variable WHERE path = $1 AND workspace_id = $2"#, path, &w_id ) @@ -995,9 +1072,9 @@ async fn delete_variables_bulk( return Err(Error::PermissionDenied(msg)); } - // Query which paths are secrets before deletion (for Vault cleanup) + // Query which paths are secrets before deletion (for Vault cleanup), external references excluded let secret_paths: Vec = sqlx::query_scalar!( - "SELECT path FROM variable WHERE path = ANY($1) AND workspace_id = $2 AND is_secret = true", + "SELECT path FROM variable WHERE path = ANY($1) AND workspace_id = $2 AND is_secret = true AND value NOT LIKE '$external:%'", &request.paths, &w_id ) @@ -1199,35 +1276,37 @@ async fn update_variable( // Determine the target path for storing secrets (use new path if provided) let target_path = ns.path.as_deref().unwrap_or(path); if let Some(nvalue) = ns.value.clone() { - let is_secret = if ns.is_secret.is_some() { - ns.is_secret.unwrap() - } else { - sqlx::query_scalar!( - "SELECT is_secret from variable WHERE path = $1 AND workspace_id = $2", - &path, - &w_id - ) - .fetch_optional(&db) - .await? - .unwrap_or(false) - }; + let old = sqlx::query!( + "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", + path, + w_id + ) + .fetch_optional(&db) + .await?; + let is_secret = ns + .is_secret + .unwrap_or_else(|| old.as_ref().is_some_and(|o| o.is_secret)); + let old_ref = old + .as_ref() + .filter(|o| o.is_secret && is_external_ref_value(&o.value)) + .map(|o| o.value.as_str()); - let value = if is_secret && !already_encrypted.unwrap_or(false) { - // Decrypt a restored draft's `$encrypted:` marker before re-storing; see create_variable. - let plain = if nvalue.starts_with(ENCRYPTED_DRAFT_PREFIX) { - decrypt_draft_secret_value(&db, &w_id, &nvalue).await? - } else { - nvalue - }; - // Use secret backend for encryption (supports both DB and Vault) - // Store at target_path (new path if renaming, otherwise current path) - store_secret_value(&db, &w_id, target_path, &plain).await? + let value = if is_secret { + // Stored at target_path (the new path when renaming) + secret_value_to_store( + &db, + &w_id, + target_path, + nvalue, + already_encrypted.unwrap_or(false), + "update", + authed.is_admin, + old_ref, + false, + ) + .await? } else { - if is_secret { - // already_encrypted == true: value is stored verbatim, so it must - // be ciphertext and not plaintext mislabeled as encrypted. - validate_already_encrypted_secret(target_path, &nvalue)?; - } + check_external_ref_change(authed.is_admin, old_ref, None)?; nvalue }; sqlb.set_str("value", &value); @@ -1594,6 +1673,10 @@ pub async fn get_value_internal<'a>( unreachable!() }; + // A reference is resolved on every read, so Vault rotation and allow-list changes apply at once. + let cacheable = !is_external_ref_value(&variable.value); + let whole_secret_ref = is_external_ref_value(&variable.value) + && parse_external_ref(&variable.value).is_ok_and(|r| r.key.is_none()); let r = if variable.is_secret { audit_decrypt_secret(db_with_opt_authed, &w_id, &variable.path).await?; @@ -1623,13 +1706,19 @@ pub async fn get_value_internal<'a>( }; if variable.is_secret && !r.is_empty() { - windmill_common::sensitive_log_masks::register_secret_for_all_running_jobs(&r); + if whole_secret_ref { + windmill_common::sensitive_log_masks::register_secret_and_fields_for_all_running_jobs( + &r, + ); + } else { + windmill_common::sensitive_log_masks::register_secret_for_all_running_jobs(&r); + } } // Cache the result when explicitly allowed. Secrets are cached too: their per-read side // effects (audit + running-job registration) are re-run on a hit (see the hit path above), // and `is_secret` is stored so the hit knows to do so. - if let Some(identity) = cache_identity.as_deref() { + if let Some(identity) = cache_identity.as_deref().filter(|_| cacheable) { cache_variable( &w_id, &path, diff --git a/backend/windmill-worker/src/common.rs b/backend/windmill-worker/src/common.rs index c0ae372e38..be2c7080d0 100644 --- a/backend/windmill-worker/src/common.rs +++ b/backend/windmill-worker/src/common.rs @@ -369,9 +369,11 @@ pub async fn transform_json_value( }) }) } - Connection::Http(_) => { - Err(Error::NotFound("Http connection not supported".to_string())) - } + Connection::Http(_) => Err(Error::ExecutionErr(format!( + "`{name}` is an `$encrypted:` value, which an agent worker cannot decrypt: \ + pass the secret as a `$var:` reference (in a flow, a static input or an \ + exact `flow_env.` read) and build the value inside the script" + ))), } // let path = y.strip_prefix("$res:").unwrap(); @@ -576,6 +578,17 @@ pub async fn get_reserved_variables( ) .await .to_vec(); + let mut variables = variables; + if let Some(client) = &job.mcp_client { + variables.push(variables::ContextualVariable { + name: "WM_MCP_CLIENT".to_string(), + value: client.clone(), + description: "OAuth client of the external identity provider the run was started \ + through on the user's behalf, propagated to flow steps" + .to_string(), + is_custom: false, + }); + } Ok(build_envs_map(variables).await) } @@ -2634,6 +2647,7 @@ mod tests { viewer_data_access: None, runnable_settings_handle: None, job_token_scopes: None, + mcp_client: None, } } diff --git a/backend/windmill-worker/src/worker_flow.rs b/backend/windmill-worker/src/worker_flow.rs index ff2a9db436..7c232fdca9 100644 --- a/backend/windmill-worker/src/worker_flow.rs +++ b/backend/windmill-worker/src/worker_flow.rs @@ -18,6 +18,7 @@ use crate::{ JobCompletedSender, PreviousResult, SameWorkerSender, SendResultPayload, StepFailureKind, UpdateFlow, KEEP_JOB_DIR, }; +use windmill_common::variables::{build_crypt_with_key_suffix, encrypt, WorkspaceCrypt}; use anyhow::Context; use async_once_cell::Lazy; @@ -2456,7 +2457,8 @@ async fn advance_flow_status( v2_job.visible_to_owner, NULL as permissioned_as_end_user_email, NULL::boolean as viewer_data_access, - job_perms.job_token_scopes", + job_perms.job_token_scopes, + NULL::varchar as mcp_client", flow, &step_path as &[&str], step, @@ -2888,11 +2890,132 @@ where } } +/// The unresolved `flow_env` and its secret entries, so that the args stored on a step job +/// never hold a resolved secret: an exact `flow_env.X` read stores the entry's reference, +/// resolved (audited and masked) when the step runs like a static input, and any other +/// expression reading a secret entry stores its result encrypted. +/// +/// A subflow step resolves nothing in its args, so it gets the resolved value of a +/// non-secret entry, while a secret one reaches it as a reference or encrypted, which its own +/// steps resolve or decrypt (they share its root job id). +pub(crate) struct FlowEnvRefs<'a> { + raw: &'a HashMap>, + db: &'a DB, + workspace_id: String, + root_job_id: Uuid, + // Loaded by the first input whose expression mentions `flow_env`, so that the steps + // reading none of it cost no query. + secrets: tokio::sync::OnceCell, +} + +struct FlowEnvSecrets { + entries: HashMap>, + // Keyed on the root job id, which is what the step's worker decrypts `$encrypted:` + // args with. Present only when `entries` is non-empty. + crypt: Option, +} + +impl<'a> FlowEnvRefs<'a> { + fn new(db: &'a DB, flow_job: &MiniPulledJob, raw: &'a HashMap>) -> Self { + Self { + raw, + db, + workspace_id: flow_job.workspace_id.clone(), + root_job_id: get_root_job_id(flow_job), + secrets: tokio::sync::OnceCell::new(), + } + } + + async fn secrets(&self) -> error::Result<&FlowEnvSecrets> { + self.secrets.get_or_try_init(|| self.load_secrets()).await + } + + async fn load_secrets(&self) -> error::Result { + let raw = self.raw; + let mut secret_keys = vec![]; + let mut var_keys: Vec<(String, String)> = vec![]; + for (k, v) in raw { + if !v.get().starts_with("\"$") { + continue; + } + let Ok(s) = serde_json::from_str::(v.get()) else { + continue; + }; + if s.starts_with("$encrypted:") { + secret_keys.push(k.clone()); + } else if let Some(path) = s + .strip_prefix("$var:") + .or_else(|| s.strip_prefix("$jsonvar:")) + { + var_keys.push((k.clone(), path.to_string())); + } + } + if !var_keys.is_empty() { + let paths: Vec = var_keys.iter().map(|(_, p)| p.clone()).collect(); + let secret_paths = sqlx::query_scalar!( + "SELECT path FROM variable WHERE workspace_id = $1 AND path = ANY($2) AND is_secret", + &self.workspace_id, + &paths + ) + .fetch_all(self.db) + .await?; + secret_keys.extend( + var_keys + .into_iter() + .filter(|(_, p)| secret_paths.contains(p)) + .map(|(k, _)| k), + ); + } + let entries: HashMap> = secret_keys + .into_iter() + .map(|k| (k.clone(), raw[&k].clone())) + .collect(); + let crypt = if entries.is_empty() { + None + } else { + Some( + build_crypt_with_key_suffix( + self.db, + &self.workspace_id, + &self.root_job_id.to_string(), + ) + .await?, + ) + }; + Ok(FlowEnvSecrets { entries, crypt }) + } +} + +impl FlowEnvSecrets { + // Decided from the expression's text, by a literal `flow_env.KEY` / `flow_env["KEY"]` + // access: a dynamic key (`flow_env[k]`) or a destructured `flow_env` is not detected. + fn reads_secret(&self, expr: &str) -> bool { + let ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$'; + self.entries.keys().any(|k| { + let dotted = [format!("flow_env.{k}"), format!("flow_env?.{k}")]; + let bracketed = ["\"", "'", "`"].map(|q| format!("[{q}{k}{q}]")); + dotted.iter().any(|p| { + expr.match_indices(p.as_str()).any(|(i, _)| { + !expr[..i].chars().next_back().is_some_and(ident) + && !expr[i + p.len()..].chars().next().is_some_and(ident) + }) + }) || bracketed.iter().any(|b| { + ["flow_env", "flow_env?."].iter().any(|o| { + expr.match_indices(&format!("{o}{b}")) + .any(|(i, _)| !expr[..i].chars().next_back().is_some_and(ident)) + }) + }) + }) + } +} + /// resumes should be in order of timestamp ascending, so that more recent are at the end #[instrument(level = "trace", skip_all)] async fn transform_input( flow_args: Marc>>, flow_env: Option<&HashMap>>, + env_refs: Option<&FlowEnvRefs<'_>>, + into_subflow: bool, last_result: Arc>, input_transforms: &HashMap, resumes: Arc>, @@ -2930,6 +3053,22 @@ async fn transform_input( mapped.insert(key.to_string(), to_raw_value(&value)); } InputTransform::Javascript { expr } => { + let env_refs = env_refs.filter(|_| expr.contains("flow_env")); + if let Some(r) = env_refs { + let exact_env = if into_subflow { + &r.secrets().await?.entries + } else { + r.raw + }; + if let Some(raw) = windmill_jseval::try_exact_property_access( + expr.trim(), + None, + Some(exact_env), + ) { + mapped.insert(key.to_string(), raw); + continue; + } + } let v = eval_timeout( expr.to_string(), env.clone(), @@ -2945,6 +3084,16 @@ async fn transform_input( "Error during isolated evaluation of expression `{expr}`:\n{e:#}" )) })?; + let secrets = match env_refs { + Some(r) => Some(r.secrets().await?), + None => None, + }; + let v = match secrets { + Some(s @ FlowEnvSecrets { crypt: Some(crypt), .. }) if s.reads_secret(expr) => { + to_raw_value(&format!("$encrypted:{}", encrypt(crypt, v.get()))) + } + _ => v, + }; mapped.insert(key.to_string(), v); } InputTransform::Ai => (), @@ -3043,6 +3192,8 @@ pub async fn handle_flow( } } + let env_refs = env_source.map(|raw| FlowEnvRefs::new(db, &flow_job, raw)); + let schedule_path = flow_job.schedule_path(); if !flow_job.is_flow_step() && status.retry.fail_count == 0 @@ -3186,6 +3337,7 @@ pub async fn handle_flow( status, flow, flow_env, + env_refs.as_ref(), no_flow_env, db, client, @@ -3475,6 +3627,7 @@ async fn push_next_flow_job( mut status: FlowStatus, flow: &FlowValue, flow_env: Option<&HashMap>>, + env_refs: Option<&FlowEnvRefs<'_>>, // Neither this flow nor any ancestor defines `flow_env`. no_flow_env: bool, db: &sqlx::Pool, @@ -4296,6 +4449,8 @@ async fn push_next_flow_job( transform_input( arc_flow_job_args.clone(), flow_env, + env_refs, + module.is_flow(), arc_last_job_result.clone(), input_transforms, resumes.clone(), @@ -4539,6 +4694,9 @@ async fn push_next_flow_job( let ti = transform_input( args, flow_env, + env_refs, + // A `flow` module is never a simple loop body. + false, arc_last_job_result.clone(), input_transforms, resumes.clone(), @@ -4594,6 +4752,8 @@ async fn push_next_flow_job( let ti = transform_input( Marc::new(hm), flow_env, + env_refs, + false, arc_last_job_result.clone(), input_transforms, resumes.clone(), @@ -6713,7 +6873,40 @@ pub async fn get_previous_job_result( mod tests { use super::{ effective_flow_step_timeout, extract_chat_message_from_flow_result, is_simple_modules, + FlowEnvSecrets, }; + + // An input computed from a secret is stored encrypted, which an agent worker cannot + // decrypt, so a key that merely shares a secret entry's name must not count as reading it. + #[test] + fn reads_secret_only_through_a_flow_env_access() { + let refs = FlowEnvSecrets { + entries: [( + "token".to_string(), + to_raw_value(&json!("$var:u/x/t")).unwrap(), + )] + .into(), + crypt: None, + }; + for expr in [ + "flow_env.token", + "\"Bearer \" + flow_env.token", + "`${flow_env?.token}`", + "flow_env[\"token\"] + 'x'", + "flow_env['token']", + ] { + assert!(refs.reads_secret(expr), "{expr}"); + } + for expr in [ + "flow_env.BASE + results.login.token", + "flow_env.tokens", + "flow_input.token", + "my_flow_env.token", + "flow_env[\"tokens\"]", + ] { + assert!(!refs.reads_secret(expr), "{expr}"); + } + } use serde_json::{json, value::to_raw_value}; use windmill_common::flows::FlowModule; diff --git a/benchmarks/lib.ts b/benchmarks/lib.ts index 62b739336e..553528fb66 100644 --- a/benchmarks/lib.ts +++ b/benchmarks/lib.ts @@ -2,7 +2,7 @@ import { sleep } from "https://deno.land/x/sleep@v1.2.1/mod.ts"; import * as windmill from "https://deno.land/x/windmill@v1.174.0/mod.ts"; import * as api from "https://deno.land/x/windmill@v1.174.0/windmill-api/index.ts"; -export const VERSION = "v1.854.2"; +export const VERSION = "v1.856.0"; export async function login(email: string, password: string): Promise { return await windmill.UserService.login({ diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index a7426f35a5..792b6b3144 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/chat-sdk", - "version": "1.854.2", + "version": "1.856.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/chat-sdk", - "version": "1.854.2", + "version": "1.856.0", "license": "Apache-2.0", "devDependencies": { "@ai-sdk/react": "^4.0.102", diff --git a/chat-sdk/package.json b/chat-sdk/package.json index 5cde3b92a5..fdf26bc3a0 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.854.2", + "version": "1.856.0", "author": "Ruben Fiszel", "license": "Apache-2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/chat-sdk#readme", diff --git a/cli/src/commands/user/user.ts b/cli/src/commands/user/user.ts index 99bea072a8..946d943371 100644 --- a/cli/src/commands/user/user.ts +++ b/cli/src/commands/user/user.ts @@ -155,6 +155,7 @@ async function createToken( } interface SimplifiedUser { + /** `admin`, or the name of one of the workspace's roles (`developer`, `operator` or a custom role). */ role: string; username: string; disabled: boolean; @@ -170,9 +171,13 @@ export async function pushWorkspaceUser( log.debug(`Processing local user ${email}`); - if (!["operator", "developer", "admin"].includes(localUser.role)) { + if (typeof localUser.role !== "string" || localUser.role.trim() === "") { throw new Error(`Invalid role for user ${email}: ${localUser.role}`); } + // Admin is a flag on top of the role; any other value names a workspace role, which the + // server checks exists in the workspace. + const isAdmin = localUser.role === "admin"; + const role = isAdmin ? undefined : localUser.role; try { const remoteUser = await wmill.getUser({ @@ -182,9 +187,8 @@ export async function pushWorkspaceUser( user = { role: remoteUser.is_admin ? "admin" - : remoteUser.operator - ? "operator" - : "developer", + : remoteUser.role ?? + (remoteUser.operator ? "operator" : "developer"), username: remoteUser.username, disabled: remoteUser.disabled, }; @@ -209,8 +213,8 @@ export async function pushWorkspaceUser( workspace: workspace, username: localUser.username, requestBody: { - is_admin: localUser.role === "admin", - operator: localUser.role === "operator", + is_admin: isAdmin, + role, disabled: localUser.disabled, }, }); @@ -229,8 +233,8 @@ export async function pushWorkspaceUser( workspace: workspace, requestBody: { email: email, - is_admin: localUser.role === "admin", - operator: localUser.role === "operator", + is_admin: isAdmin, + role, username: !automatedUsernameCreation ? localUser.username : undefined, }, }); diff --git a/cli/src/commands/variable/variable.ts b/cli/src/commands/variable/variable.ts index e9c3183ea9..803a6031bf 100644 --- a/cli/src/commands/variable/variable.ts +++ b/cli/src/commands/variable/variable.ts @@ -111,15 +111,17 @@ export interface VariableFile { * ciphertext (AES-256-GCM or legacy AES-256-CBC, base64) is standard base64 * decoding to a non-zero * multiple of the 16-byte block size. External secret-backend markers - * ($vault:/$aws_sm:/$azure_kv:/$http_store:) are stored verbatim too, so they - * count as already-encrypted. This is a shape check only — it never decrypts. + * ($vault:/$aws_sm:/$azure_kv:/$http_store:) and `$external:` references to a secret in + * an external store are stored verbatim too, so they count as already-encrypted. + * This is a shape check only — it never decrypts. */ export function looksLikeWorkspaceCiphertext(value: string): boolean { if ( value.startsWith("$vault:") || value.startsWith("$aws_sm:") || value.startsWith("$azure_kv:") || - value.startsWith("$http_store:") + value.startsWith("$http_store:") || + value.startsWith("$external:") ) { return true; } diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index 380ab7633d..cf156b164b 100644 --- a/cli/src/core/constants.ts +++ b/cli/src/core/constants.ts @@ -10,4 +10,4 @@ export const WM_FORK_PREFIX = "wm-fork"; // (e.g. utils.ts) can read it without importing main.ts and creating a circular // dependency (main → workspace → utils → main) that triggers a TDZ. // Re-exported from main.ts for backwards compatibility. -export const VERSION = "1.854.2"; +export const VERSION = "1.856.0"; diff --git a/cli/src/core/settings.ts b/cli/src/core/settings.ts index 9891440dd4..d9bffcb66b 100644 --- a/cli/src/core/settings.ts +++ b/cli/src/core/settings.ts @@ -61,6 +61,7 @@ export interface SimplifiedSettings { mute_critical_alerts?: boolean; color?: string; operator_settings?: any; + role_overrides?: any; datatable?: any; slack_team_id?: string; slack_name?: string; @@ -93,6 +94,7 @@ export const SETTINGS_MANAGED_ONLY_WHEN_PRESENT = [ "error_handler_fallback_to_instance_alerts", "add_admins_and_developers_to_forks", "variable_expiration_handler", + "role_overrides", ] as const; /** Keys earlier versions wrote that no longer configure anything; the server ignores them, diff --git a/cli/test/variable_ciphertext_shape_unit.test.ts b/cli/test/variable_ciphertext_shape_unit.test.ts index 0113929164..a05d4d225d 100644 --- a/cli/test/variable_ciphertext_shape_unit.test.ts +++ b/cli/test/variable_ciphertext_shape_unit.test.ts @@ -19,6 +19,7 @@ test("treats workspace-ciphertext-shaped values as already-encrypted", () => { "$vault:f/x/cfg", "$aws_sm:f/x/cfg", "$azure_kv:f/x/cfg", + "$external:vault://secret/team/app#token", ]; for (const value of ciphertextShaped) { expect(looksLikeWorkspaceCiphertext(value)).toBe(true); diff --git a/cli/windmill-utils-internal/src/deploy.ts b/cli/windmill-utils-internal/src/deploy.ts index 3478fa8b0b..77d093f74f 100644 --- a/cli/windmill-utils-internal/src/deploy.ts +++ b/cli/windmill-utils-internal/src/deploy.ts @@ -602,11 +602,19 @@ export async function deployItem( } } } else if (kind === "variable") { - const variable = await provider.getVariable({ + // An external secret reference is copied as the reference, never as the value it resolves to. + let variable = await provider.getVariable({ workspace: workspaceFrom, path, - decryptSecret: true, + decryptSecret: false, }); + if (variable.is_secret && !variable.value?.startsWith("$external:")) { + variable = await provider.getVariable({ + workspace: workspaceFrom, + path, + decryptSecret: true, + }); + } if (alreadyExists) { await provider.updateVariable({ workspace: workspaceTo, diff --git a/docs/auth-surface.md b/docs/auth-surface.md index 3bcd90b571..3044f9c3cd 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -153,6 +153,24 @@ Symbols, not line numbers, are cited: they drift less. "true"/"false" strings) and is only consulted for the claim above; only GitHub is filtered to `primary && verified`; a missing email is fabricated from `name` as `@windmill.dev` and reaches `login_externally` with `email_asserted = false`. +- **MCP access tokens from an external issuer** (`mcp_external_idp`, EE, `mcp/external_idp.rs`): + taken only for a JWT whose unverified `iss` is the configured issuer, then verified against its + discovery JWKS. With no audience configured, only a token typed as an access token (`at+jwt` + header, or a `Bearer` `typ` claim) is taken, so a client's ID token cannot stand in for one; + an instance-deactivated account (`password.disabled`) is refused, since this path has no + Windmill token for deactivation to revoke. The token's client claim (`azp` by default) must name a configured client, and + its email claim an existing, enabled member of that client's workspace: no account is created, + and a client-credentials token (no user) is refused with 403. When `sso_groups_claim` is set, + the instance groups with an `external_id` come from that claim of the token alone, for that + request only (nested paths counting for their ancestors): nothing is written, unlike an SSO + login, and an absent claim means no IdP groups, so removing a user from every group revokes at + the next token. Roles (admin, superadmin, operator) are not derived from the token: they stay as + stored, which SCIM and SSO login keep current. Entra's overage pointer (`_claim_names`) is refused rather than read as no + groups. The resolved identity is cached per token for at most a minute. Runs + record the client in `job_perms.mcp_client` (and the job-start audit entry), from the pushing identity + rather than `job_authed`, so a run on behalf of another identity still names it; the + session toolset reaches the API through a JWT minted for the caller, which carries the client + in its `mcp_client` claim for the same reason, and so does a job's `WM_TOKEN`. - **`GET /api/oauth/login/{client}`** is an unauthenticated 302 to the provider — a plain link from any page starts SSO. - **`CLOUD_HOSTED`** is presence-tested (`windmill-common/src/worker.rs`): `CLOUD_HOSTED=false` diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 0adbcef7d0..b95d3aa04e 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.854.2", + "version": "1.856.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.854.2", + "version": "1.856.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { diff --git a/frontend/package.json b/frontend/package.json index 3f8c3378dc..906cbde9d7 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.854.2", + "version": "1.856.0", "scripts": { "dev": "vite dev", "dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev", diff --git a/frontend/src/lib/components/CompareWorkspaces.svelte b/frontend/src/lib/components/CompareWorkspaces.svelte index 06b691679c..4ce7fb1504 100644 --- a/frontend/src/lib/components/CompareWorkspaces.svelte +++ b/frontend/src/lib/components/CompareWorkspaces.svelte @@ -17,6 +17,7 @@ UserPlus } from 'lucide-svelte' import { onDestroy, untrack } from 'svelte' + import { isExternalRef } from '$lib/externalSecretRef' import type { CiTestResult } from '$lib/gen' import { Alert, Badge } from './common' import { @@ -285,7 +286,11 @@ } }) } else { - const v = await VariableService.getVariable({ workspace: from, path, decryptSecret: true }) + // An external secret reference is copied as the reference, never as its resolved value. + let v = await VariableService.getVariable({ workspace: from, path, decryptSecret: false }) + if (v.is_secret && !isExternalRef(v.value)) { + v = await VariableService.getVariable({ workspace: from, path, decryptSecret: true }) + } await VariableService.createVariable({ workspace: to, requestBody: { diff --git a/frontend/src/lib/components/InstanceSetting.svelte b/frontend/src/lib/components/InstanceSetting.svelte index 485d558f24..92e31bcf31 100644 --- a/frontend/src/lib/components/InstanceSetting.svelte +++ b/frontend/src/lib/components/InstanceSetting.svelte @@ -22,9 +22,11 @@ import CriticalAlertChannels from './instanceSettings/CriticalAlertChannels.svelte' import RetentionPeriodOverrides from './instanceSettings/RetentionPeriodOverrides.svelte' import AgentWorkloadIdentityIssuers from './instanceSettings/AgentWorkloadIdentityIssuers.svelte' + import McpExternalIdp from './instanceSettings/McpExternalIdp.svelte' import WorkspaceRolesSetting from './instanceSettings/WorkspaceRolesSetting.svelte' import SmtpSettings from './instanceSettings/SmtpSettings.svelte' import SecretBackendConfig from './instanceSettings/SecretBackendConfig.svelte' + import ExternalSecretsConfig from './instanceSettings/ExternalSecretsConfig.svelte' import ExternalInstancePgSettings from './instanceSettings/ExternalInstancePgSettings.svelte' import InstancePgSettings from './instanceSettings/InstancePgSettings.svelte' import GhesAppSettings from './instanceSettings/GhesAppSettings.svelte' @@ -636,6 +638,8 @@ {:else if setting.fieldType == 'agent_workload_identity_issuers'} + {:else if setting.fieldType == 'mcp_external_idp'} + {:else if setting.fieldType == 'critical_error_channels'} {:else if setting.fieldType == 'otel'} @@ -876,6 +880,8 @@ {:else if setting.fieldType == 'secret_backend'} + {:else if setting.fieldType == 'external_secrets'} + {:else if setting.fieldType == 'external_instance_pg'} {#each settings[category] as setting} - {#if setting.fieldType != 'slack_connect' && !(quickSetup && setting.hideInQuickSetup) && !(quickSetup && category === 'Core' && setting.key === 'license_key')} + {#if setting.fieldType != 'slack_connect' && !(quickSetup && setting.hideInQuickSetup) && !(quickSetup && category === 'Core' && setting.key === 'license_key') && !(setting.key === 'mcp_external_idp' && authSubTab !== 'sso')} closeDrawer?.()} diff --git a/frontend/src/lib/components/VariableEditor.svelte b/frontend/src/lib/components/VariableEditor.svelte index a308237f5a..6095419f6c 100644 --- a/frontend/src/lib/components/VariableEditor.svelte +++ b/frontend/src/lib/components/VariableEditor.svelte @@ -31,6 +31,7 @@ import { setLocalDraftHint } from '$lib/localDraftHints.svelte' import { logFeatureUsage } from '$lib/utils/featureUsage' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { isExternalRef } from '$lib/externalSecretRef' const operatingWorkspace = useOperatingWorkspace() @@ -431,7 +432,8 @@ if (!isSecret || !selected || !existedInitially[selected]) return const s = states[selected]?.draft const ini = initialStates[selected] - if (!s || !ini?.variable.is_secret) return + // A reference was never loaded, and its baseline is what tells save() to replace it. + if (!s || !ini?.variable.is_secret || isExternalRef(ini.variable.value)) return if (s.variable.value !== '' && s.variable.value !== ini.variable.value) return s.variable.value = '' ini.variable.value = '' @@ -456,7 +458,13 @@ path: ini.path, requestBody: { path: ini.path != s.path ? s.path : undefined, - value: s.variable.value == '' ? undefined : s.variable.value, + // An empty value keeps the stored one, except when it replaces a + // reference: the reference is then dropped for the empty value. + value: + s.variable.value == '' && + !(isExternalRef(ini.variable.value) && !isExternalRef(s.variable.value)) + ? undefined + : s.variable.value, is_secret: ini.variable.is_secret != s.variable.is_secret ? s.variable.is_secret : undefined, description: @@ -599,6 +607,9 @@ deployedSecret={!!selected && !!existedInitially[selected] && !!initialStates[selected]?.variable.is_secret} + deployedRef={!!selected && + !!existedInitially[selected] && + isExternalRef(initialStates[selected]?.variable.value ?? '')} workspace={selected} actingUser={acting.in(selected) ?? null} oauthLinked={!!selected && !!oauthLinked[selected]} diff --git a/frontend/src/lib/components/VariableForm.svelte b/frontend/src/lib/components/VariableForm.svelte index 8bebd55953..cbf1bf4af0 100644 --- a/frontend/src/lib/components/VariableForm.svelte +++ b/frontend/src/lib/components/VariableForm.svelte @@ -17,6 +17,10 @@ import EncryptedDraftField from './EncryptedDraftField.svelte' import DateTimeInput from './DateTimeInput.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import TextInput from './text_input/TextInput.svelte' + import { formatVaultRef, isExternalRef, parseVaultRef } from '$lib/externalSecretRef' + import { VariableService } from '$lib/gen' + import { resource } from 'runed' const operatingWorkspace = useOperatingWorkspace() @@ -42,6 +46,8 @@ onSecretChange?: (isSecret: boolean) => void /** Whether the deployed variable being edited is secret. */ deployedSecret?: boolean + /** Whether the deployed variable being edited is an external reference. */ + deployedRef?: boolean /** Workspace the path is validated against; defaults to the nav workspace. */ workspace?: string | undefined /** The user acting in `workspace`, resolved by the editor above. `undefined` while @@ -67,6 +73,7 @@ onLoadSecret, onSecretChange, deployedSecret = false, + deployedRef = false, workspace = undefined, actingUser, oauthLinked = false @@ -96,11 +103,43 @@ let hasStagedValue = $derived(variable.value !== '') // Un-securing has to send the plaintext, and fetching it silently on the toggle would - // reveal the secret without the explicit, audited "Load secret value" action. - let unsecureNeedsLoad = $derived(edit && deployedSecret && variable.is_secret && !hasStagedValue) + // reveal the secret without the explicit, audited "Load secret value" action. A saved + // reference holds no value to load: whatever is typed, even nothing, replaces it. + let unsecureNeedsLoad = $derived( + edit && deployedSecret && !deployedRef && variable.is_secret && !hasStagedValue + ) + + // The API refuses anyone else creating, repointing or removing a reference. + let canEditRef = $derived(can_write && !!actingUser?.is_admin) const MAX_VARIABLE_LENGTH = 10000 + let externalRef = $derived(variable.is_secret && isExternalRef(variable.value)) + let vaultRef = $derived(parseVaultRef(variable.value)) + let kind = $derived(externalRef ? 'ref' : variable.is_secret ? 'secret' : 'plain') + let secretLocked = $derived( + edit && (!actingUser || !caps.code || isEncryptedDraftValue(variable.value)) + ) + + function setKind(next: string | undefined) { + if (!next || next === kind) return + if (kind === 'ref') variable.value = '' + if (variable.is_secret !== (next !== 'plain')) { + variable.is_secret = next !== 'plain' + onSecretChange?.(variable.is_secret) + } + if (next === 'ref') variable.value = formatVaultRef('', '') + } + let allowedPrefixes = resource( + () => (canEditRef ? ws : undefined), + async (ws) => + ws ? await VariableService.listExternalSecretPrefixes({ workspace: ws }) : undefined + ) + let pathPlaceholder = $derived( + (allowedPrefixes.current?.[0]?.replace(/^vault:\/\//, '').replace(/\/*$/, '') ?? + 'secret/team') + '/app' + ) + let editorKind: 'plain' | 'json' | 'yaml' = $state('plain') let editor: any = $state(undefined) @@ -123,29 +162,66 @@ /> -
- Secret + Type
- onSecretChange?.(e.detail)} - bind:checked={variable.is_secret} - disabled={unsecureNeedsLoad || - (edit && (!actingUser || !caps.code || isEncryptedDraftValue(variable.value)))} - /> - {#if unsecureNeedsLoad && can_write && caps.code} - - Load the secret value or enter a new one to make it non-secret - - {/if} + + {#snippet children({ item })} + + + + {#if externalRef || (canEditRef && allowedPrefixes.current?.length)} + + {/if} + {/snippet} +
- {#if variable.is_secret} + {#if externalRef && can_write && !canEditRef} + + Only workspace admins can create or change a reference + + {/if} + {#if deployedRef && kind !== 'ref' && !hasStagedValue} + Enter a value to replace the Vault reference + {:else if unsecureNeedsLoad && can_write && caps.code} + + Load the secret value or enter a new one to make it non-secret + + {/if} + {#if externalRef} + + Only the reference is stored in Windmill. The value is read from HashiCorp Vault each time the + variable is read, and every read generates an audit log whose operation name is: + variables.decrypt_secret + + {:else if variable.is_secret} Every secret is encrypted at rest and in transit with a key specific to this workspace. In addition, any read of a secret variable generates an audit log whose operation name is: @@ -163,96 +239,142 @@ stretch the hit area over the whole row and the alert. The toggle carries its na {/if} -
-