Merge origin/main into access-view-read-only

This commit is contained in:
Guilhem Lemouel
2026-11-02 01:36:48 -08:00
156 changed files with 5999 additions and 677 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "1.854.2"
".": "1.856.0"
}
+1 -1
View File
@@ -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 `<!-- cli-only -->` / `<!-- chat-only -->` 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<N>` 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<N>` 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.
+42
View File
@@ -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)
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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<HashMap<String, Box<RawValue>>>\",\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<Box<RawValue>>\",\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<HashMap<String, Box<RawValue>>>\",\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<Box<RawValue>>\",\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"
}
@@ -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"
}
@@ -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"
}
@@ -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<HashMap<String, Box<RawValue>>>\",\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<Box<RawValue>>\",\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<HashMap<String, Box<RawValue>>>\",\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<Box<RawValue>>\",\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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
@@ -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"
}
+295 -155
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -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 <ruben@windmill.dev>"]
edition = "2021"
+1 -1
View File
@@ -1 +1 @@
e183143e1172a780e06c43f4c4d15c42deb8990d
303e60fa90f55b08fa04d5c71319c96392f3fc6c
@@ -0,0 +1 @@
ALTER TABLE job_perms DROP COLUMN IF EXISTS mcp_client;
@@ -0,0 +1 @@
ALTER TABLE job_perms ADD COLUMN IF NOT EXISTS mcp_client VARCHAR(255);
+24 -24
View File
@@ -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",
@@ -12,7 +12,7 @@ resolver = "2"
members = ["."]
[workspace.package]
version = "1.854.2"
version = "1.856.0"
edition = "2021"
authors = ["Ruben Fiszel <ruben@windmill.dev>"]
+3
View File
@@ -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;
}
+30
View File
@@ -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<serde_json::Value>) {
};
}
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<serde_json::Value>) {
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),
+1
View File
@@ -359,6 +359,7 @@ async fn test_job_token_run_keeps_end_user_email(db: Pool<Postgres>) -> anyhow::
folders: vec![],
scopes: None,
token_prefix: None,
mcp_client: None,
},
"test-workspace",
3600,
+1
View File
@@ -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,
+1
View File
@@ -26,6 +26,7 @@ fn scoped_authed(scopes: Vec<&str>) -> ApiAuthed {
read_only: false,
job_id: None,
credential_expiry: None,
mcp_client: None,
}
}
+1
View File
@@ -90,6 +90,7 @@ fn trigger_authed() -> windmill_api_auth::ApiAuthed {
read_only: false,
job_id: None,
credential_expiry: None,
mcp_client: None,
}
}
@@ -179,6 +179,7 @@ fn make_authed() -> windmill_api_auth::ApiAuthed {
read_only: false,
job_id: None,
credential_expiry: None,
mcp_client: None,
}
}
+2
View File
@@ -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,
}
}
@@ -36,6 +36,7 @@ fn outsider() -> ApiAuthed {
read_only: false,
job_id: None,
credential_expiry: None,
mcp_client: None,
}
}
+10
View File
@@ -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,
}
}
+6
View File
@@ -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<chrono::DateTime<chrono::Utc>>,
/// 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<String>,
}
impl ApiAuthed {
@@ -157,6 +160,7 @@ impl From<ApiAuthed> for Authed {
folders: value.folders,
scopes: value.scopes,
token_prefix: value.token_prefix,
mcp_client: value.mcp_client,
}
}
}
@@ -178,6 +182,7 @@ impl From<Authed> 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(
+13
View File
@@ -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::<Vec<_>>();
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()];
@@ -68,6 +68,8 @@ pub enum ConversationKind {
pub struct ListConversationsQuery {
pub flow_path: Option<String>,
pub kind: Option<ConversationKind>,
/// Only the caller's own chats: an admin otherwise lists every user's.
pub mine: Option<bool>,
}
#[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");
@@ -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<Postgres>) -> 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(())
}
@@ -67,6 +67,7 @@ fn test_authed() -> ApiAuthed {
read_only: false,
job_id: None,
credential_expiry: None,
mcp_client: None,
}
}
@@ -105,6 +105,7 @@ async fn test_preview_on_behalf_of(db: Pool<Postgres>) -> anyhow::Result<()> {
folders: vec![],
scopes: None,
token_prefix: None,
mcp_client: None,
},
"test-workspace",
3600,
+2 -2
View File
@@ -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 {
+4
View File
@@ -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| {
+19 -5
View File
@@ -772,7 +772,8 @@ async fn whoami(
authed: ApiAuthed,
) -> JsonResult<UserInfo> {
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,
@@ -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,
)
@@ -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<String>,
Extension(db): Extension<DB>,
@@ -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, `{ "<role>": { 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?;
+42 -5
View File
@@ -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
@@ -30018,14 +30041,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 `<mount>/data/<prefix>/<workspace>/<secret>`, allowing a Vault policy scoped to exactly `<mount>/data/<prefix>/*`.
@@ -30035,6 +30057,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=<mount> 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)
@@ -32361,6 +32389,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:
@@ -32910,7 +32941,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://<path>#<key>`
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
`#<key>` 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
@@ -32959,7 +32996,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://<path>[#<key>]` reference for a secret, as in CreateVariable.
is_secret:
type: boolean
description: Whether the variable is a secret
+1 -1
View File
@@ -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 {
+7 -6
View File
@@ -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,
}
}
+6
View File
@@ -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::<ApiAuthed>())
.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::<ApiAuthed>())
.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::<ApiAuthed>())
.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(
+16 -1
View File
@@ -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}\""
)
}
@@ -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<Arc<McpExternalIdp>> {
#[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<Option<Jwks>> = tokio::sync::RwLock::new(None);
static ref RESOLVED: quick_cache::sync::Cache<String, Resolved> =
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<String> {
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::<Value>(&bytes)
.ok()?
.get("iss")?
.as_str()
.map(str::to_string)
}
async fn fetch_jwks(issuer: &str) -> anyhow::Result<JwkSet> {
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>| {
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::<Value>(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<String>,
email: Option<String>,
workspace_id: Option<String>,
reason: String,
}
fn claim_str(claims: &Value, name: &str) -> Option<String> {
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<bool> =
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<String> = 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<Option<Vec<String>>, 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<String> = 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<Option<Vec<String>>, 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<DB>,
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::<WorkspaceId>()
.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
}
+1
View File
@@ -5,6 +5,7 @@
mod auto_generated_endpoints;
mod core;
pub mod external_idp;
mod session;
mod utils;
+14 -2
View File
@@ -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()]),
}
}
+1
View File
@@ -1489,6 +1489,7 @@ mod tests {
read_only: false,
job_id,
credential_expiry: None,
mcp_client: None,
}
}
@@ -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<Value> {
let rows = sqlx::query_as::<_, (String, i32, Vec<String>, Vec<String>, 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<Value>, bool); 31] = [
let entries: [(&str, Option<Value>, 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");
@@ -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<UpdateSharedUi>,
) -> Result<String> {
require_admin(authed.is_admin, &authed.username)?;
// The route layer matches `apps:write:<paths>` 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}")))?;
+15 -11
View File
@@ -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<String>)>(
"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"]))
+14 -1
View File
@@ -324,6 +324,10 @@ pub struct JWTAuthClaims {
pub job_id: Option<String>,
pub scopes: Option<Vec<String>>,
pub audit_span: Option<String>,
/// [`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<String>,
}
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<String>,
}
impl From<JobPerms> for Authed {
@@ -387,6 +394,7 @@ impl From<JobPerms> 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(
+2
View File
@@ -20,6 +20,8 @@ pub struct Authed {
pub folders: Vec<(String, bool, bool)>,
pub scopes: Option<Vec<String>>,
pub token_prefix: Option<String>,
/// See `ApiAuthed::mcp_client`.
pub mcp_client: Option<String>,
}
impl Authed {
@@ -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<McpExternalIdp> =
arc_swap::ArcSwapOption::empty();
/// Empty means unset. See [`API_BASE_URL_SETTING`].
pub static ref API_BASE_URL: arc_swap::ArcSwap<String> =
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<String>,
#[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<McpExternalClient>,
}
#[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<String>,
}
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<Option<McpExternalIdp>, 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<bool, String> {
// 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<String> = 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,
@@ -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)
+11 -14
View File
@@ -290,7 +290,7 @@ pub enum ScopeDomain {
Configs,
OAuth,
AI,
AiEvals, // AI agent eval datasets
AiEvals, // AI agent eval datasets
SlackAgents, // AI agents answering in Slack channels
Indexer,
@@ -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),
@@ -611,9 +613,7 @@ pub fn intersect_job_token_scopes(
let (pc, po) = (parse(c), parse(o));
let mut out: Vec<String> = vec![];
let mut keep_covered =
|raw: &[String],
parsed: &[Option<ScopeDefinition>],
by: &[Option<ScopeDefinition>]| {
|raw: &[String], parsed: &[Option<ScopeDefinition>], by: &[Option<ScopeDefinition>]| {
for (s, p) in raw.iter().zip(parsed) {
let Some(p) = p else { continue };
if by.iter().flatten().any(|b| scope_contains(b, p))
@@ -697,17 +697,14 @@ mod job_token_scopes_tests {
fn intersect_never_widens() {
assert_eq!(intersect_job_token_scopes(None, None), None);
let oidc = v(&["oidc:write"]);
assert_eq!(
intersect_job_token_scopes(Some(&oidc), None),
Some(oidc.clone())
);
assert_eq!(
intersect_job_token_scopes(None, Some(&oidc)),
Some(oidc.clone())
);
assert_eq!(intersect_job_token_scopes(Some(&oidc), None), Some(oidc.clone()));
assert_eq!(intersect_job_token_scopes(None, Some(&oidc)), Some(oidc.clone()));
// A child setting asking for more than its parent holds gets only the common part.
assert_eq!(
intersect_job_token_scopes(Some(&oidc), Some(&v(&["oidc:write", "variables:read"]))),
intersect_job_token_scopes(
Some(&oidc),
Some(&v(&["oidc:write", "variables:read"]))
),
Some(oidc.clone())
);
// Narrower entries win from either side.
@@ -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:<scheme>://<path>#<key>` 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 `<path>`
//! 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<VaultSettings>,
#[serde(default)]
pub allowed: Vec<ExternalSecretAllowedPrefix>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ExternalSecretAllowedPrefix {
/// `<scheme>://<path prefix>`, the path matched on whole segments.
pub prefix: String,
/// Workspaces that may reference under `prefix`; empty means all.
#[serde(default)]
pub workspaces: Vec<String>,
}
#[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<Self> {
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<String>,
}
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<Vec<&str>> {
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 `<scheme>://<path>[#<key>]`, e.g. `vault://secret/team/app#token`"
))
})?;
Ok((ExternalSecretBackend::from_scheme(scheme)?, rest))
}
/// Parses `$external:<scheme>://<path>[#<key>]` (the marker is optional).
pub fn parse_external_ref(value: &str) -> Result<ExternalSecretRef> {
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<Vec<String>> {
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<ExternalSecretsSettings> {
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<VaultSettings>, 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<String> {
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::<Vec<_>>(),
}))
.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::<VaultSettings>(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"));
}
}
@@ -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<String>,
/// 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<String>,
/// Mount path of the AppRole auth method (defaults to "approle").
#[serde(skip_serializing_if = "Option::is_none")]
pub approle_mount_path: Option<String>,
/// Vault Enterprise namespace (optional)
#[serde(skip_serializing_if = "Option::is_none")]
pub namespace: Option<String>,
@@ -298,6 +298,9 @@ pub async fn get_secret_value(
path: &str,
encrypted_value: &str,
) -> Result<String> {
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() {
@@ -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,
@@ -129,3 +129,15 @@ pub async fn generate_vault_jwt(_db: &DB, _vault_address: &str) -> Result<String
"HashiCorp Vault integration requires Enterprise Edition".to_string(),
))
}
/// Read `key` of the secret at `path`, or all of it, for an `$external:vault://` reference (OSS stub)
pub async fn read_vault_external_secret(
_db: &DB,
_settings: &VaultSettings,
_path: &str,
_key: Option<&str>,
) -> Result<String> {
Err(Error::internal_err(
"HashiCorp Vault integration requires Enterprise Edition".to_string(),
))
}
@@ -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<Item = &str> {
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<String> {
fn walk(v: serde_json::Value, out: &mut Vec<String>) {
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);
}
}
+5 -5
View File
@@ -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<String> {
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<T: Authable + Sync>(
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?;
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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?;
@@ -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,
@@ -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,
@@ -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
// ─────────────────────────────────────────────────────────────────
+42 -16
View File
@@ -637,16 +637,22 @@ impl<B: McpBackend> ServerHandler for Runner<B> {
// 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<B: McpBackend> Runner<B> {
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
+7 -2
View File
@@ -374,7 +374,7 @@ impl<B: McpBackend> ServerHandler for SessionRunner<B> {
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<B: McpBackend> ServerHandler for SessionRunner<B> {
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()));
+19 -6
View File
@@ -3858,6 +3858,9 @@ pub struct MiniPulledJob {
/// unrestricted token.
#[serde(default)]
pub job_token_scopes: Option<Vec<String>>,
/// `job_perms.mcp_client`, read only on pull: see `ApiAuthed::mcp_client`.
#[serde(default)]
pub mcp_client: Option<String>,
}
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
@@ -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 {
@@ -65,6 +65,7 @@ mod schedule_push {
folders: vec![],
scopes: None,
token_prefix: None,
mcp_client: None,
}
}
@@ -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
+148 -59
View File
@@ -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<String> {
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<DB>,
@@ -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<NewOAuthAccount>,
) -> Result<Option<i32>> {
@@ -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<DB>,
Path(w_id): Path<String>,
) -> JsonResult<Vec<String>> {
require_admin(authed.is_admin, &authed.username)?;
Ok(Json(allowed_prefixes(&db, &w_id).await?))
}
async fn encrypt_value(
Extension(db): Extension<DB>,
Path(w_id): Path<String>,
@@ -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<String> = 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,
+17 -3
View File
@@ -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.<key>` 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,
}
}
+194 -1
View File
@@ -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<String, Box<RawValue>>,
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<FlowEnvSecrets>,
}
struct FlowEnvSecrets {
entries: HashMap<String, Box<RawValue>>,
// 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<WorkspaceCrypt>,
}
impl<'a> FlowEnvRefs<'a> {
fn new(db: &'a DB, flow_job: &MiniPulledJob, raw: &'a HashMap<String, Box<RawValue>>) -> 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<FlowEnvSecrets> {
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::<String>(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<String> = 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<String, Box<RawValue>> = 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<HashMap<String, Box<RawValue>>>,
flow_env: Option<&HashMap<String, Box<RawValue>>>,
env_refs: Option<&FlowEnvRefs<'_>>,
into_subflow: bool,
last_result: Arc<Box<RawValue>>,
input_transforms: &HashMap<String, InputTransform>,
resumes: Arc<Box<RawValue>>,
@@ -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<String, Box<RawValue>>>,
env_refs: Option<&FlowEnvRefs<'_>>,
// Neither this flow nor any ancestor defines `flow_env`.
no_flow_env: bool,
db: &sqlx::Pool<sqlx::Postgres>,
@@ -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;
+1 -1
View File
@@ -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<string> {
return await windmill.UserService.login({
+2 -2
View File
@@ -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",
+1 -1
View File
@@ -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",
+12 -8
View File
@@ -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,
},
});
+5 -3
View File
@@ -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;
}
+1 -1
View File
@@ -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";
+2
View File
@@ -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,
@@ -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);
+10 -2
View File
@@ -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,
+18
View File
@@ -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 `<name>@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`
+2 -2
View File
@@ -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": {
+1 -1
View File
@@ -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",
@@ -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: {
@@ -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 @@
</div>
{:else if setting.fieldType == 'agent_workload_identity_issuers'}
<AgentWorkloadIdentityIssuers {values} disabled={!$enterpriseLicense} />
{:else if setting.fieldType == 'mcp_external_idp'}
<McpExternalIdp {values} disabled={!$enterpriseLicense} />
{:else if setting.fieldType == 'critical_error_channels'}
<CriticalAlertChannels {values} {openSmtpSettings} {oauths} />
{:else if setting.fieldType == 'otel'}
@@ -876,6 +880,8 @@
<SmtpSettings {values} disabled={loading} />
{:else if setting.fieldType == 'secret_backend'}
<SecretBackendConfig {values} disabled={loading} />
{:else if setting.fieldType == 'external_secrets'}
<ExternalSecretsConfig {values} disabled={loading} />
{:else if setting.fieldType == 'external_instance_pg'}
<ExternalInstancePgSettings
{values}
@@ -764,7 +764,20 @@
custom_instance_pg_databases: ['user_pwd'],
external_instance_pg: ['password'],
rsa_keys: ['private_key'],
github_enterprise_app: ['private_key']
github_enterprise_app: ['private_key'],
external_secrets: ['vault.token']
}
// A field may name one nested level, `parent.child`.
function getField(obj: any, field: string): any {
const [a, b] = field.split('.')
return b === undefined ? obj?.[a] : obj?.[a]?.[b]
}
function setField(obj: any, field: string, value: any) {
const [a, b] = field.split('.')
if (b === undefined) obj[a] = value
else if (obj[a] && typeof obj[a] === 'object') obj[a] = { ...obj[a], [b]: value }
}
/** Returns SENSITIVE_UNCHANGED if the value is non-empty and matches the initial */
@@ -792,10 +805,10 @@
const init = initialValues?.[key]
for (const field of nestedSensitiveFields[key]) {
const m = maskField(
field === 'serviceAccountKey' ? JSON.stringify(cp[field]) : cp[field],
field === 'serviceAccountKey' ? JSON.stringify(init?.[field]) : init?.[field]
field === 'serviceAccountKey' ? JSON.stringify(cp[field]) : getField(cp, field),
field === 'serviceAccountKey' ? JSON.stringify(init?.[field]) : getField(init, field)
)
if (m) cp[field] = m
if (m) setField(cp, field, m)
}
masked[key] = cp
} else if (sensitiveKeys.has(key) && value != null && value !== '') {
@@ -898,8 +911,8 @@
if (parsed[parentKey] && typeof parsed[parentKey] === 'object') {
const init = initialValues?.[parentKey]
for (const field of fields) {
if (parsed[parentKey][field] === SENSITIVE_UNCHANGED) {
parsed[parentKey][field] = init?.[field]
if (getField(parsed[parentKey], field) === SENSITIVE_UNCHANGED) {
setField(parsed[parentKey], field, getField(init, field))
}
}
}
@@ -1261,7 +1274,7 @@
<div class="flex-col flex gap-6 pb-6">
{#each settings[category] as setting}
<!-- slack connect is handled with the alert channels settings, smtp_connect is handled in InstanceSetting -->
{#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')}
<InstanceSetting
{openSmtpSettings}
on:closeDrawer={() => closeDrawer?.()}
@@ -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]}
+227 -105
View File
@@ -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 @@
/>
<LabelsInput bind:labels />
</div>
<!-- No <label> for the heading: clicking it would flip the toggle, and a wrapping one would
stretch the hit area over the whole row and the alert. The toggle carries its name instead. -->
<div class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">Secret</span>
<span class="text-xs font-semibold text-emphasis">Type</span>
<div class="flex flex-row items-center gap-2">
<!-- An `$encrypted:` value is only redeemable while the variable stays secret — the
deploy endpoints decrypt the marker inside their `is_secret` branch and store it
verbatim otherwise — so un-securing one has to be unreachable until it is Reset. -->
<Toggle
ariaLabel="Secret"
class="w-fit"
on:change={(e) => onSecretChange?.(e.detail)}
bind:checked={variable.is_secret}
disabled={unsecureNeedsLoad ||
(edit && (!actingUser || !caps.code || isEncryptedDraftValue(variable.value)))}
/>
{#if unsecureNeedsLoad && can_write && caps.code}
<span class="text-2xs text-secondary">
Load the secret value or enter a new one to make it non-secret
</span>
{/if}
<ToggleButtonGroup selected={kind} onSelected={setKind}>
{#snippet children({ item })}
<ToggleButton
value="plain"
label="Non-secret"
{item}
disabled={kind === 'ref'
? !canEditRef
: kind === 'secret' && (secretLocked || unsecureNeedsLoad)}
/>
<ToggleButton
value="secret"
label="Secret"
{item}
disabled={kind === 'plain'
? secretLocked
: kind === 'ref' && (!canEditRef || isEncryptedDraftValue(variable.value))}
/>
<!-- Without an allowed prefix (the `external_secrets` setting unset, or naming no
prefix for this workspace) every reference is refused, so none can be created. -->
{#if externalRef || (canEditRef && allowedPrefixes.current?.length)}
<ToggleButton
value="ref"
label="Vault reference"
tooltip="Read the value from an existing secret in HashiCorp Vault"
{item}
disabled={kind !== 'ref' &&
(!canEditRef ||
isEncryptedDraftValue(variable.value) ||
(kind === 'plain' && secretLocked))}
/>
{/if}
{/snippet}
</ToggleButtonGroup>
</div>
{#if variable.is_secret}
{#if externalRef && can_write && !canEditRef}
<span class="text-xs text-secondary">
Only workspace admins can create or change a reference
</span>
{/if}
{#if deployedRef && kind !== 'ref' && !hasStagedValue}
<span class="text-xs text-secondary">Enter a value to replace the Vault reference</span>
{:else if unsecureNeedsLoad && can_write && caps.code}
<span class="text-xs text-secondary">
Load the secret value or enter a new one to make it non-secret
</span>
{/if}
{#if externalRef}
<Alert type="info" title="Read from Vault on each access">
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
</Alert>
{:else if variable.is_secret}
<Alert type="info" title="Audit log for each access">
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
</Label>
{/if}
<div class="flex flex-col gap-1">
<label for="variable-value" class="flex flex-row justify-left items-center">
<span class="text-xs font-semibold text-emphasis">Variable value&nbsp;</span>
{#if !isEncryptedDraftValue(variable.value)}
<span class="text-xs text-secondary font-normal">
({variable.value.length}/{MAX_VARIABLE_LENGTH} characters)
</span>
{/if}
{#if edit && variable.is_secret}
<div class="ml-3"></div>
{#if hasStagedValue}
<!-- Clearing the staged value is the only way back to loading the deployed one;
see `hasStagedValue`. An `$encrypted:` value additionally cannot be displayed. -->
<Button
size="xs"
variant="default"
startIcon={{ icon: RotateCcw }}
disabled={!can_write}
on:click={() => (variable.value = '')}
>
Reset
</Button>
{:else if !caps.code}
<div class="p-2 border">Your role cannot load secret values</div>
{:else}
<Button size="xs" variant="default" on:click={() => onLoadSecret?.()}>
Load secret value<Tooltip>Will generate an audit log</Tooltip>
</Button>
{#if externalRef}
<div class="flex flex-col gap-2">
<div class="flex flex-col gap-1">
<label for="external-ref-path" class="text-xs font-semibold text-emphasis">Vault path</label>
{#if allowedPrefixes.current?.length}
<span class="text-xs text-secondary">
Under <code
>{allowedPrefixes.current
.map((p) => p.replace(/^vault:\/\//, '').replace(/\/*$/, '/**'))
.join(', ')}</code
>
</span>
{:else if allowedPrefixes.current}
<Alert type="warning" size="xs" title="No Vault paths allowed for this workspace">
Ask a superadmin to allow one in the instance settings.
</Alert>
{/if}
{/if}
</label>
<div>
{#if isEncryptedDraftValue(variable.value)}
<!-- The draft's secret value was encrypted server-side and can't be
<TextInput
inputProps={{
id: 'external-ref-path',
placeholder: pathPlaceholder,
disabled: !canEditRef
}}
bind:value={
() => vaultRef.path, (v) => (variable.value = formatVaultRef(v ?? '', vaultRef.key))
}
/>
</div>
<div class="flex flex-col gap-1">
<label for="external-ref-key" class="text-xs font-semibold text-emphasis">
Key (optional)
</label>
<span class="text-xs text-secondary">
The entry to read from the secret, like <code>token</code>. Leave empty to get all its
entries as a JSON object.
</span>
<TextInput
inputProps={{ id: 'external-ref-key', placeholder: 'token', disabled: !canEditRef }}
bind:value={
() => vaultRef.key, (v) => (variable.value = formatVaultRef(vaultRef.path, v ?? ''))
}
/>
</div>
</div>
{:else}
<div class="flex flex-col gap-1">
<label for="variable-value" class="flex flex-row justify-left items-center">
<span class="text-xs font-semibold text-emphasis">Variable value&nbsp;</span>
{#if !isEncryptedDraftValue(variable.value)}
<span class="text-xs text-secondary font-normal">
({variable.value.length}/{MAX_VARIABLE_LENGTH} characters)
</span>
{/if}
{#if edit && variable.is_secret && !(deployedRef && !hasStagedValue)}
<div class="ml-3"></div>
{#if hasStagedValue}
<!-- Clearing the staged value is the only way back to loading the deployed one;
see `hasStagedValue`. An `$encrypted:` value additionally cannot be displayed. -->
<Button
size="xs"
variant="default"
startIcon={{ icon: RotateCcw }}
disabled={!can_write}
on:click={() => (variable.value = '')}
>
Reset
</Button>
{:else if !caps.code}
<div class="p-2 border">Your role cannot load secret values</div>
{:else}
<Button size="xs" variant="default" on:click={() => onLoadSecret?.()}>
Load secret value<Tooltip>Will generate an audit log</Tooltip>
</Button>
{/if}
{/if}
</label>
<div>
{#if isEncryptedDraftValue(variable.value)}
<!-- The draft's secret value was encrypted server-side and can't be
loaded back. Saving deploys the last saved value as-is; Reset clears
it so a new secret can be typed. -->
<EncryptedDraftField disabled={!can_write} onReset={() => (variable.value = '')} />
{:else}
<div class="flex flex-col gap-2">
<ToggleButtonGroup bind:selected={editorKind}>
{#snippet children({ item })}
<ToggleButton value="plain" label="Plain" {item} />
<ToggleButton value="json" label="Json" {item} />
<ToggleButton value="yaml" label="YAML" {item} />
{/snippet}
</ToggleButtonGroup>
{#if editorKind == 'plain'}
<textarea
disabled={!can_write}
rows="4"
use:autosize
bind:value={variable.value}
placeholder="Update variable value"
id="variable-value"
></textarea>
{:else if editorKind == 'json'}
<div class="border rounded mb-4 w-full">
{#await import('$lib/components/SimpleEditor.svelte')}
<Loader2 class="animate-spin" />
{:then Module}
<Module.default
bind:this={editor}
autoHeight
lang="json"
bind:code={variable.value}
fixedOverflowWidgets={false}
class="bg-surface-tertiary"
/>
{/await}
</div>
{:else if editorKind == 'yaml'}
<div class="border rounded mb-4 w-full">
{#await import('$lib/components/SimpleEditor.svelte')}
<Loader2 class="animate-spin" />
{:then Module}
<Module.default
bind:this={editor}
autoHeight
lang="yaml"
bind:code={variable.value}
fixedOverflowWidgets={false}
class="bg-surface-tertiary"
/>
{/await}
</div>
{/if}
</div>
{/if}
<EncryptedDraftField disabled={!can_write} onReset={() => (variable.value = '')} />
{:else}
<div class="flex flex-col gap-2">
<ToggleButtonGroup bind:selected={editorKind}>
{#snippet children({ item })}
<ToggleButton value="plain" label="Plain" {item} />
<ToggleButton value="json" label="Json" {item} />
<ToggleButton value="yaml" label="YAML" {item} />
{/snippet}
</ToggleButtonGroup>
{#if editorKind == 'plain'}
<textarea
disabled={!can_write}
rows="4"
use:autosize
bind:value={variable.value}
placeholder="Update variable value"
id="variable-value"
></textarea>
{:else if editorKind == 'json'}
<div class="border rounded mb-4 w-full">
{#await import('$lib/components/SimpleEditor.svelte')}
<Loader2 class="animate-spin" />
{:then Module}
<Module.default
bind:this={editor}
autoHeight
lang="json"
bind:code={variable.value}
fixedOverflowWidgets={false}
class="bg-surface-tertiary"
/>
{/await}
</div>
{:else if editorKind == 'yaml'}
<div class="border rounded mb-4 w-full">
{#await import('$lib/components/SimpleEditor.svelte')}
<Loader2 class="animate-spin" />
{:then Module}
<Module.default
bind:this={editor}
autoHeight
lang="yaml"
bind:code={variable.value}
fixedOverflowWidgets={false}
class="bg-surface-tertiary"
/>
{/await}
</div>
{/if}
</div>
{/if}
</div>
</div>
</div>
{/if}
<label class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">Description</span>
<textarea rows="4" use:autosize bind:value={variable.description} placeholder="Used for X"
@@ -179,10 +179,11 @@
height as one replaces another. That needs a definite height from the caller.
`inert` and not just opacity: an off-screen page keeps its DOM, so without it the
tab order and every screen reader still walk through it. -->
<!-- `tabindex="-1"`: focusable programmatically, never a tab stop of its own. -->
<!-- `tabindex="-1"`: focusable programmatically, never a tab stop of its own, so no
focus ring: one around the whole page after a keyboard navigation marks nothing. -->
<div
tabindex="-1"
class="paged-content-page absolute inset-0 flex flex-col"
class="paged-content-page absolute inset-0 flex flex-col outline-none"
class:is-hidden={i !== index}
class:opacity-0={i !== index}
class:pointer-events-none={i !== index}

Some files were not shown because too many files have changed in this diff Show More