From 9c012b659e38fa512d5c22084fc0bf519407aafb Mon Sep 17 00:00:00 2001 From: AlexRV12 <71396855+AlexRV12@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:27:40 +0100 Subject: [PATCH] feat: let a role without code use the Hub scripts an admin allows --- ...8d16414daad90ad8b0ea35a769d78626039aa.json | 15 -- ...2efd37f0e83f38d65576ff9ba0a54e5305de6.json | 15 ++ ...cc0aa58df96928eed3c05c515476771538c3a.json | 15 -- ...3f46c168973498385765c2403e4e780ed6814.json | 15 ++ ...04f54f35feba001bb9ceafba62b22f6058c54.json | 15 ++ backend/ee-repo-ref.txt | 2 +- ...261123152952_workspace_hub_access.down.sql | 1 + ...20261123152952_workspace_hub_access.up.sql | 3 + backend/src/main.rs | 3 +- backend/tests/fixtures/hub_grant.sql | 11 + backend/tests/hub_composed_step.rs | 76 ++++++- backend/tests/hub_named_path.rs | 205 ++++++++++++++++- backend/tests/hub_saved_path.rs | 4 +- backend/tests/trigger_hub_target.rs | 2 +- backend/tests/workspace_handlers.rs | 4 +- backend/windmill-api-auth/src/composed.rs | 36 ++- backend/windmill-api-auth/src/lib.rs | 4 +- backend/windmill-api-settings/src/lib.rs | 10 +- backend/windmill-api-users/src/users.rs | 6 +- .../src/workspace_roles.rs | 81 ++++++- .../windmill-api-workspaces/src/workspaces.rs | 27 ++- .../src/workspaces_extra.rs | 2 +- backend/windmill-api/openapi.yaml | 58 ++++- .../ai_session_tools/gen/instructions.json | 2 +- backend/windmill-api/src/apps.rs | 8 +- .../src/workspace_settings_document.rs | 22 +- backend/windmill-common/src/db.rs | 6 +- .../windmill-common/src/global_settings.rs | 3 + .../windmill-common/src/instance_config.rs | 6 + backend/windmill-common/src/jobs.rs | 99 ++++++++- backend/windmill-common/src/roles.rs | 206 ++++++++++++++++-- backend/windmill-common/src/scripts.rs | 24 +- backend/windmill-common/src/utils.rs | 149 +++++++++++-- .../tests/workspace_roles_license.rs | 38 +++- backend/windmill-queue/tests/schedule_push.rs | 2 +- backend/windmill-test-utils/src/lib.rs | 41 ++++ cli/src/core/settings.ts | 2 + cli/src/guidance/skills.gen.ts | 3 +- docs/operator-builder-rights.md | 7 +- docs/operator-write-rights.md | 6 +- docs/workspace-roles.md | 31 +++ .../components/copilot/chat/global/core.ts | 2 +- .../flows/content/FlowInputsQuick.svelte | 3 +- .../flows/map/InsertModuleInner.svelte | 3 +- system_prompts/auto-generated/prompts.ts | 1 + .../skills/workspace-settings/SKILL.md | 3 +- system_prompts/base/workspace-settings.md | 3 +- 47 files changed, 1115 insertions(+), 165 deletions(-) delete mode 100644 backend/.sqlx/query-0d73210f3ce58d0dd8fd850c1df8d16414daad90ad8b0ea35a769d78626039aa.json create mode 100644 backend/.sqlx/query-17fca8d19f4e243eb7863efdb102efd37f0e83f38d65576ff9ba0a54e5305de6.json delete mode 100644 backend/.sqlx/query-4693a6932e0f09f8d0a929bde83cc0aa58df96928eed3c05c515476771538c3a.json create mode 100644 backend/.sqlx/query-c013762a78f431d4911132e44503f46c168973498385765c2403e4e780ed6814.json create mode 100644 backend/.sqlx/query-f850b4c4579708431792503e56204f54f35feba001bb9ceafba62b22f6058c54.json create mode 100644 backend/migrations/20261123152952_workspace_hub_access.down.sql create mode 100644 backend/migrations/20261123152952_workspace_hub_access.up.sql create mode 100644 backend/tests/fixtures/hub_grant.sql diff --git a/backend/.sqlx/query-0d73210f3ce58d0dd8fd850c1df8d16414daad90ad8b0ea35a769d78626039aa.json b/backend/.sqlx/query-0d73210f3ce58d0dd8fd850c1df8d16414daad90ad8b0ea35a769d78626039aa.json deleted file mode 100644 index 07a85d9004..0000000000 --- a/backend/.sqlx/query-0d73210f3ce58d0dd8fd850c1df8d16414daad90ad8b0ea35a769d78626039aa.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE workspace_settings SET role_overrides =\n (SELECT role_overrides FROM workspace_settings WHERE workspace_id = $2)\n WHERE workspace_id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Text" - ] - }, - "nullable": [] - }, - "hash": "0d73210f3ce58d0dd8fd850c1df8d16414daad90ad8b0ea35a769d78626039aa" -} diff --git a/backend/.sqlx/query-17fca8d19f4e243eb7863efdb102efd37f0e83f38d65576ff9ba0a54e5305de6.json b/backend/.sqlx/query-17fca8d19f4e243eb7863efdb102efd37f0e83f38d65576ff9ba0a54e5305de6.json new file mode 100644 index 0000000000..e78cce85bb --- /dev/null +++ b/backend/.sqlx/query-17fca8d19f4e243eb7863efdb102efd37f0e83f38d65576ff9ba0a54e5305de6.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET (role_overrides, hub_access) =\n (SELECT role_overrides, hub_access FROM workspace_settings WHERE workspace_id = $2)\n WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "17fca8d19f4e243eb7863efdb102efd37f0e83f38d65576ff9ba0a54e5305de6" +} diff --git a/backend/.sqlx/query-4693a6932e0f09f8d0a929bde83cc0aa58df96928eed3c05c515476771538c3a.json b/backend/.sqlx/query-4693a6932e0f09f8d0a929bde83cc0aa58df96928eed3c05c515476771538c3a.json deleted file mode 100644 index 96a0927e30..0000000000 --- a/backend/.sqlx/query-4693a6932e0f09f8d0a929bde83cc0aa58df96928eed3c05c515476771538c3a.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Text" - ] - }, - "nullable": [] - }, - "hash": "4693a6932e0f09f8d0a929bde83cc0aa58df96928eed3c05c515476771538c3a" -} diff --git a/backend/.sqlx/query-c013762a78f431d4911132e44503f46c168973498385765c2403e4e780ed6814.json b/backend/.sqlx/query-c013762a78f431d4911132e44503f46c168973498385765c2403e4e780ed6814.json new file mode 100644 index 0000000000..7a52ea3e2f --- /dev/null +++ b/backend/.sqlx/query-c013762a78f431d4911132e44503f46c168973498385765c2403e4e780ed6814.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, hub_access, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, hub_access, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "c013762a78f431d4911132e44503f46c168973498385765c2403e4e780ed6814" +} diff --git a/backend/.sqlx/query-f850b4c4579708431792503e56204f54f35feba001bb9ceafba62b22f6058c54.json b/backend/.sqlx/query-f850b4c4579708431792503e56204f54f35feba001bb9ceafba62b22f6058c54.json new file mode 100644 index 0000000000..8a78a240eb --- /dev/null +++ b/backend/.sqlx/query-f850b4c4579708431792503e56204f54f35feba001bb9ceafba62b22f6058c54.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET hub_access = $1 WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Jsonb", + "Text" + ] + }, + "nullable": [] + }, + "hash": "f850b4c4579708431792503e56204f54f35feba001bb9ceafba62b22f6058c54" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 74d6ecc82f..1e1ccc6288 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -c05fadda9d6bd772e56cec00d5b9c721afab4aed +7f6594fffc090a061e84ec3ed5bc5a52a45e6ca0 diff --git a/backend/migrations/20261123152952_workspace_hub_access.down.sql b/backend/migrations/20261123152952_workspace_hub_access.down.sql new file mode 100644 index 0000000000..44f1388157 --- /dev/null +++ b/backend/migrations/20261123152952_workspace_hub_access.down.sql @@ -0,0 +1 @@ +ALTER TABLE workspace_settings DROP COLUMN IF EXISTS hub_access; diff --git a/backend/migrations/20261123152952_workspace_hub_access.up.sql b/backend/migrations/20261123152952_workspace_hub_access.up.sql new file mode 100644 index 0000000000..f38cda1e92 --- /dev/null +++ b/backend/migrations/20261123152952_workspace_hub_access.up.sql @@ -0,0 +1,3 @@ +-- The workspace's own list of Hub integrations members without code may use, +-- `{"": "read" | "write"}`. NULL follows the instance's `hub_access` setting. +ALTER TABLE workspace_settings ADD COLUMN IF NOT EXISTS hub_access JSONB; diff --git a/backend/src/main.rs b/backend/src/main.rs index db5abf21d2..e989179607 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -2070,7 +2070,8 @@ async fn process_notify_event( DISABLE_PASSWORD_LOGIN_SETTING => { load_disable_password_login(db).await; } - windmill_common::global_settings::WORKSPACE_ROLES_SETTING => { + windmill_common::global_settings::WORKSPACE_ROLES_SETTING + | windmill_common::global_settings::HUB_ACCESS_SETTING => { windmill_common::roles::invalidate_all_roles_cache(); } MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING => { diff --git a/backend/tests/fixtures/hub_grant.sql b/backend/tests/fixtures/hub_grant.sql new file mode 100644 index 0000000000..666ef9f0e6 --- /dev/null +++ b/backend/tests/fixtures/hub_grant.sql @@ -0,0 +1,11 @@ +-- Workspace `hub-grant`, where `operator` composes flows and Slack's read-only Hub scripts are +-- allowed. Its own workspace: roles are cached per workspace id across a test binary's tests. +-- test-user is its admin, test-user-3 (SECRET_TOKEN_3) its operator. +INSERT INTO workspace (id, name, owner) VALUES ('hub-grant', 'hub-grant', 'test-user'); +INSERT INTO workspace_key (workspace_id, kind, key) VALUES ('hub-grant', 'cloud', 'test-key'); +INSERT INTO workspace_settings (workspace_id, role_overrides, hub_access) VALUES ('hub-grant', + '{"operator": {"capabilities": {"flows": "compose"}}}', '{"Slack": "read"}'); +INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES ('hub-grant', 'all', 'All users', '{}'); +INSERT INTO usr (workspace_id, email, username, is_admin, operator, role) VALUES + ('hub-grant', 'test@windmill.dev', 'test-user', true, false, 'Admin'), + ('hub-grant', 'test3@windmill.dev', 'test-user-3', false, true, 'Operator'); diff --git a/backend/tests/hub_composed_step.rs b/backend/tests/hub_composed_step.rs index 5943789597..9da2d2e65a 100644 --- a/backend/tests/hub_composed_step.rs +++ b/backend/tests/hub_composed_step.rs @@ -1,5 +1,5 @@ //! A builder choosing a Hub step in a flow, an agent or an app is held to the run-time rule for -//! naming a Hub path: refused without `code`, allowed with it. +//! naming a Hub path: refused without `code` or a grant, allowed with either. use reqwest::multipart; use serde_json::{json, Value}; @@ -9,7 +9,7 @@ use windmill_test_utils::*; const CODER: &str = "SECRET_TOKEN_2"; const OP: &str = "SECRET_TOKEN_3"; const HUB_PATH: &str = "hub/990000794/test/echo"; -const REFUSAL: &str = "Hub scripts and flows require a role that can write code"; +const REFUSAL: &str = "Your role may not use this Hub script"; fn flow(path: &str) -> Value { json!({"modules": [{"id": "a", "value": {"type": "script", "path": path, "input_transforms": {}}}]}) @@ -110,9 +110,7 @@ async fn a_hub_step_follows_the_code_capability(db: Pool) -> anyhow::R /// a personal one. Its own operator, so no other test has warmed the role cache for it; the /// overrides match the other test's, since the workspace's roles are cached across tests. #[sqlx::test(fixtures("base"))] -async fn a_hub_step_is_refused_on_a_one_connection_pool( - db: Pool, -) -> anyhow::Result<()> { +async fn a_hub_step_is_refused_on_a_one_connection_pool(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; sqlx::raw_sql( r#"UPDATE workspace_settings SET role_overrides = '{ @@ -179,3 +177,71 @@ async fn a_hub_step_is_refused_on_a_one_connection_pool( } Ok(()) } + +/// A save checks its Hub steps inside its transaction, so the Hub lookup must not need a second +/// connection: with the only one of the pool held, a granted step passes and a step the list does +/// not cover is refused with the reason. The Hub is asked once, whatever the steps. +#[sqlx::test(fixtures("base"))] +async fn the_hub_check_needs_no_second_connection(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let meta = |id: i32, read_only: bool| { + json!({ "version_id": id, "ask_id": 1, "app": "Slack", "read_only": read_only, + "script_approved": true, "version_ever_approved": true }) + }; + let (_, calls) = start_stub_hub(vec![ + meta(990000821, true), + meta(990000822, false), + meta(990000823, true), + ]) + .await; + let one = sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .acquire_timeout(std::time::Duration::from_secs(5)) + .connect_with((*db.connect_options()).clone()) + .await?; + let authed = windmill_api_auth::ApiAuthed { + email: "test3@windmill.dev".into(), + username: "test-user-3".into(), + is_operator: true, + capabilities: Some(windmill_common::roles::RoleCapabilities { + hub: serde_json::from_value(json!({"slack": "read"}))?, + ..windmill_common::roles::RoleCapabilities::OPERATOR + }), + ..Default::default() + }; + for (ids, refusal) in [ + ([990000821, 990000823], None), + ( + [990000821, 990000822], + Some("hub/990000822/slack/list: This Hub script can write"), + ), + ] { + let steps = ids + .iter() + .map(|id| { + windmill_common::runnable_ref::RunnableRef::from_path( + &format!("hub/{id}/slack/list"), + false, + ) + .unwrap() + }) + .collect::>(); + calls.store(0, std::sync::atomic::Ordering::SeqCst); + let tx = one.begin().await?; + let res = windmill_api_auth::composed::check_builder_can_name_hub( + &steps, + &authed, + &one, + "test-workspace", + ) + .await; + tx.rollback().await?; + match (res, refusal) { + (Ok(()), None) => {} + (Err(e), Some(text)) if e.to_string().contains(text) => {} + (res, _) => panic!("{ids:?}: {res:?}"), + } + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1); + } + Ok(()) +} diff --git a/backend/tests/hub_named_path.rs b/backend/tests/hub_named_path.rs index 0c432f83aa..df758b1a91 100644 --- a/backend/tests/hub_named_path.rs +++ b/backend/tests/hub_named_path.rs @@ -1,5 +1,5 @@ -//! A Hub path named at run time is refused to a member whose role cannot write code, on every -//! route that takes one. +//! A Hub path named at run time is refused to a member whose role does not write code, unless +//! the Hub access list allows that script, on every route that takes one. use serde_json::json; use sqlx::{Pool, Postgres}; @@ -12,8 +12,9 @@ use windmill_test_utils::*; const DEV: &str = "SECRET_TOKEN_2"; const OP: &str = "OPERATOR_TOKEN"; -const HUB_ID: i32 = 990000792; -const REFUSAL: &str = "Hub scripts and flows require a role that can write code"; +const HUB_ID: i32 = 9990792; +const REFUSAL: &str = "Your role may not use this Hub script"; +const FLOW_REFUSAL: &str = "Hub flows require a role that can write code"; #[sqlx::test(fixtures("base"))] async fn a_hub_path_named_without_code_is_refused(db: Pool) -> anyhow::Result<()> { @@ -135,8 +136,13 @@ async fn a_hub_path_named_without_code_is_refused(db: Pool) -> anyhow: async { for route in routes { let (status, body) = send(OP, route).await; + let reason = if route == "app component flow" { + FLOW_REFUSAL + } else { + REFUSAL + }; // Batch rerun reports every failure as the same "Couldn't re-run" line. - let refused = (status == 403 && body.contains(REFUSAL)) + let refused = (status == 403 && body.contains(reason)) || (route == "batch_rerun" && body.starts_with("Error: ")); assert!(refused, "op on {route}: {status} {body}"); @@ -210,3 +216,192 @@ async fn the_rule_reads_code_from_the_caller(db: Pool) -> anyhow::Resu check(op(Some(coder)), dead).await?; Ok(()) } + +const SLACK_READ: i32 = 990000801; +const SLACK_WRITE: i32 = 990000802; +const SLACK_SCRIPT_UNAPPROVED: i32 = 990000803; +const SLACK_VERSION_UNAPPROVED: i32 = 990000805; +const GITHUB: i32 = 990000804; + +fn meta( + version_id: i32, + app: &str, + read_only: bool, + script_approved: bool, + version_ever_approved: bool, +) -> serde_json::Value { + json!({ "version_id": version_id, "ask_id": 1, "app": app, "read_only": read_only, + "script_approved": script_approved, "version_ever_approved": version_ever_approved }) +} + +/// A role without code, where Slack is allowed at read, names Slack's approved read-only Hub scripts and +/// nothing else, each refusal saying why; a role with nothing allowed never asks the Hub. +#[sqlx::test(fixtures("base", "hub_grant"))] +async fn a_hub_grant_admits_approved_scripts_of_its_integration( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let (hub, calls) = start_stub_hub(vec![ + meta(SLACK_READ, "Slack", true, true, true), + meta(SLACK_WRITE, "slack", false, true, true), + meta(SLACK_SCRIPT_UNAPPROVED, "slack", true, false, true), + meta(SLACK_VERSION_UNAPPROVED, "slack", true, true, false), + meta(GITHUB, "github", true, true, true), + ]) + .await; + let server = ApiServer::start(db.clone()).await?; + let ws = format!("http://localhost:{}/api/w/hub-grant", server.addr.port()); + let client = reqwest::Client::new(); + + let resp = client + .post(format!("{ws}/jobs/run/p/hub/{SLACK_READ}/slack/list")) + .bearer_auth("SECRET_TOKEN_3") + .json(&json!({})) + .send() + .await?; + assert!(resp.status().is_success(), "{}", resp.text().await?); + + let caps = |hub: serde_json::Value| RoleCapabilities { + hub: serde_json::from_value(hub).unwrap(), + ..RoleCapabilities::OPERATOR + }; + let check = |caps: RoleCapabilities, id: i32| { + let db = db.clone(); + async move { + let authed = windmill_api_auth::ApiAuthed { + email: "test3@windmill.dev".into(), + username: "test-user-3".into(), + is_operator: true, + capabilities: Some(caps), + ..Default::default() + }; + let hub = RunnableRef::from_path(&format!("hub/{id}/slack/x"), false).unwrap(); + check_can_name_runnable( + &RunOrigin::NamedBy(authed.to_authed_ref()), + &hub, + &db, + "hub-grant", + ) + .await + .map_err(|e| e.to_string()) + } + }; + let slack_read = || caps(json!({"slack": "read"})); + for (id, reason) in [ + ( + SLACK_WRITE, + "can write to `slack` and your role may only use its read-only scripts", + ), + (SLACK_SCRIPT_UNAPPROVED, "is not approved on the Hub"), + (SLACK_VERSION_UNAPPROVED, "is not approved on the Hub"), + (GITHUB, "may not use the Hub scripts of `github`"), + (990000806, "is not on the Hub"), + ] { + let err = check(slack_read(), id).await.unwrap_err(); + assert!(err.contains(reason), "{id}: {err}"); + } + check(caps(json!({"slack": "write"})), SLACK_WRITE) + .await + .unwrap(); + + let before = calls.load(std::sync::atomic::Ordering::SeqCst); + let err = check(RoleCapabilities::OPERATOR, 990000809) + .await + .unwrap_err(); + assert!(err.contains(REFUSAL), "{err}"); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), before); + + // Another Hub's script of the same id, cached above, is not what this Hub's approval admits. + let (other_hub, _) = start_stub_hub(vec![]).await; + let script = windmill_common::scripts::get_full_hub_script_by_id( + SLACK_READ, + &windmill_common::utils::HTTP_CLIENT, + None, + ) + .await?; + assert_eq!(script.content, format!("echo {other_hub}")); + + for (url, id, reason) in [ + ( + "http://127.0.0.1:1".to_string(), + 990000810, + "the Hub is unreachable", + ), + ( + format!("{hub}/predates-access-meta"), + 990000811, + "needs an update", + ), + ] { + windmill_common::HUB_BASE_URL.store(std::sync::Arc::new(url)); + let err = check(slack_read(), id).await.unwrap_err(); + assert!(err.contains(reason), "{id}: {err}"); + } + + Ok(()) +} + +/// Only an admin writes the workspace's list. An empty one is not the instance's: it allows nothing. +/// Its own workspace: roles are cached per workspace id across the tests. +#[sqlx::test(fixtures("base"))] +async fn a_workspace_replaces_its_hub_access_list(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + "INSERT INTO workspace (id, name, owner) VALUES ('hub-list', 'hub-list', 'test-user'); + INSERT INTO workspace_key (workspace_id, kind, key) VALUES ('hub-list', 'cloud', 'test-key'); + INSERT INTO workspace_settings (workspace_id) VALUES ('hub-list'); + INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES ('hub-list', 'all', '', '{}'); + INSERT INTO usr (workspace_id, email, username, is_admin, operator, role) VALUES + ('hub-list', 'test@windmill.dev', 'test-user', true, false, 'Admin'), + ('hub-list', 'test2@windmill.dev', 'test-user-2', false, false, 'User');", + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let ws = format!( + "http://localhost:{}/api/w/hub-list/workspaces", + server.addr.port() + ); + let client = reqwest::Client::new(); + let write = |token: &'static str, list: serde_json::Value| { + client + .post(format!("{ws}/hub_access")) + .bearer_auth(token) + .json(&json!({ "hub_access": list })) + .send() + }; + let status = write(DEV, json!({"slack": "write"})).await?.status(); + assert_eq!(status, 403); + let typo = client + .post(format!("{ws}/hub_access")) + .bearer_auth("SECRET_TOKEN") + .json(&json!({ "hubAccess": {} })) + .send() + .await?; + assert_eq!(typo.status(), 422); + for (list, stored) in [ + (json!({"Slack": "read"}), json!({"slack": "read"})), + (json!({}), json!({})), + (json!(null), json!(null)), + ] { + let resp = write("SECRET_TOKEN", list).await?; + assert!(resp.status().is_success(), "{}", resp.text().await?); + let roles: serde_json::Value = client + .get(format!("{ws}/roles")) + .bearer_auth("SECRET_TOKEN") + .send() + .await? + .json() + .await?; + assert_eq!(roles["hub_access"], stored); + let operator = roles["roles"] + .as_array() + .unwrap() + .iter() + .find(|r| r["name"] == "operator") + .unwrap(); + let effective = if stored.is_null() { json!({}) } else { stored }; + assert_eq!(operator["capabilities"]["hub"], effective); + } + Ok(()) +} diff --git a/backend/tests/hub_saved_path.rs b/backend/tests/hub_saved_path.rs index a83b1bf287..6a79480fdc 100644 --- a/backend/tests/hub_saved_path.rs +++ b/backend/tests/hub_saved_path.rs @@ -1,5 +1,5 @@ //! A Hub path saved into a trigger or a schedule is checked when it is chosen, against the member -//! saving it: refused without `code`, and only on the paths the save changes. +//! saving it: refused without `code` or the Hub access list, and only on the paths the save changes. use serde_json::{json, Value}; use sqlx::{Pool, Postgres}; @@ -10,7 +10,7 @@ const OP: &str = "OPERATOR_TOKEN"; const HUB: &str = "hub/990000802/test/echo"; const OTHER_HUB: &str = "hub/990000803/test/echo"; const PRESET: &str = "hub/2431/slack/schedule-error-handler-slack"; -const REFUSAL: &str = "Hub scripts and flows require a role that can write code"; +const REFUSAL: &str = "Your role may not use this Hub script"; #[cfg(feature = "http_trigger")] fn http(path: &str, script_path: &str, error_handler: Option<&str>) -> Value { diff --git a/backend/tests/trigger_hub_target.rs b/backend/tests/trigger_hub_target.rs index f42ff339b4..7dc63e4f91 100644 --- a/backend/tests/trigger_hub_target.rs +++ b/backend/tests/trigger_hub_target.rs @@ -16,7 +16,7 @@ async fn hub_target_with_retry_runs_its_preprocessor(db: Pool) -> anyh initialize_tracing().await; let server = ApiServer::start(db.clone()).await?; - let version = "990000004"; + let version = "9990004"; let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR; tokio::fs::create_dir_all(hub_dir).await?; tokio::fs::write( diff --git a/backend/tests/workspace_handlers.rs b/backend/tests/workspace_handlers.rs index 0ad1e044bd..fc36bbba3e 100644 --- a/backend/tests/workspace_handlers.rs +++ b/backend/tests/workspace_handlers.rs @@ -288,7 +288,7 @@ async fn test_error_handler_triggered_on_hub_script_failure( let server = ApiServer::start(db.clone()).await?; - let version = "990000002"; + let version = "9990002"; let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR; tokio::fs::create_dir_all(hub_dir).await?; tokio::fs::write( @@ -386,7 +386,7 @@ async fn test_success_handler_triggered_on_hub_script_success( let server = ApiServer::start(db.clone()).await?; - let version = "990000003"; + let version = "9990003"; let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR; tokio::fs::create_dir_all(hub_dir).await?; tokio::fs::write( diff --git a/backend/windmill-api-auth/src/composed.rs b/backend/windmill-api-auth/src/composed.rs index 7860409c50..25cf358366 100644 --- a/backend/windmill-api-auth/src/composed.rs +++ b/backend/windmill-api-auth/src/composed.rs @@ -6,7 +6,7 @@ use sqlx::{Postgres, Transaction}; use windmill_common::{ error::{self, Error}, flows::FlowValue, - jobs::{check_can_name_runnable, RunOrigin}, + jobs::{check_can_name_runnables, RunOrigin}, roles::AuthorLevel, runnable_ref::RunnableRef, workspaces::{check_operator_can_build, BuilderKind}, @@ -15,32 +15,32 @@ use windmill_common::{ use crate::{get_scope_tags, is_super_admin_authed, ApiAuthed}; -/// The run-time rule for naming a Hub path, applied to one a builder saves. A save can hold many -/// Hub paths, so a refusal names the one it is about. +/// The run-time rule for naming a Hub path, applied to those a builder saves. A refusal names the +/// path it is about. pub async fn check_builder_can_name_hub( - runnable: &RunnableRef, + runnables: &[RunnableRef], authed: &ApiAuthed, db: &DB, w_id: &str, ) -> error::Result<()> { let origin = RunOrigin::NamedBy(authed.to_authed_ref()); - check_can_name_runnable(&origin, runnable, db, w_id) + check_can_name_runnables(&origin, runnables, db, w_id) .await - .map_err(|e| name_refused_path(runnable, e)) + .map_err(|(runnable, e)| name_refused_path(runnable, e)) } -fn name_refused_path(runnable: &RunnableRef, e: Error) -> Error { - match e { - Error::PermissionDenied(msg) => { +fn name_refused_path(runnable: Option<&RunnableRef>, e: Error) -> Error { + match (runnable, e) { + (Some(runnable), Error::PermissionDenied(msg)) => { Error::PermissionDenied(format!("{}: {msg}", runnable.path())) } - e => e, + (_, e) => e, } } -/// Refuses each of `new` that `old` does not hold and that needs `code`. A trigger or schedule -/// save is checked on the paths it changes only, so a member without `code` can still edit one -/// that already runs a Hub path; nothing is checked at fire. `old` must be the row locked by the +/// Refuses `new` if it holds a path that `old` does not and that the caller may not name. A trigger +/// or schedule save is checked on the paths it changes only, so a member can still edit one that +/// already runs a Hub path they may not name; nothing is checked at fire. `old` must be the row locked by the /// save, or a concurrent edit could slip a removed Hub path back in as unchanged. pub async fn check_new_hub_paths( new: &[RunnableRef], @@ -49,10 +49,8 @@ pub async fn check_new_hub_paths( db: &DB, w_id: &str, ) -> error::Result<()> { - for runnable in new.iter().filter(|r| !old.contains(r)) { - check_builder_can_name_hub(runnable, authed, db, w_id).await?; - } - Ok(()) + let added: Vec<_> = new.iter().filter(|r| !old.contains(r)).cloned().collect(); + check_builder_can_name_hub(&added, authed, db, w_id).await } /// `validate_operator_composed_flow` on a transaction the caller already holds, so a write that @@ -67,9 +65,7 @@ pub async fn authorize_composed_flow( w_id: &str, ) -> error::Result<()> { let mut refs = windmill_common::flows::check_flow_is_composition_only(value)?; - for runnable in &refs.hub_runnables { - check_builder_can_name_hub(runnable, authed, db, w_id).await?; - } + check_builder_can_name_hub(&refs.hub_runnables, authed, db, w_id).await?; // A builder links only an agent it can read, and binds only the tool inputs it leaves open. for agent in &refs.agents { diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index 5fb1d0be1f..faeda4365d 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -127,7 +127,7 @@ impl ApiAuthed { folders: &self.folders, scopes: &self.scopes, token_prefix: &self.token_prefix, - capabilities: self.capabilities, + capabilities: self.capabilities.clone(), } } @@ -240,7 +240,7 @@ impl Authable for ApiAuthed { } fn capabilities(&self) -> Option { - self.capabilities + self.capabilities.clone() } fn groups(&self) -> &[String] { diff --git a/backend/windmill-api-settings/src/lib.rs b/backend/windmill-api-settings/src/lib.rs index d6e6672080..a63da7be9e 100644 --- a/backend/windmill-api-settings/src/lib.rs +++ b/backend/windmill-api-settings/src/lib.rs @@ -69,8 +69,8 @@ use windmill_common::{ CRITICAL_ALERT_MUTE_UI_SETTING, CUSTOM_TAGS_SETTING, DEFAULT_TAGS_WORKSPACES_SETTING, DISABLE_HUB_SETTING, EMAIL_DOMAIN_SETTING, ENV_SETTINGS, EXTERNAL_INSTANCE_PG_SETTING, GITHUB_APP_WEBHOOK_BASE_URL_SETTING, HTTP_ROUTE_DEFAULT_ALLOWED_ORIGINS_SETTING, - HTTP_ROUTE_WORKSPACED_ROUTE_SETTING, HUB_ACCESSIBLE_URL_SETTING, HUB_BASE_URL_SETTING, - INSTANCE_BANNER_SETTING, MAX_RETENTION_OVERRIDE_WORKSPACES, + HTTP_ROUTE_WORKSPACED_ROUTE_SETTING, HUB_ACCESSIBLE_URL_SETTING, HUB_ACCESS_SETTING, + HUB_BASE_URL_SETTING, INSTANCE_BANNER_SETTING, MAX_RETENTION_OVERRIDE_WORKSPACES, MAX_TOKEN_EXPIRATION_DAYS_SETTING, MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING, RETENTION_PERIOD_SECS_OVERRIDES_SETTING, RUFF_CONFIG_SETTING, UNIQUE_ID_SETTING, WORKSPACE_FAIRNESS_DURATION_SECS_SETTING, WORKSPACE_FAIRNESS_ENABLED_SETTING, @@ -1006,6 +1006,9 @@ async fn run_setting_post_write_hook(db: &DB, key: &str) -> error::Result<()> { if key == WORKSPACE_ROLES_SETTING { windmill_common::roles::after_instance_roles_write(db).await?; } + if key == HUB_ACCESS_SETTING { + windmill_common::roles::invalidate_all_roles_cache(); + } Ok(()) } @@ -1042,6 +1045,9 @@ async fn run_setting_pre_write_hook( WORKSPACE_ROLES_SETTING => { windmill_common::roles::validate_instance_roles_write(db, Some(value)).await?; } + HUB_ACCESS_SETTING => { + windmill_common::roles::validate_instance_hub_access_write(db, value).await?; + } // Settings that fail validation would only surface on the next secret read, as an error // on every secret of every workspace. windmill_common::global_settings::SECRET_BACKEND_SETTING => { diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index 4acaff2433..66af60b90c 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -2585,18 +2585,18 @@ pub async fn set_workspace_role( username: &str, role: &str, ) -> Result<()> { - let caps = windmill_common::roles::workspace_roles_on(&mut **tx, w_id) + let code = windmill_common::roles::workspace_roles_on(&mut **tx, w_id) .await? .iter() .find(|r| r.name == role) - .map(|r| r.capabilities) + .map(|r| r.capabilities.code) .ok_or_else(|| { Error::BadRequest(format!("role `{role}` is not defined in workspace {w_id}")) })?; sqlx::query!( "UPDATE usr SET workspace_role = $1, operator = $2 WHERE username = $3 AND workspace_id = $4", role, - !caps.code, + !code, username, w_id ) diff --git a/backend/windmill-api-workspaces/src/workspace_roles.rs b/backend/windmill-api-workspaces/src/workspace_roles.rs index b78c9c0deb..3dee005871 100644 --- a/backend/windmill-api-workspaces/src/workspace_roles.rs +++ b/backend/windmill-api-workspaces/src/workspace_roles.rs @@ -11,8 +11,8 @@ use windmill_audit::{audit_oss::audit_log, ActionKind}; use windmill_common::{ error::{Error, JsonResult, Result}, roles::{ - self, instance_roles, load_role_overrides, EffectiveRole, RoleCapabilities, RoleOverrides, - RoleSource, OPERATOR_ROLE, + self, instance_roles, load_role_overrides, EffectiveRole, HubAccessList, RoleCapabilities, + RoleOverrides, RoleSource, OPERATOR_ROLE, }, utils::require_admin, DB, @@ -23,12 +23,16 @@ pub fn workspaced_service() -> Router { Router::new() .route("/roles", get(list_roles)) .route("/role_overrides", post(update_role_overrides)) + .route("/hub_access", post(update_hub_access)) } #[derive(Serialize)] struct WorkspaceRoles { roles: Vec, overrides: RoleOverrides, + /// The workspace's own Hub access list, `None` while it follows `instance_hub_access`. + hub_access: Option, + instance_hub_access: HubAccessList, /// Whether this workspace may add roles of its own. custom_roles_enabled: bool, /// The caller's role, `None` for a caller with no membership (a superadmin, a guest). @@ -43,6 +47,7 @@ async fn list_roles( ) -> JsonResult { let roles = roles::workspace_roles(&db, &w_id).await?; let overrides = load_role_overrides(&db, &w_id).await?; + let hub = roles::load_hub_access(&mut *db.acquire().await?, &w_id).await?; let my_role = sqlx::query!( "SELECT workspace_role, operator FROM usr WHERE workspace_id = $1 AND username = $2", &w_id, @@ -61,6 +66,8 @@ async fn list_roles( Ok(Json(WorkspaceRoles { roles: roles.as_ref().clone(), overrides, + hub_access: hub.workspace, + instance_hub_access: hub.instance, custom_roles_enabled: roles::custom_roles_enabled(), my_role, my_capabilities, @@ -182,6 +189,65 @@ pub(crate) async fn write_role_overrides( Ok(()) } +#[derive(Deserialize)] +pub(crate) struct UpdateHubAccess { + /// `null` follows the instance's list; `{}` allows nothing. `deserialize_with`: an + /// absent key is refused, not read as `null`, so a typo does not drop the list. + #[serde(deserialize_with = "Option::deserialize")] + hub_access: Option, +} + +pub(crate) async fn update_hub_access( + authed: ApiAuthed, + Path(w_id): Path, + Extension(db): Extension, + Json(body): Json, +) -> Result { + require_admin(authed.is_admin, &authed.username)?; + let hub_access = body + .hub_access + .as_ref() + .map(roles::parse_hub_access) + .transpose()? + .map(|list| serde_json::json!(list)); + + let mut tx = db.begin().await?; + sqlx::query!( + "UPDATE workspace_settings SET hub_access = $1 WHERE workspace_id = $2", + hub_access, + &w_id + ) + .execute(&mut *tx) + .await?; + roles::notify_role_overrides_change(&mut tx, &w_id).await?; + let audited = hub_access.unwrap_or_default().to_string(); + audit_log( + &mut *tx, + &authed, + "workspaces.update_hub_access", + ActionKind::Update, + &w_id, + None, + Some([("hub_access", audited.as_str())].into()), + ) + .await?; + tx.commit().await?; + roles::invalidate_workspace_roles_cache(&w_id); + + handle_deployment_metadata( + &authed.email, + &authed.username, + &db, + &w_id, + windmill_git_sync::DeployedObject::Settings { setting_type: "hub_access".to_string() }, + Some("Workspace Hub scripts updated".to_string()), + false, + None, + ) + .await?; + Ok("Hub access updated".to_string()) +} + /// The legacy `/operator_settings` payload. Visibility flags always serialize; the rights are /// `Option` because git-sync posts whole files that may predate them, and an absent key must /// leave the stored value alone. @@ -241,14 +307,13 @@ pub(crate) async fn update_operator_settings( let base = base.capabilities; let mut overrides = load_role_overrides(&db, &w_id).await?; - let current = roles::workspace_roles(&db, &w_id) + let mut target = roles::workspace_roles(&db, &w_id) .await? .iter() .find(|r| r.name == OPERATOR_ROLE) - .map(|r| r.capabilities) - .unwrap_or(base); + .map(|r| r.capabilities.clone()) + .unwrap_or_else(|| base.clone()); - let mut target = current; let v = &mut target.visibility; (v.runs, v.schedules, v.resources, v.variables, v.assets) = ( settings.runs, @@ -269,8 +334,8 @@ pub(crate) async fn update_operator_settings( Some(false) => roles::AuthorLevel::None, _ => cur, }; - target.flows = compose_or_keep(current.flows, settings.builder_flows); - target.apps = compose_or_keep(current.apps, settings.builder_apps); + target.flows = compose_or_keep(target.flows, settings.builder_flows); + target.apps = compose_or_keep(target.apps, settings.builder_apps); if let Some(b) = settings.manage_schedules { target.manage_schedules = b; } diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 2580ce84f4..34340aa99e 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -650,14 +650,15 @@ async fn resolve_new_member_role( None if operator => windmill_common::roles::OPERATOR_ROLE.to_string(), None => windmill_common::roles::default_role_name(roles.iter().map(|r| r.name.as_str())), }; - let caps = roles + let code = roles .iter() .find(|r| r.name == name) .ok_or_else(|| { Error::BadRequest(format!("role `{name}` is not defined in workspace {w_id}")) })? - .capabilities; - Ok((name, !caps.code)) + .capabilities + .code; + Ok((name, !code)) } /// The role is one choice stored as two flags; both set would show as admin in the UI while the @@ -8156,28 +8157,27 @@ async fn fork_roles(db: &DB, parent_workspace_id: &str) -> Result { let mut out = ForkRoles { from: vec![], to: vec![], to_operator: vec![] }; for role in roles.iter() { let to = mapping.get(&role.name).unwrap_or(&role.name); - let caps = roles + let code = roles .iter() .find(|r| &r.name == to) - .map(|r| r.capabilities) - .unwrap_or(windmill_common::roles::RoleCapabilities::NONE); + .is_some_and(|r| r.capabilities.code); out.from.push(role.name.clone()); out.to.push(to.clone()); - out.to_operator.push(!caps.code); + out.to_operator.push(!code); } Ok(out) } -/// Give the fork the parent's workspace-only roles and overrides, so a role carried into the fork -/// means there what it means in the parent. +/// Give the fork the parent's workspace-only roles, overrides and Hub access list, so a role carried +/// into the fork means there what it means in the parent. async fn copy_workspace_roles( tx: &mut Transaction<'_, Postgres>, source_workspace_id: &str, target_workspace_id: &str, ) -> Result<()> { sqlx::query!( - "UPDATE workspace_settings SET role_overrides = - (SELECT role_overrides FROM workspace_settings WHERE workspace_id = $2) + "UPDATE workspace_settings SET (role_overrides, hub_access) = + (SELECT role_overrides, hub_access FROM workspace_settings WHERE workspace_id = $2) WHERE workspace_id = $1", target_workspace_id, source_workspace_id, @@ -15950,6 +15950,7 @@ pub enum SettingsEdit { OperatorSettings, /// Body: the workspace's role overrides as a whole, `{ "": { label?, capabilities } }`. RoleOverrides, + HubAccess, Datatable, SlackCommand, SetSlackOAuth, @@ -16018,6 +16019,10 @@ pub async fn apply_settings_edit( crate::workspace_roles::update_role_overrides(a, p, d, settings_edit_body(edit, body)?) .await? } + HubAccess => { + crate::workspace_roles::update_hub_access(a, p, d, settings_edit_body(edit, body)?) + .await? + } Datatable => { let Json(result) = edit_datatable_config(a, d, p, settings_edit_body(edit, body)?).await?; diff --git a/backend/windmill-api-workspaces/src/workspaces_extra.rs b/backend/windmill-api-workspaces/src/workspaces_extra.rs index bd7b342695..bbffd82bcd 100644 --- a/backend/windmill-api-workspaces/src/workspaces_extra.rs +++ b/backend/windmill-api-workspaces/src/workspaces_extra.rs @@ -152,7 +152,7 @@ pub(crate) async fn change_workspace_id( // Duplicate workspace settings (keep copy in old workspace for reference) info!("Duplicating workspace_settings table"); sqlx::query!( - "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", + "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, hub_access, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, hub_access, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", &rw.new_id, &old_id ) diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 59852e1482..556a206496 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -4221,6 +4221,36 @@ paths: schema: type: string + /w/{workspace}/workspaces/hub_access: + post: + operationId: updateWorkspaceHubAccess + summary: Replace the workspace's Hub access list + description: The Hub integrations whose approved scripts members without code may use in this workspace. `null` follows the instance's list; a list replaces it, and an empty one allows nothing. Requires workspace admin privileges. + tags: + - workspace + parameters: + - $ref: "#/components/parameters/WorkspaceId" + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - hub_access + properties: + hub_access: + nullable: true + allOf: + - $ref: "#/components/schemas/HubAccessList" + responses: + "200": + description: Hub access list updated + content: + text/plain: + schema: + type: string + /w/{workspace}/workspaces/compare/{target_workspace_id}: get: operationId: compareWorkspaces @@ -10429,6 +10459,12 @@ paths: description: the label the hub curates for the integration, null or absent where it names none type: string nullable: true + approved_scripts: + description: how many standalone scripts of the integration are approved, of every kind, absent on a hub that does not count them + type: integer + read_only_scripts: + description: how many of the approved scripts are read-only, absent on a hub that does not count them + type: integer required: - name @@ -41105,6 +41141,17 @@ components: enum: [none, compose, full] description: How much of a kind of runnable a role may author. `compose` assembles already-deployed runnables with no code of one's own. + HubAccess: + type: string + enum: [read, write] + description: What a role without code may do with the Hub scripts of one integration. `read` allows only versions the Hub approved as read-only; `write` implies `read`. + + HubAccessList: + type: object + description: Hub integrations (lowercased) whose approved scripts a role without `code` may name, with the level allowed. A key may not contain `/`. + additionalProperties: + $ref: "#/components/schemas/HubAccess" + RoleVisibility: type: object description: Pages a role sees. Not enforced. @@ -41143,6 +41190,8 @@ components: description: Fork the workspace. visibility: $ref: "#/components/schemas/RoleVisibility" + hub: + $ref: "#/components/schemas/HubAccessList" required: [code, flows, apps, manage_schedules, manage_triggers, run, fork, visibility] RoleCapabilitiesPatch: @@ -41214,6 +41263,13 @@ components: $ref: "#/components/schemas/EffectiveRole" overrides: $ref: "#/components/schemas/RoleOverrides" + hub_access: + nullable: true + description: The workspace's own Hub access list, null while it follows `instance_hub_access`. + allOf: + - $ref: "#/components/schemas/HubAccessList" + instance_hub_access: + $ref: "#/components/schemas/HubAccessList" custom_roles_enabled: type: boolean description: Whether this workspace may add roles of its own. @@ -41222,7 +41278,7 @@ components: nullable: true my_capabilities: $ref: "#/components/schemas/RoleCapabilities" - required: [roles, overrides, custom_roles_enabled, my_capabilities] + required: [roles, overrides, instance_hub_access, custom_roles_enabled, my_capabilities] WorkspaceComparison: type: object diff --git a/backend/windmill-api/src/ai_session_tools/gen/instructions.json b/backend/windmill-api/src/ai_session_tools/gen/instructions.json index 3175fce392..86c99b3cc4 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/instructions.json +++ b/backend/windmill-api/src/ai_session_tools/gen/instructions.json @@ -317,7 +317,7 @@ "datatable.python3": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role `, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", "datatable.go": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role `, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch(\n params?: FetchParams // The union is for auto-completion\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit, \"resultCollection\">\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit, \"resultCollection\">\n ): Promise;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n (strings: TemplateStringsArray, ...values: any[]): SqlStatement;\n query(sql: string, ...params: any[]): SqlStatement;\n};\n```\n\nCreate a SQL template function for PostgreSQL/datatable queries\n@param name - Database/datatable name (default: \"main\")\n@param opts.role - Connect as this data table role instead of the data table's default one.\n Only meaningful on a data table under roles, and only for a role you are a tenant of.\n@returns SQL template function for building parameterized queries\n@example\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", "pipeline": "# Data pipeline authoring\n\nA **data pipeline** is NOT a flow. A flow is one runnable that orchestrates steps internally. A data pipeline is a set of **independent scripts**, each deployed on its own, that form a DAG by reading and writing shared **storage assets** (DuckLake tables, data tables, S3 objects, volumes, resources) and by declaring execution **triggers**. The pipeline is visualized and edited at `/pipeline/`; every node is a normal workspace script that happens to carry pipeline annotations. When the user asks for a \"data pipeline\" (or to \"ingest / transform / materialize\" data across steps), build pipeline-annotated scripts — do NOT build a flow.\n\n## Default to DuckDB + DuckLake\n\nA pipeline node that produces a table should almost always be a **`duckdb`** node that materializes its output into a **DuckLake** table with `-- materialize ducklake:///` (in a DuckDB node the annotation uses SQL `--` comment syntax; write the body as a bare `SELECT` and let the runtime do the write). DuckLake is the default lakehouse store for pipelines and is the shape the pipeline editor is built around, so prefer it unless the work specifically calls for something else:\n\n- `postgresql` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live).\n- `bun` / `python3` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see \"Ingesting from Python / TypeScript\" below — rather than inventing a parallel store.\n\nDo not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal.\n\n## Ingesting from Python / TypeScript\n\nA node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with `wmill.ducklake()`, or into a data table with `wmill.datatable()`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second \"load the raw file\" node. One ingestion node, one table.\n\nPass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema:\n\n```python\n# pipeline\n# on schedule\nimport wmill\n\ndef main():\n rows = fetch_charges() # list[dict]\n lake = wmill.ducklake()\n lake.query(\"\"\"\n CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json($rows, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)\n \"\"\", rows=rows).fetch()\n```\n\n```ts\n// pipeline\n// on schedule\nimport * as wmill from \"windmill-client\"\n\nexport async function main() {\n const rows = await fetchCharges()\n const lake = wmill.ducklake()\n await lake`CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json(${rows}, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)`.fetch()\n}\n```\n\n- Use `INSERT INTO
SELECT ...` instead of `CREATE OR REPLACE` to append (an incremental pull), with a one-time `CREATE TABLE IF NOT EXISTS` first.\n- Assign the client to a variable (`lake = wmill.ducklake()`) and keep the SQL a **string literal** (Python) or a template without `sql.raw` (TS): that is what lets the graph record the node's write to `ducklake://main/
`. A chained `wmill.ducklake().query(...)` or SQL built in a variable records no output, so the downstream edge never forms.\n- `wmill.ducklake(\"\")` targets a non-default catalog; `wmill.datatable(\"\")` writes a Postgres data table the same way (Python `db.query(sql, *args)` with `$1` placeholders, TS the same template form) — use it only when the data belongs in Postgres (see above).\n- The downstream node triggers on the table itself: `-- on ducklake://main/stripe_charges`.\n\n## Storage prerequisites\n\nA DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and `s3://` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build.\nDrafting the annotated scripts does not require storage, but the pipeline can't ingest, materialize, or read its assets until it exists. So if there is none (or the user hits \"storage not configured\" errors), say so and give the right next step **by role**:\n\n- a workspace **admin** sets it up in Workspace settings → Object Storage (add an S3/Azure/GCS storage), then adds a DuckLake catalog on top of it;\n- anyone **without admin rights** should ask a workspace admin to configure object storage + a DuckLake catalog.\n\nNever hand back a DuckLake pipeline that cannot run without flagging the missing storage and pointing to who sets it up.\n\n## What makes a script a pipeline node\n\nA script joins the pipeline when its source begins with the `pipeline` annotation as a top-of-file comment, **written in the script's own comment syntax** — `//` for TS/JS (bun), `--` for SQL (DuckDB/Postgres), `#` for Python/Bash. So it's `-- pipeline` in a DuckDB node, `# pipeline` in a Python node, `// pipeline` in a bun node. Every annotation below uses that same prefix (the `//` shown is the TS form). All other wiring is expressed as annotation comments near the top of the file:\n\n- `// on ` — declares an execution-DAG **input** (what triggers/feeds this node). `` is either:\n - an **asset URI** (the node runs when that asset is produced upstream): `ducklake://main/orders`, `datatable://main/users`, `$res:f/folder/my_resource`, `volume://name/path`, or an S3 object (see the S3 storage-form rule below).\n - a **native trigger kind**: `schedule`, `webhook`, `email`, `kafka`, `mqtt`, `amqp`, `nats`, `postgres`, `sqs`, `gcp`, or `data_upload` (a user-uploaded S3 file). For these the actual trigger row (cron, topic, …) is created separately; the annotation only declares the binding. **`data_upload` is special**: there is no trigger row — the node instead declares an **`S3Object` input parameter** fed by the auto-generated upload picker; it never hard-codes a key. Any language can be the `data_upload` node:\n - Python (has `import wmill`): `def main(file: wmill.S3Object):` then `wmill.load_s3_file(file)`; TS (has `import * as wmill from \"windmill-client\"`): `export async function main(file: wmill.S3Object)`. Qualify the type as `wmill.S3Object` (or add `from wmill import S3Object` / `import { S3Object } from \"windmill-client\"`) — a bare `S3Object` is undefined.\n - **DuckDB** takes the s3object arg via a `-- $ (s3object)` declaration and reads it directly, so a single DuckDB node can ingest **and** materialize:\n ```\n -- pipeline\n -- on data_upload\n -- materialize ducklake://main/raw_uploads\n -- $file (s3object)\n SELECT * FROM read_csv($file)\n ```\n- **Outputs** are inferred from what the body writes — a `CREATE TABLE`, a `wmill.writeS3File(...)`, a DuckLake/datatable write. To declare a managed output explicitly, use `// materialize `.\n- Optional badges: `// partitioned `, `// freshness ` (e.g. `1h`), `// tag `, `// retry [delay]`, `// data_test ...` (managed DuckLake targets only — deploy rejects it beside a `dbt://` one), `// measure = [where ]` and `// dimension = ` (see \"Declared metrics\" below).\n\n## S3 object wiring (storage form matters)\n\nAn `s3://` URI's first slashes select the **storage**, not part of the key — get this wrong and the producer/consumer edge silently won't connect:\n\n- `s3:///` (**triple** slash, empty first segment) = the **default** workspace storage. A downstream node reading or triggering on that object uses `s3:///` — e.g. DuckDB `-- on s3:///orders/2024.parquet` and `read_parquet('s3:///orders/2024.parquet')`.\n- `s3:///` (**double** slash, non-empty first segment) = a **named secondary** storage called `` — so `s3://ingest/x` means storage `ingest`, key `x`, NOT key `ingest/x`. Only use this when the object genuinely lives in a configured secondary storage; never invent a bucket/storage name for a default-storage object (it breaks the edge).\n\nTo make the producer side visible to lineage, a Python/TS node MUST pass the **`S3Object` form**, not a bare key string: Python `wmill.write_s3_file(wmill.S3Object(s3=\"\"), data)` (or the import-free dict `{\"s3\": \"\"}`), TS `wmill.writeS3File({ s3: \"\" }, data)`. That records the default-storage asset `/`, which a downstream `s3:///` reader connects to (same key both sides). A bare `write_s3_file(\"\", ...)` records **no** asset and produces **no** edge. Add `storage=\"\"` only for a named secondary storage.\n\nThe key must be a **string literal** — the graph parser is static and cannot follow a variable, f-string, or computed path, so `write_s3_file(wmill.S3Object(s3=key_var), ...)` records no edge. Inline the literal (`s3=\"events/user_events.parquet\"`) on both the writing and reading node. The same rule applies to every asset URI in an annotation or SDK call (`ducklake://`, `datatable://`, `s3://`): write them literally, not via a variable.\n\n## Materialize (the managed output)\n\n> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake:///
`). Deploy **rejects** a `ducklake://` `// materialize` on any other language (`python3`, `bun`, `postgresql`). For a non-DuckDB node writing the lake, do **not** use `// materialize` — write the table itself with `wmill.ducklake()` (see \"Ingesting from Python / TypeScript\") and let the output be inferred. Use `duckdb` when a node should materialize a DuckLake table.\n>\n> The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt:////`, where `` is a warehouse the workspace configures under Settings → dbt. `manual` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql `CREATE TABLE` / `INSERT`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a `source`: the declared relation and the dbt model land on ONE graph node, and a downstream `// on dbt:////` fires when the ingestion node completes.\n\nA managed `// materialize ducklake:///
` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.)\n\nA target that names no table — `// materialize`, `// materialize ducklake://`, or options alone such as `// materialize key=id` — writes the table named after the script: node `f/shop/orders_daily` materializes `ducklake://main/orders_daily` (characters other than letters, digits and `_` become `_`, and a name starting with a digit gets a leading `_`). Name the node after the table it produces and the bare form is enough; write the full target when the table's name differs from the node's, and use that same name in every downstream `// on` and read.\n\nWrite strategy:\n\n- no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change);\n- `// materialize append` → INSERT-append rows (incremental);\n- `// materialize key=` → merge/upsert on ``.\n\n`// materialize manual ` opts **out** of managed writes — the script writes its own DDL and the annotation only records the output asset for lineage.\n\n`materialize` pairs with partitioning for incremental pipelines: a `// partitioned ` node runs **once per partition** (append/merge into a fixed-schema table). The `{partition}` token, usable in any asset URI **and** in the body SQL, is replaced at run time by the current partition's **identity string**:\n\n- To filter the source to the active slice on a time grain, use the runtime-injected macro: `WHERE wm_partition() = {partition}`. `wm_partition(ts)` buckets a timestamp in exactly the identity format the runtime uses for daily/hourly/weekly/monthly, so it always matches; never hand-write a `strftime` format.\n- Do NOT write `= TIMESTAMP {partition}`: the identity string is not a valid timestamp literal for hourly/weekly/monthly and errors at run time.\n- For `dynamic` partitioning the identity is the caller-supplied key (not a timestamp, no macro), so filter on it directly: `WHERE = {partition}`.\n\n`materialize` is an output **declaration** on a node — not a command. There is no \"materialize run\".\n\n## Declared metrics (`measure` / `dimension`)\n\nOn a node that materializes a DuckLake table, `// measure = [where ]` names the canonical way to aggregate that table (e.g. `// measure revenue = sum(amount) where not is_refund`), and `// dimension = ` names a way to slice it (e.g. `// dimension region = region`, `// dimension month = date_trunc('month', ordered_at)`). They execute nothing: they are catalogued at deploy so the editor and other agents reuse the definition instead of re-deriving it and silently disagreeing.\n\n- Keep the predicate in the `where` clause rather than folding it into the aggregate: it is rendered as ` FILTER (WHERE )`, which is what lets two measures with different predicates share one GROUP BY.\n- DuckLake-only, and only meaningful next to `// materialize`.\n- Declare one when a number carries a judgement call someone else would get wrong (refunds excluded, test rows dropped, which column is the amount); do NOT blanket every table with measures — an obvious `count(*)` earns nothing.\n- To use a metric another node declares, read that node and reuse its exact expression rather than guessing it.\n\n## How to build one\n\n1. Put every node in the **same folder**: `f//`. The folder is the pipeline.\n2. Write each node as its own script. Default to `duckdb` materializing into DuckLake (see \"Default to DuckDB + DuckLake\" above); pick `postgresql`, `bun`, or `python3` only when that section says the work calls for it.\n3. Start each body with `// pipeline`, then the `// on` input declarations, then the transform that writes the output.\n4. **Chain nodes by asset URI**: read an upstream node's output asset, then `// on ` in the downstream node so the edge forms. Reuse exact asset paths from existing nodes rather than inventing parallel ones.\n5. Never guess the columns of a file or table you have not seen: read them first with a query that writes nothing, such as `DESCRIBE SELECT * FROM read_csv('s3:///raw/orders/*.csv')` or `ATTACH 'ducklake://main' AS lake; DESCRIBE lake.orders`, and use those exact column names. A test run of a node that materializes a table writes that table into the workspace's lake: test-run such a node only while its table does not exist yet, and ask before running one that would replace a table already there.\n6. Don't deploy nodes unless the user asks to. A pipeline only \"runs\" once its scripts are deployed and their triggers exist.\n\n## Example (DuckDB → DuckLake, scheduled ingest + downstream transform)\n\nNode `f/sales/orders_ingest` (runs on a schedule, materializes a DuckLake table):\n\n```sql\n-- pipeline\n-- on schedule\n-- materialize ducklake://main/orders\nSELECT * FROM read_csv('s3:///raw/orders/*.csv')\n```\n\nNode `f/sales/orders_daily` (runs when `orders` is produced, writes a rollup):\n\n```sql\n-- pipeline\n-- on ducklake://main/orders\n-- materialize ducklake://main/orders_daily\nATTACH 'ducklake://main' AS lake;\nSELECT date_trunc('day', ts) AS day, count(*) AS n\nFROM lake.orders GROUP BY 1\n```\n\nA node reads a DuckLake table only through a lake it attaches itself (`ATTACH 'ducklake://' AS lake;`, then `lake.
`); the materialize target is attached by the runtime under a name of its own, so `ducklake.main.
` does not resolve.\n", - "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`webhook` (its URL usually carries the receiver's token) and `slack_oauth_client_secret` are the\nsecrets. A read shows `__SENSITIVE_AND_UNCHANGED__` in place\nof a set secret; sending that placeholder back keeps the stored value. A value starting with\n`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key\nis left unchanged with a warning; any other value is taken as plaintext. Never\nwrite a secret you were not given: keep the placeholder.\n\n## Keys\n\n| Key | Value |\n|---|---|\n| `auto_invite` | `{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. |\n| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path?, muted_on_ui_runs? }`, `path` being `script/` or `flow/`. `muted_on_ui_runs` (error handler only) skips jobs started from the UI. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { : { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ : { default_role, roles: { : [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/`, `g/`, `f/` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. |\n| `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { : } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`, `RequireSso` (an account signing in with a password, other than a bypasser, cannot join, and no member can be switched to a password login; members already signing in with a password are not removed). A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |\n| `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `role_overrides` | `{ : { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |\n| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |\n| `mute_critical_alerts` | Mute the workspace's critical alerts. |\n| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |\n| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. |\n| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. |\n| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. |\n| `guest_jwt_public_key`, `guest_jwt_jwks_url` | The key that signs guest JWTs for apps set to Guests. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n", + "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`webhook` (its URL usually carries the receiver's token) and `slack_oauth_client_secret` are the\nsecrets. A read shows `__SENSITIVE_AND_UNCHANGED__` in place\nof a set secret; sending that placeholder back keeps the stored value. A value starting with\n`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key\nis left unchanged with a warning; any other value is taken as plaintext. Never\nwrite a secret you were not given: keep the placeholder.\n\n## Keys\n\n| Key | Value |\n|---|---|\n| `auto_invite` | `{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. |\n| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path?, muted_on_ui_runs? }`, `path` being `script/` or `flow/`. `muted_on_ui_runs` (error handler only) skips jobs started from the UI. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { : { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ : { default_role, roles: { : [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/`, `g/`, `f/` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. |\n| `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { : } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`, `RequireSso` (an account signing in with a password, other than a bypasser, cannot join, and no member can be switched to a password login; members already signing in with a password are not removed). A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |\n| `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `role_overrides` | `{ : { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |\n| `hub_access` | `{ : read \\| write }`: the Hub scripts members without code may use, replacing the instance's list. `null` uses the instance's list; `{}` allows none. |\n| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |\n| `mute_critical_alerts` | Mute the workspace's critical alerts. |\n| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |\n| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. |\n| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. |\n| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. |\n| `guest_jwt_public_key`, `guest_jwt_jwks_url` | The key that signs guest JWTs for apps set to Guests. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n", "display": "# Rich results\n\nWindmill renders a script's or flow's return value according to its shape: on run pages, in the\nscript and flow editors, in app result displays and in AI chat run cards. Anything that matches none\nof the shapes below is shown as JSON.\n\n## Shapes\n\n- `{ \"table-row-object\": [{...}, ...] }`, or a bare array of objects: a table whose columns are the\n union of the objects' keys.\n- `{ \"table-col\": { \"col\": [...], ... } }`, or a bare object of equal-length arrays: a table built\n column by column.\n- `{ \"table-row\": [[\"col\", ...], [v, ...], ...] }`: a table whose first row holds the column names.\n- `{ \"chart\": {...} }`: a bar, line, pie or scatter chart drawn from rows (schema below). A `chart`\n value the schema rejects is shown as JSON, not as a broken chart.\n- `{ \"markdown\": \"...\" }` (or `md`): rendered markdown.\n- `{ \"html\": \"...\" }`: sanitized HTML.\n- `{ \"png\": \"\" }`, likewise `jpeg`, `gif`, `svg`: an image. `{ \"pdf\": \"\" }`: a PDF.\n- `{ \"file\": \"\", \"filename\": \"report.csv\" }`: a download.\n- `{ \"map\": { \"lat\": 0, \"lon\": 0, \"zoom\": 3, \"markers\": [{ \"lat\": 0, \"lon\": 0, \"title\": \"...\" }] } }`:\n a map.\n- `{ \"s3\": \"path/to/key\" }`: an object in the workspace storage, previewed by type.\n- `{ \"render_all\": [ ... ] }`: each item rendered in turn with the rules above.\n\nEach shape is an object with that one key (plus `filename` for a file, and an optional `storage` for\n`s3`). A result carrying any other key beside it is shown as JSON.\n\n## Choosing one\n\nA chart answers a question at a glance: a trend over time (line), a comparison across categories\n(bar), parts of a whole with few parts (pie), or a relation between two numbers (scatter). A table\nanswers lookups and holds the exact values. When both help, return both in a `render_all`: the chart\nfirst, then the table of the same rows.\n\nKeep a chart to what it shows well: at most 8 series. A pie with more than 8 slices keeps the 7\nlargest and folds the rest into \"Other\", so prefer a bar chart for many categories. Aggregate before\ncharting: a chart of thousands of raw points says less than one of the totals per day.\n\n\n### Chart and table schema\n\nA chart or table value, as JSON Schema. Beyond it: `x` and every `y` must be columns of `data`, `y` columns hold numbers, a scatter chart's `x` column holds numbers, and a pie chart takes exactly one `y`.\n\n```json\n{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"anyOf\":[{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]},{\"type\":\"object\",\"properties\":{\"render_all\":{\"description\":\"Several items shown one after another\",\"minItems\":1,\"maxItems\":10,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]}}},\"required\":[\"render_all\"],\"additionalProperties\":false}]}\n```\n\nBar chart, one series per y column:\n\n```json\n{\n \"chart\": {\n \"type\": \"bar\",\n \"title\": \"Runs per day\",\n \"data\": [\n {\n \"day\": \"2026-11-10\",\n \"success\": 42,\n \"failure\": 3\n },\n {\n \"day\": \"2026-11-11\",\n \"success\": 51,\n \"failure\": 1\n }\n ],\n \"x\": \"day\",\n \"y\": [\n \"success\",\n \"failure\"\n ],\n \"stacked\": true\n }\n}\n```\n\nPie chart (exactly one y column):\n\n```json\n{\n \"chart\": {\n \"type\": \"pie\",\n \"data\": [\n {\n \"language\": \"python3\",\n \"scripts\": 18\n },\n {\n \"language\": \"bun\",\n \"scripts\": 25\n }\n ],\n \"x\": \"language\",\n \"y\": \"scripts\"\n }\n}\n```\n\nA chart and a table together:\n\n```json\n{\n \"render_all\": [\n {\n \"chart\": {\n \"type\": \"line\",\n \"data\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180\n }\n ],\n \"x\": \"hour\",\n \"y\": \"p95_ms\",\n \"y_label\": \"ms\"\n }\n },\n {\n \"table-row-object\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120,\n \"jobs\": 310\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180,\n \"jobs\": 402\n }\n ]\n }\n ]\n}\n```\n", "code_mode": "# Solving a task with code\n\nWhen the user asks for something done against the systems their workspace connects to (look\nsomething up in an API, move data, check a status), answer it with a Windmill script run as a\npreview: it executes on the workspace's workers, with its resources. A script that worked can be\nsaved and run as is the next time.\n\n1. **Look for a saved script first**, by the user's words and by the system the task touches. If\n one fits, run it rather than writing new code; if one nearly fits, offer to change it rather\n than writing a near-duplicate.\n2. **Otherwise write one script and run it as a preview.** Do the fetching, filtering and\n combining in the code, and return only what answers the task, not raw API payloads. Take\n credentials as a resource-typed `main` parameter, passed as `$res:` when running, never\n as a token in the code. Give `main` typed parameters for whatever would change between runs,\n so the script is reusable.\n3. **Offer to save it** when the task is likely to come back, without saving it unasked. Saving\n makes a draft, deployed only when the user asks; from then on it is an ordinary script.\n\nFor a third-party API, look up its hub integration for its resource type and how to call it.\n\n" } diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index a835203697..f6bb7c851e 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -2494,19 +2494,19 @@ pub(crate) async fn validate_operator_composed_app( let referenced = check_operator_composed_app(write, raw_app, value, policy)?; // A Hub path has no workspace row to be readable in: it is held to the rule for naming one. let mut in_workspace = Vec::with_capacity(referenced.len()); + let mut hub_runnables = vec![]; for (kind, path) in referenced { if kind != AppRunnableKind::Agent { let runnable = RunnableRef::from_path(&path, kind == AppRunnableKind::Flow)?; if runnable.path().starts_with("hub/") { - windmill_api_auth::composed::check_builder_can_name_hub( - &runnable, authed, db, w_id, - ) - .await?; + hub_runnables.push(runnable); continue; } } in_workspace.push((kind, path)); } + windmill_api_auth::composed::check_builder_can_name_hub(&hub_runnables, authed, db, w_id) + .await?; require_runnables_readable(authed, db, user_db, w_id, in_workspace).await } diff --git a/backend/windmill-api/src/workspace_settings_document.rs b/backend/windmill-api/src/workspace_settings_document.rs index 0c78f4b947..a3d3f2566f 100644 --- a/backend/windmill-api/src/workspace_settings_document.rs +++ b/backend/windmill-api/src/workspace_settings_document.rs @@ -81,6 +81,7 @@ struct SettingsRow { slack_oauth_client_secret: Option, ducklake: Option, dbt_warehouses: Option, + hub_access: Option, deploy_ui: Option, teams_command_script: Option, public_app_execution_limit_per_minute: Option, @@ -356,7 +357,7 @@ pub async fn load_settings_document( ai_config, large_file_storage, git_sync, default_app, default_scripts, workspace.name AS name, mute_critical_alerts, color, operator_settings, datatable, slack_team_id, slack_name, slack_command_script, - slack_oauth_client_id, slack_oauth_client_secret, ducklake, dbt_warehouses, deploy_ui, + slack_oauth_client_id, slack_oauth_client_secret, ducklake, dbt_warehouses, hub_access, deploy_ui, teams_command_script, public_app_execution_limit_per_minute, guest_jwt_public_key, guest_jwt_jwks_url, error_handler_fallback_to_instance_alerts, add_admins_and_developers_to_forks @@ -417,7 +418,7 @@ pub async fn load_settings_document( // In the order `wmill sync pull` has always written settings.yaml. A key that predates the // document and is not marked `always` is written only when set, as it always was; a key // added since is always written, so a pulled file states it and from then on manages it. - let entries: [(&str, Option, bool); 33] = [ + let entries: [(&str, Option, bool); 34] = [ ("auto_invite", row.auto_invite, false), ("webhook", webhook.map(Value::String), false), ("webhook_events", row.webhook_events.map(|e| json!(e)), true), @@ -442,6 +443,7 @@ pub async fn load_settings_document( ("color", row.color.map(Value::String), false), ("operator_settings", operator_settings, false), ("role_overrides", Some(role_overrides), true), + ("hub_access", row.hub_access, true), ( "datatable", windmill_common::workspaces::strip_datatable_permissions(row.datatable), @@ -764,6 +766,7 @@ const KNOWN_KEYS: &[&str] = &[ "color", "operator_settings", "role_overrides", + "hub_access", "datatable", "slack_team_id", "slack_name", @@ -1645,6 +1648,21 @@ fn plan_document( |v| json!({ "dbt_warehouses": v }), ); + // Normalized, so a list spelled as the endpoint would not store it is no change. + let hub_access = p + .managed("hub_access") + .map(|v| match v { + Value::Null => Ok(Value::Null), + v => roles::parse_hub_access(&v).map(|list| json!(list)), + }) + .transpose()?; + p.simple( + "hub_access", + hub_access, + Target::Edit(SettingsEdit::HubAccess), + |v| json!({ "hub_access": v }), + ); + let deploy_ui = p.managed("deploy_ui"); p.simple( "deploy_ui", diff --git a/backend/windmill-common/src/db.rs b/backend/windmill-common/src/db.rs index 6093ffa76a..25ca6a6c0b 100644 --- a/backend/windmill-common/src/db.rs +++ b/backend/windmill-common/src/db.rs @@ -37,7 +37,7 @@ impl Authed { folders: &self.folders, scopes: &self.scopes, token_prefix: &self.token_prefix, - capabilities: self.capabilities, + capabilities: self.capabilities.clone(), } } } @@ -70,7 +70,7 @@ impl Authable for AuthedRef<'_> { *self.is_operator } fn capabilities(&self) -> Option { - self.capabilities + self.capabilities.clone() } fn groups(&self) -> &[String] { self.groups @@ -111,7 +111,7 @@ impl Authable for Authed { } fn capabilities(&self) -> Option { - self.capabilities + self.capabilities.clone() } fn groups(&self) -> &[String] { diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index 4792d02e63..d5eac51b14 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -495,6 +495,9 @@ pub const ALERT_CONFIG_SETTING: &str = "alert_job_queue_waiting"; /// The instance's workspace roles (EE), a list of `crate::roles::RoleDefinition`. pub const WORKSPACE_ROLES_SETTING: &str = "workspace_roles"; +/// The instance's default `crate::roles::HubAccessList` (EE), which a workspace may replace. +pub const HUB_ACCESS_SETTING: &str = "hub_access"; + // Workspace fairness (Enterprise): caps any single workspace at // `workspace_fairness_max_percent`% of the shared worker pool once it has been // occupying it for more than `workspace_fairness_duration_secs` seconds. See diff --git a/backend/windmill-common/src/instance_config.rs b/backend/windmill-common/src/instance_config.rs index 6945064805..8ae073433a 100644 --- a/backend/windmill-common/src/instance_config.rs +++ b/backend/windmill-common/src/instance_config.rs @@ -1731,6 +1731,12 @@ pub async fn sync_global_settings_declarative( .map_err(|e| anyhow::anyhow!("{idp_key}: {e}"))?; let mut diff = diff_global_settings(current, desired, ApplyMode::Replace); + let hub_key = crate::global_settings::HUB_ACCESS_SETTING; + if let Some((_, hub_access)) = diff.upserts.iter().find(|(k, _)| k.as_str() == hub_key) { + crate::roles::validate_instance_hub_access_write(db, hub_access) + .await + .map_err(|e| anyhow::anyhow!("{hub_key}: {e}"))?; + } let roles_key = crate::global_settings::WORKSPACE_ROLES_SETTING; let roles_written = diff.upserts.iter().any(|(k, _)| k == roles_key) || diff.deletes.iter().any(|k| k == roles_key); diff --git a/backend/windmill-common/src/jobs.rs b/backend/windmill-common/src/jobs.rs index ecc2143c1c..b5fa0f4ba7 100644 --- a/backend/windmill-common/src/jobs.rs +++ b/backend/windmill-common/src/jobs.rs @@ -177,28 +177,105 @@ impl ChosenBy { } } -/// Refuses a Hub script or flow named by a member whose role cannot write code, preset handlers -/// excepted. Gated on the path, not `hub_id()`: a flow at `hub/123` has none. +/// [`check_can_name_runnables`] for a single one. pub async fn check_can_name_runnable( origin: &RunOrigin<'_>, runnable: &RunnableRef, db: &DB, w_id: &str, ) -> error::Result<()> { + check_can_name_runnables(origin, std::slice::from_ref(runnable), db, w_id) + .await + .map_err(|(_, e)| e) +} + +/// Refuses a Hub script or flow named by a member whose role cannot write code, preset handlers +/// excepted. Gated on the path, not `hub_id()`: a flow at `hub/123` has none. A role without code +/// may still name a Hub script that the workspace's Hub access list allows, as the Hub reports it: +/// approved, in a listed integration, and read-only unless it is listed at `write`. +/// +/// The error comes with the runnable it is about, if it is about one. Pass all that one request +/// names together: the Hub is asked about them at once, and a caller may hold a transaction meanwhile. +pub async fn check_can_name_runnables<'r>( + origin: &RunOrigin<'_>, + runnables: &'r [RunnableRef], + db: &DB, + w_id: &str, +) -> std::result::Result<(), (Option<&'r RunnableRef>, Error)> { + use crate::roles::HubAccess; let RunOrigin::NamedBy(authed) = origin else { return Ok(()); }; - if !runnable.path().starts_with("hub/") - || runnable.preset_handler().is_some() - || crate::roles::caller_capabilities(db, w_id, authed) - .await? - .code - { + let named: Vec<&'r RunnableRef> = runnables + .iter() + .filter(|r| r.path().starts_with("hub/") && r.preset_handler().is_none()) + .collect(); + if named.is_empty() { return Ok(()); } - Err(Error::PermissionDenied( - "Hub scripts and flows require a role that can write code. Ask a developer to deploy it to the workspace.".to_string(), - )) + let caps = crate::roles::caller_capabilities(db, w_id, authed) + .await + .map_err(|e| (None, e))?; + if caps.code { + return Ok(()); + } + let refuse = |r: &'r RunnableRef, reason: String| Err((Some(r), Error::PermissionDenied(reason))); + let mut scripts = Vec::with_capacity(named.len()); + for r in named { + match r.hub_id() { + Some(id) if !r.is_flow() && !caps.hub.is_empty() => scripts.push((r, id)), + _ => { + let reason = if r.is_flow() { + "Hub flows require a role that can write code. Ask a developer to deploy it to the workspace." + } else { + "Your role may not use this Hub script. Ask an admin to allow its integration, or a developer to deploy it to the workspace." + }; + return refuse(r, reason.to_string()); + } + } + } + let mut ids: Vec = scripts.iter().map(|(_, id)| *id).collect(); + ids.sort_unstable(); + ids.dedup(); + let metas = match crate::utils::hub_script_meta(&ids).await { + Ok(metas) => metas, + Err(Error::BadGateway(e)) => { + return Err(( + None, + Error::PermissionDenied(format!("Could not check approvals on the Hub: {e}.")), + )) + } + Err(e) => return Err((None, e)), + }; + for (r, id) in scripts { + let Some(meta) = metas.get(&id) else { + return refuse(r, format!("Hub script version {id} is not on the Hub.")); + }; + let app = &meta.app; + match caps.hub.get(&app.to_lowercase()) { + Some(HubAccess::Write) => {} + Some(HubAccess::Read) if meta.read_only => {} + Some(HubAccess::Read) => { + return refuse( + r, + format!("This Hub script can write to `{app}` and your role may only use its read-only scripts. Ask an admin to allow writing, or a developer to deploy this one to the workspace."), + ) + } + _ => { + return refuse( + r, + format!("Your role may not use the Hub scripts of `{app}`. Ask an admin to allow them, or a developer to deploy this one to the workspace."), + ) + } + } + if !(meta.script_approved && meta.version_ever_approved) { + return refuse( + r, + format!("Hub script version {id} is not approved on the Hub, so your role cannot use it."), + ); + } + } + Ok(()) } pub async fn script_path_to_payload<'e>( diff --git a/backend/windmill-common/src/roles.rs b/backend/windmill-common/src/roles.rs index f1db372cf3..68388f044f 100644 --- a/backend/windmill-common/src/roles.rs +++ b/backend/windmill-common/src/roles.rs @@ -11,7 +11,10 @@ //! computed at authentication from the role, never from `usr.operator` alone: every gate fast-paths //! on it, so a stale flag would let a restricted member through. -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::{BTreeMap, HashMap}, + sync::Arc, +}; use quick_cache::sync::Cache; use serde::{Deserialize, Serialize}; @@ -19,7 +22,7 @@ use serde::{Deserialize, Serialize}; use crate::{ db::Authable, error::{Error, Result}, - global_settings::WORKSPACE_ROLES_SETTING, + global_settings::{HUB_ACCESS_SETTING, WORKSPACE_ROLES_SETTING}, DB, }; @@ -41,6 +44,86 @@ pub enum AuthorLevel { Full, } +/// What a role without `code` may do with the Hub scripts of one integration. `Write` implies +/// `Read`: `Read` allows only versions the Hub approved as read-only. See +/// [`crate::jobs::check_can_name_runnable`]. +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +pub enum HubAccess { + Read, + Write, +} + +/// Hub integrations, lowercased, whose approved scripts a role without `code` may name. +pub type HubAccessList = BTreeMap; + +/// A [`HubAccessList`] that every role of a workspace shares. Capabilities are cloned several +/// times per request, so they hold a pointer rather than their own copy of up to every Hub +/// integration. Reads, compares and serializes as the list itself. +#[derive(Clone, Debug, Default)] +pub struct SharedHubAccess(Option>); + +impl SharedHubAccess { + pub const EMPTY: Self = Self(None); +} + +impl From for SharedHubAccess { + fn from(list: HubAccessList) -> Self { + Self((!list.is_empty()).then(|| Arc::new(list))) + } +} + +impl std::ops::Deref for SharedHubAccess { + type Target = HubAccessList; + fn deref(&self) -> &HubAccessList { + static EMPTY: HubAccessList = BTreeMap::new(); + self.0.as_deref().unwrap_or(&EMPTY) + } +} + +impl PartialEq for SharedHubAccess { + fn eq(&self, other: &Self) -> bool { + **self == **other + } +} + +impl Eq for SharedHubAccess {} + +impl std::hash::Hash for SharedHubAccess { + fn hash(&self, state: &mut H) { + (**self).hash(state) + } +} + +impl Serialize for SharedHubAccess { + fn serialize(&self, s: S) -> std::result::Result { + (**self).serialize(s) + } +} + +impl<'de> Deserialize<'de> for SharedHubAccess { + fn deserialize>(d: D) -> std::result::Result { + HubAccessList::deserialize(d).map(Self::from) + } +} + +/// Parses and normalizes a [`HUB_ACCESS_SETTING`] or `workspace_settings.hub_access` value. +/// Lowercased, since the Hub holds both `Slack` and `slack`. `/` is refused: it is reserved for +/// per-script keys, `/`. +pub fn parse_hub_access(value: &serde_json::Value) -> Result { + let raw: BTreeMap = serde_json::from_value(value.clone()) + .map_err(|e| Error::BadRequest(format!("invalid Hub access list: {e}")))?; + let mut out = HubAccessList::new(); + for (k, v) in raw { + if k.is_empty() || k.contains('/') || out.insert(k.to_lowercase(), v).is_some() { + return Err(Error::BadRequest(format!( + "invalid or repeated Hub integration `{k}`" + ))); + } + } + Ok(out) +} + /// Pages a role sees. Not enforced: hiding a page never stopped an API call, and the enforced /// rights are the other fields of [`RoleCapabilities`]. #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -84,12 +167,12 @@ impl RoleVisibility { }; } -#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] pub struct RoleCapabilities { /// Author scripts and run code of one's own on a worker: script previews, dependency jobs, /// dynamic selects, resolving a job's code, data table migrations. `Full` flows or apps /// require it, since both carry inline code. Previews also need `run`. Also required to name - /// a Hub script or flow at run time (preset handlers excepted), see + /// a Hub script or flow at run time (preset handlers excepted, and scripts `hub` lists), see /// [`crate::jobs::check_can_name_runnable`]. pub code: bool, pub flows: AuthorLevel, @@ -105,6 +188,10 @@ pub struct RoleCapabilities { /// by every layer, it is granted exactly to an unrestricted role (see [`Self::resolve`]). pub fork: bool, pub visibility: RoleVisibility, + /// The Hub scripts a role without `code` may name. Not a setting of the role: filled in from + /// the workspace's [`HubAccessList`] by [`workspace_roles`], and empty on a role with `code`. + #[serde(default)] + pub hub: SharedHubAccess, } impl RoleCapabilities { @@ -117,6 +204,7 @@ impl RoleCapabilities { run: true, fork: true, visibility: RoleVisibility::ALL, + hub: SharedHubAccess::EMPTY, }; /// The `operator` role as it stood before roles were configurable, and the base any other @@ -130,6 +218,7 @@ impl RoleCapabilities { run: true, fork: false, visibility: RoleVisibility::ALL, + hub: SharedHubAccess::EMPTY, }; /// For a restricted caller whose role cannot be resolved: a guest, a removed member's job, a @@ -143,6 +232,7 @@ impl RoleCapabilities { run: false, fork: false, visibility: RoleVisibility::NONE, + hub: SharedHubAccess::EMPTY, }; /// What a role named `name` holds before any configuration applies. @@ -159,7 +249,7 @@ impl RoleCapabilities { /// left out: it only hides pages, and must not turn a full author into an operator for the /// raw `is_operator` checks, job permissions and credential caches keyed on it. pub fn is_restricted(&self) -> bool { - Self { visibility: RoleVisibility::ALL, fork: true, ..*self } != Self::FULL + Self { visibility: RoleVisibility::ALL, fork: true, ..self.clone() } != Self::FULL } /// Whether the role authors deployable artifacts and so costs a full seat rather than half. @@ -643,6 +733,50 @@ pub async fn load_role_overrides<'c, E: sqlx::PgExecutor<'c>>( } } +/// The Hub access lists that meet in a workspace. +pub struct HubAccessLists { + pub instance: HubAccessList, + /// `None` follows the instance; an empty list allows nothing. + pub workspace: Option, +} + +impl HubAccessLists { + pub fn effective(self) -> HubAccessList { + self.workspace.unwrap_or(self.instance) + } +} + +/// A stored list that does not parse allows nothing. Reads as the server: the caller must already +/// be a member of `workspace_id`, or act for the server itself. +pub async fn load_hub_access( + conn: &mut sqlx::PgConnection, + workspace_id: &str, +) -> Result { + let (instance, workspace): (Option, Option) = + sqlx::query_as( + "SELECT (SELECT value FROM global_settings WHERE name = $1), + (SELECT hub_access FROM workspace_settings WHERE workspace_id = $2)", + ) + .bind(HUB_ACCESS_SETTING) + .bind(workspace_id) + .fetch_one(conn) + .await?; + let parse = |v: Option| { + v.filter(|v| !v.is_null()).map(|v| { + parse_hub_access(&v).unwrap_or_else(|e| { + tracing::error!("ignoring invalid Hub access list: {e:#}"); + HubAccessList::new() + }) + }) + }; + // As for the instance's roles, a CE build has none. + let instance = instance.filter(|_| custom_roles_built()); + Ok(HubAccessLists { + instance: parse(instance).unwrap_or_default(), + workspace: parse(workspace), + }) +} + fn cached_workspace_roles(workspace_id: &str) -> Option>> { let now = chrono::Utc::now().timestamp(); WORKSPACE_ROLES @@ -651,8 +785,8 @@ fn cached_workspace_roles(workspace_id: &str) -> Option>> .map(|(r, _)| r) } -/// The roles of `workspace_id`. Cached 60s; `role_overrides` writes and the instance setting drop -/// the entry on every replica. +/// The roles of `workspace_id`. Cached 60s; `role_overrides` and `hub_access` writes and the instance +/// settings drop the entry on every replica. /// /// Call it before opening an RLS transaction: on a cache miss it takes a connection from the root /// pool, and a second pooled connection held alongside a transaction self-deadlocks on a @@ -674,7 +808,12 @@ pub async fn workspace_roles_on( } let instance = instance_roles_on(&mut *conn).await?; let overrides = load_role_overrides(&mut *conn, workspace_id).await?; - let roles = Arc::new(effective_roles(&instance, &overrides)?); + let hub = SharedHubAccess::from(load_hub_access(&mut *conn, workspace_id).await?.effective()); + let mut roles = effective_roles(&instance, &overrides)?; + for role in roles.iter_mut().filter(|r| !r.capabilities.code) { + role.capabilities.hub = hub.clone(); + } + let roles = Arc::new(roles); WORKSPACE_ROLES.insert( workspace_id.to_string(), ( @@ -719,9 +858,7 @@ pub async fn member_is_restricted( .await? .iter() .find(|r| r.name == name) - .map(|r| r.capabilities) - .unwrap_or(RoleCapabilities::NONE) - .is_restricted()) + .map_or(true, |r| r.capabilities.is_restricted())) } /// [`member_is_restricted`] for a caller holding no connection. @@ -819,8 +956,8 @@ pub fn invalidate_workspace_roles_cache(workspace_id: &str) { pub const ROLE_OVERRIDES_CHANGE_CHANNEL: &str = "notify_role_overrides_change"; /// Tells every replica to drop its cached roles for the workspace. Call it in the transaction -/// that writes `role_overrides`: a replica that missed it keeps authorizing whatever the workspace -/// just withdrew until its entry expires. +/// that writes `role_overrides` or `hub_access`: a replica that missed it keeps authorizing whatever +/// the workspace just withdrew until its entry expires. pub async fn notify_role_overrides_change( conn: &mut sqlx::PgConnection, workspace_id: &str, @@ -961,6 +1098,28 @@ pub async fn validate_instance_roles_write( Ok(()) } +/// Checks a write of [`HUB_ACCESS_SETTING`] before it is stored. Every writer of the setting must +/// call it, the declarative config sync included. Without a license the stored list is frozen: +/// it can be cleared or written back unchanged. +pub async fn validate_instance_hub_access_write(db: &DB, value: &serde_json::Value) -> Result<()> { + if value.is_null() { + return Ok(()); + } + let next = parse_hub_access(value)?; + if custom_roles_enabled() { + return Ok(()); + } + let current = + crate::global_settings::load_value_from_global_settings(db, HUB_ACCESS_SETTING).await?; + if next.is_empty() || current.and_then(|v| parse_hub_access(&v).ok()) == Some(next) { + return Ok(()); + } + Err(Error::BadRequest( + "changing the instance's Hub scripts requires a valid Windmill Enterprise Edition license" + .to_string(), + )) +} + /// Side effects of a stored `workspace_roles` write, owed by every writer. The seat table is read /// by billing on every replica, so it is rebuilt here rather than on the notify that drops the /// role caches. @@ -1092,6 +1251,27 @@ mod tests { assert!(op.capabilities.is_author()); } + #[test] + fn hub_access_list_is_the_workspaces_own_or_the_instances() { + let parse = |v| parse_hub_access(&v); + let instance = parse(serde_json::json!({"Slack": "read"})).unwrap(); + assert_eq!(instance.get("slack"), Some(&HubAccess::Read)); + for bad in [ + serde_json::json!({"slack/12": "read"}), + serde_json::json!({"": "read"}), + serde_json::json!({"Slack": "read", "slack": "write"}), + serde_json::json!({"slack": "none"}), + ] { + assert!(parse(bad.clone()).is_err(), "{bad}"); + } + let effective = + |workspace| HubAccessLists { instance: instance.clone(), workspace }.effective(); + assert_eq!(effective(None), instance); + assert_eq!(effective(Some(HubAccessList::new())), HubAccessList::new()); + let own = parse(serde_json::json!({"gmail": "write"})).unwrap(); + assert_eq!(effective(Some(own.clone())), own); + } + #[test] fn unset_fork_follows_restriction() { let instance: Vec = serde_json::from_value(serde_json::json!([ diff --git a/backend/windmill-common/src/scripts.rs b/backend/windmill-common/src/scripts.rs index 79a2065354..95438e4fdb 100644 --- a/backend/windmill-common/src/scripts.rs +++ b/backend/windmill-common/src/scripts.rs @@ -22,7 +22,7 @@ use backon::ConstantBuilder; use backon::{BackoffBuilder, Retryable}; use regex::Regex; -use crate::utils::{parse_hub_id, StripPath}; +use crate::utils::{calculate_hash, parse_hub_id, StripPath}; /// The tag a script's dependency job runs on, given the script's own tag; `None` leaves it to /// `push`'s default (the language tag). Every relock of a script must use this, or a relock @@ -247,6 +247,17 @@ pub async fn get_full_hub_script_by_path( get_full_hub_script_by_id(parse_hub_id(path.to_path(), "hub/")?, http_client, db).await } +/// The name a version is cached under. Private Hubs number their scripts alike, so theirs carry +/// the Hub: what [`crate::jobs::check_can_name_runnables`] read from the configured Hub must not +/// admit a script cached from another. Public ones keep the bare id, which images ship. +fn hub_cache_name(hub_base_url: &str, version: i32) -> String { + if version < PRIVATE_HUB_MIN_VERSION { + version.to_string() + } else { + format!("{version}-{}", &calculate_hash(hub_base_url)[..16]) + } +} + /// Performs no authorization and uses the instance's Hub credentials and shared cache: the caller /// must already have decided this user may run or read this script. pub async fn get_full_hub_script_by_id( @@ -257,7 +268,9 @@ pub async fn get_full_hub_script_by_id( // A cache entry that cannot be read or parsed counts as a miss rather than an error: // a truncated write leaves a file that exists but deserializes to nothing, and refetching // it is always preferable to failing the job push it was read for. - let cache_path = format!("{}/{version}", *HUB_CACHE_DIR); + let hub_base_url = (**HUB_BASE_URL.load()).clone(); + let cache_name = hub_cache_name(&hub_base_url, version); + let cache_path = format!("{}/{cache_name}", *HUB_CACHE_DIR); let cached = match tokio::fs::read_to_string(&cache_path).await { Ok(content) => serde_json::from_str::(&content) .inspect_err(|e| { @@ -276,10 +289,10 @@ pub async fn get_full_hub_script_by_id( return Ok(script); } - let script = fetch_hub_script(version, http_client, db).await?; + let script = fetch_hub_script(&hub_base_url, version, http_client, db).await?; if let Err(e) = crate::worker::write_file( &HUB_CACHE_DIR, - &version.to_string(), + &cache_name, &serde_json::to_string(&script).map_err(to_anyhow)?, ) { tracing::error!("failed to write hub script {version} to cache: {e}"); @@ -290,12 +303,11 @@ pub async fn get_full_hub_script_by_id( } async fn fetch_hub_script( + hub_base_url: &str, id: i32, http_client: &reqwest::Client, db: Option<&DB>, ) -> crate::error::Result { - let hub_base_url = (**HUB_BASE_URL.load()).clone(); - let response = (|| async { let response = http_get_from_hub( http_client, diff --git a/backend/windmill-common/src/utils.rs b/backend/windmill-common/src/utils.rs index 343d4d0d05..3648069e0e 100644 --- a/backend/windmill-common/src/utils.rs +++ b/backend/windmill-common/src/utils.rs @@ -629,22 +629,7 @@ pub async fn http_get_from_hub( None => None, }; - let mut request = http_client.get(url).header( - "Accept", - if plain { - "text/plain" - } else { - "application/json" - }, - ); - - if let Some(uid) = uid { - request = request.header("X-uid", uid); - } - - if let Some(hub_api_secret) = (**HUB_API_SECRET.load()).clone() { - request = request.header("X-api-secret", hub_api_secret); - } + let mut request = hub_request(http_client, url, plain, uid); if let Some(query_params) = query_params { for (key, value) in query_params { @@ -660,6 +645,137 @@ pub async fn http_get_from_hub( Ok(response) } +fn hub_request( + http_client: &reqwest::Client, + url: &str, + plain: bool, + uid: Option, +) -> reqwest::RequestBuilder { + let mut request = http_client.get(url).header( + "Accept", + if plain { + "text/plain" + } else { + "application/json" + }, + ); + if let Some(uid) = uid { + request = request.header("X-uid", uid); + } + if let Some(hub_api_secret) = (**HUB_API_SECRET.load()).clone() { + request = request.header("X-api-secret", hub_api_secret); + } + request +} + +/// What the Hub says about one script version, for [`crate::jobs::check_can_name_runnable`]. +#[derive(Deserialize, Clone, Debug)] +pub struct HubScriptMeta { + pub version_id: i32, + /// The integration, as the Hub spells it ("Slack" and "slack" both occur). + pub app: String, + /// Absent on a version the Hub never flagged, which counts as able to write. + #[serde(default)] + pub read_only: bool, + pub script_approved: bool, + pub version_ever_approved: bool, +} + +lazy_static::lazy_static! { + /// Keyed by the configured Hub too, so a changed `hub_base_url` is not answered from the old one. + static ref HUB_SCRIPT_META: quick_cache::sync::Cache<(String, i32), (HubScriptMeta, std::time::Instant)> = + quick_cache::sync::Cache::new(10_000); +} + +static INSTANCE_UID: std::sync::OnceLock = std::sync::OnceLock::new(); + +const HUB_SCRIPT_META_TTL: std::time::Duration = std::time::Duration::from_secs(300); + +/// The Hub's metadata of each known version in `ids`; unknown ones are left out. Cached per version +/// for [`HUB_SCRIPT_META_TTL`], so an unapproval takes up to that long to be seen. +/// +/// Takes no pool connection: it runs inside save transactions, where a second one held alongside +/// self-deadlocks on a one-connection pool. The `X-uid` it sends is read from memory, so a server +/// that never read its uid yet sends none. +pub async fn hub_script_meta(ids: &[i32]) -> Result> { + let hub = (**crate::HUB_BASE_URL.load()).clone(); + let mut out = std::collections::HashMap::new(); + let mut missing = vec![]; + for &id in ids { + match HUB_SCRIPT_META.get(&(hub.clone(), id)) { + Some((m, at)) if at.elapsed() < HUB_SCRIPT_META_TTL => { + out.insert(id, m); + } + _ => missing.push(id), + } + } + if missing.is_empty() { + return Ok(out); + } + let mut found = fetch_hub_script_meta(&hub, &missing).await?; + if hub != crate::DEFAULT_HUB_BASE_URL { + // Same fallback as the script fetch: low ids a private Hub lacks are public Hub scripts. + let public: Vec = missing + .into_iter() + .filter(|id| { + *id < crate::PRIVATE_HUB_MIN_VERSION && !found.iter().any(|m| m.version_id == *id) + }) + .collect(); + if !public.is_empty() { + found.extend(fetch_hub_script_meta(crate::DEFAULT_HUB_BASE_URL, &public).await?); + } + } + let now = std::time::Instant::now(); + for m in found { + HUB_SCRIPT_META.insert((hub.clone(), m.version_id), (m.clone(), now)); + out.insert(m.version_id, m); + } + Ok(out) +} + +/// The Hub's URL goes to the log only: a private Hub's address is not every member's business. +fn hub_meta_err(hub: &str, what: &str, e: impl Display) -> Error { + tracing::warn!("hub script access lookup at {hub}: {what}: {e}"); + Error::BadGateway(what.to_string()) +} + +async fn fetch_hub_script_meta(hub: &str, ids: &[i32]) -> Result> { + let uid = match (**LICENSE_KEY_ID.load()).clone() { + id if !id.is_empty() => Some(id), + _ => INSTANCE_UID.get().cloned(), + }; + let mut out = vec![]; + for chunk in ids.chunks(100) { + let resp = hub_request( + &HTTP_CLIENT, + &format!("{hub}/scripts/access_meta"), + false, + uid.clone(), + ) + .query(&[("ids", chunk.iter().join(","))]) + .timeout(std::time::Duration::from_secs(5)) + .send() + .await + .map_err(|e| hub_meta_err(hub, "the Hub is unreachable", e))?; + if resp.status() == reqwest::StatusCode::NOT_FOUND { + return Err(hub_meta_err( + hub, + "the Hub cannot report script approvals and needs an update", + "404", + )); + } + let resp = resp + .error_for_status() + .map_err(|e| hub_meta_err(hub, "the Hub failed", e))?; + out.extend( + resp.json::>() + .await + .map_err(|e| hub_meta_err(hub, "the Hub answered badly", e))?, + ); + } + Ok(out) +} + pub fn rd_string(len: usize) -> String { rng() .sample_iter(&Alphanumeric) @@ -697,6 +813,7 @@ pub async fn get_instance_uid<'c, E: sqlx::Executor<'c, Database = Postgres>>( .await?; let uid = serde_json::from_value::(uid_value).map_err(to_anyhow)?; + let _ = INSTANCE_UID.set(uid.clone()); Ok(uid) } diff --git a/backend/windmill-common/tests/workspace_roles_license.rs b/backend/windmill-common/tests/workspace_roles_license.rs index 88aa3593cb..d8cfc5f57a 100644 --- a/backend/windmill-common/tests/workspace_roles_license.rs +++ b/backend/windmill-common/tests/workspace_roles_license.rs @@ -1,13 +1,14 @@ #![cfg(feature = "enterprise")] //! Flips the process-wide `LICENSE_KEY_VALID`, so it keeps a test binary of its own. -use std::sync::atomic::Ordering; +use std::{collections::BTreeMap, sync::atomic::Ordering}; use sqlx::{Pool, Postgres}; use windmill_common::ee_oss::LICENSE_KEY_VALID; +use windmill_common::instance_config::sync_global_settings_declarative; use windmill_common::roles::{ self, check_frozen_overrides, instance_roles, load_role_overrides, - validate_instance_roles_write, RoleOverrides, + validate_instance_hub_access_write, validate_instance_roles_write, RoleOverrides, }; /// A lapsed license freezes the configured roles: falling back to the defaults would give a @@ -65,6 +66,39 @@ async fn lapsed_license_freezes_roles(db: Pool) { check_frozen_overrides(&instance, &previous, &RoleOverrides::new()) .expect("removing a workspace-only role stays open"); + // The instance's Hub access list is frozen the same way, and can always be cleared. + let slack = BTreeMap::from([( + "hub_access".to_string(), + serde_json::json!({"slack": "read"}), + )]); + sync_global_settings_declarative(&db, &BTreeMap::new(), &slack, &()) + .await + .expect_err("changing the instance's Hub scripts needs a license"); + validate_instance_hub_access_write(&db, &serde_json::json!({})) + .await + .expect("clearing stays open"); + + LICENSE_KEY_VALID.store(true, Ordering::Relaxed); + sync_global_settings_declarative(&db, &BTreeMap::new(), &slack, &()) + .await + .expect("licensed again"); + validate_instance_hub_access_write(&db, &serde_json::json!({"slack/x": "read"})) + .await + .expect_err("a license does not let a malformed list through"); + LICENSE_KEY_VALID.store(false, Ordering::Relaxed); + validate_instance_hub_access_write(&db, &serde_json::json!({"Slack": "read"})) + .await + .expect("writing the stored list back unchanged stays open"); + validate_instance_hub_access_write(&db, &serde_json::json!({"slack": "write"})) + .await + .expect_err("changing the stored list still needs a license"); + roles::invalidate_all_roles_cache(); + let ws = roles::workspace_roles(&db, "test-workspace").await.unwrap(); + let dev = ws.iter().find(|r| r.name == "developer").unwrap(); + assert!( + dev.capabilities.hub.contains_key("slack"), + "the stored list keeps applying" + ); LICENSE_KEY_VALID.store(true, Ordering::Relaxed); check_frozen_overrides(&instance, &previous, &relabelled).expect("licensed again"); } diff --git a/backend/windmill-queue/tests/schedule_push.rs b/backend/windmill-queue/tests/schedule_push.rs index 7de6be09ff..aadb733e1c 100644 --- a/backend/windmill-queue/tests/schedule_push.rs +++ b/backend/windmill-queue/tests/schedule_push.rs @@ -1880,7 +1880,7 @@ mod schedule_push { #[sqlx::test(migrations = "../migrations", fixtures("base", "schedule_push"))] async fn test_push_hub_script_schedule(db: Pool) -> anyhow::Result<()> { // Seed the hub cache so the push resolves the script without the network. - let version = "990000001"; + let version = "9990001"; let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR; tokio::fs::create_dir_all(hub_dir).await?; tokio::fs::write( diff --git a/backend/windmill-test-utils/src/lib.rs b/backend/windmill-test-utils/src/lib.rs index 5f804cee75..21990169ef 100644 --- a/backend/windmill-test-utils/src/lib.rs +++ b/backend/windmill-test-utils/src/lib.rs @@ -1173,3 +1173,44 @@ pub fn parse_dedicated_worker_line(line: &str) -> DedicatedWorkerResult { DedicatedWorkerResult::Other(line.to_string()) } + +/// A Hub serving `GET /scripts/access_meta` from `rows`, each a version's metadata, and for every +/// script a bash one echoing the Hub's URL, set as the instance's Hub. Returns its URL and the +/// number of lookups it served. +pub async fn start_stub_hub( + rows: Vec, +) -> (String, std::sync::Arc) { + use std::sync::{atomic::AtomicUsize, Arc}; + let calls = Arc::new(AtomicUsize::new(0)); + let served = calls.clone(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let script = serde_json::json!({ "content": format!("echo {url}"), "lockfile": null, + "language": "bash", "schema": {}, "summary": null }); + let app = axum::Router::new() + .route( + "/scripts/access_meta", + axum::routing::get( + move |axum::extract::Query(q): axum::extract::Query< + std::collections::HashMap, + >| async move { + served.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let ids: Vec = + q["ids"].split(',').filter_map(|s| s.parse().ok()).collect(); + let known: Vec<_> = rows + .iter() + .filter(|r| ids.contains(&r["version_id"].as_i64().unwrap())) + .cloned() + .collect(); + axum::Json(known) + }, + ), + ) + .route( + "/raw2/{id}/script", + axum::routing::get(move || async move { axum::Json(script) }), + ); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + windmill_common::HUB_BASE_URL.store(Arc::new(url.clone())); + (url, calls) +} diff --git a/cli/src/core/settings.ts b/cli/src/core/settings.ts index 1546902fbe..754e5a5161 100644 --- a/cli/src/core/settings.ts +++ b/cli/src/core/settings.ts @@ -63,6 +63,7 @@ export interface SimplifiedSettings { color?: string; operator_settings?: any; role_overrides?: any; + hub_access?: any; datatable?: any; slack_team_id?: string; slack_name?: string; @@ -96,6 +97,7 @@ export const SETTINGS_MANAGED_ONLY_WHEN_PRESENT = [ "add_admins_and_developers_to_forks", "variable_expiration_handler", "role_overrides", + "hub_access", "webhook_events", ] as const; diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index ff00734e20..3c4a01310e 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -8667,6 +8667,7 @@ write a secret you were not given: keep the placeholder. | \`default_scripts\` | \`{ order?, hidden?, default_script_content? }\` for the script language picker. | | \`deploy_ui\` | \`{ include_path?, include_type? }\`: what the deploy-to-workspace UI offers. | | \`role_overrides\` | \`{ : { label?, capabilities, workspace_only? } }\`: the workspace's overrides of the instance's roles, and with \`workspace_only: true\` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in \`role_overrides.operator\`. | +| \`hub_access\` | \`{ : read \\| write }\`: the Hub scripts members without code may use, replacing the instance's list. \`null\` uses the instance's list; \`{}\` allows none. | | \`operator_settings\` | Legacy view of the \`operator\` role, kept for older servers: page visibility flags (\`runs\`, \`schedules\`, \`resources\`, \`variables\`, \`assets\`, \`audit_logs\`, \`groups\`, \`folders\`, \`workers\`, \`triggers\`) and write rights (\`manage_schedules\`, \`manage_triggers\`, \`builder_flows\`, \`builder_apps\`). Not applied when the document also states \`role_overrides\`. | | \`mute_critical_alerts\` | Mute the workspace's critical alerts. | | \`slack_team_id\`, \`slack_name\` | Read only: set by connecting Slack on the settings page. | @@ -8689,7 +8690,7 @@ only show them, \`-y\` to skip the question, \`--replace\` to clear what the fil With \`includeSettings: true\` in \`wmill.yaml\`, \`wmill sync pull\` writes the document to \`settings.yaml\`, secrets encrypted with the workspace key (plaintext only with \`plainSecrets\`), and \`wmill sync push\` applies it. Unlike a partial apply, a push treats the file as the whole -document: a setting the file omits is cleared, except \`operator_settings\`, \`role_overrides\`, \`color\`, the auto-invite +document: a setting the file omits is cleared, except \`operator_settings\`, \`role_overrides\`, \`hub_access\`, \`color\`, the auto-invite instance groups, and the keys \`ducklake\`, \`dbt_warehouses\`, \`deploy_ui\`, \`teams_command_script\`, \`public_app_execution_limit_per_minute\`, \`guest_jwt_public_key\`, \`guest_jwt_jwks_url\`, \`error_handler_fallback_to_instance_alerts\` and diff --git a/docs/operator-builder-rights.md b/docs/operator-builder-rights.md index d2786df83c..99bec62615 100644 --- a/docs/operator-builder-rights.md +++ b/docs/operator-builder-rights.md @@ -57,8 +57,9 @@ permissions: it as whoever it runs as: `validate_operator_composed_flow` re-checks each path under the caller's RLS. This is the general case; the one below is on top of it, not instead of it. A Hub step has no workspace row to read, so it is collected apart and held to the run-time rule - for naming a Hub path (`check_can_name_runnable`) against the builder: Hub steps follow the - `code` capability, and preset handlers are allowed to every role. + for naming a Hub path (`check_can_name_runnable`) against the builder: Hub steps need + the `code` capability or the Hub access list (`docs/workspace-roles.md`, "Hub scripts"), and preset + handlers are allowed to every role. - **the `(path, hash)` of every version-pinned step**. A step carrying a `hash` is dispatched by that hash alone, with the path beside it never consulted, so a readable path paired with another script's hash still runs that other script. @@ -92,7 +93,7 @@ that function. The same reasoning applies to a builder-authored app, with one extra step. `execute_component` resolves the runnable it runs on the root handle, so `validate_operator_composed_app` checks every referenced path under the caller's RLS and holds a Hub one to `check_can_name_runnable`, as in a -flow, so Hub steps follow the `code` capability. For a script it checks the version a +flow, so Hub steps need `code` or the Hub access list. For a script it checks the version a run would pick: grants are per version, and a path reused after its versions were archived starts with none while the archived ones keep theirs. But it has to check **two** surfaces, because they are not the same list: the policy's `script/`, `flow/` and diff --git a/docs/operator-write-rights.md b/docs/operator-write-rights.md index 89d5b15830..ec1e6da825 100644 --- a/docs/operator-write-rights.md +++ b/docs/operator-write-rights.md @@ -57,12 +57,14 @@ app rather than telling them why. Both integration tests assert the status for t ## Hub paths in triggers and schedules Whatever write rights they hold, a member without `code` cannot save a new Hub path into a trigger, -a schedule or a WebSocket capture config (`check_new_hub_paths`). Paths already saved keep working, +a schedule or a WebSocket capture config (`check_new_hub_paths`), unless the Hub +access list allows that script (see `docs/workspace-roles.md`, "Hub scripts", for the list and its +refusal reasons). Paths already saved keep working, and are not rechecked when the trigger or schedule is edited, even when the edit moves one between a trigger's fields (an error handler to the main script) or among a schedule's handlers; a handler cannot take the schedule's Hub target. The edit makes the editor its run-as identity unless they may keep the stored one (admins, `wm_deployers`), so a saved Hub path then runs as the editor, with -the arguments they save: accepted so that rows a member with `code` set up stay editable, since the +the arguments they save: accepted so that rows set up by a member who could name the path stay editable, since the choice of which Hub code runs stays with that member. ## Drafts diff --git a/docs/workspace-roles.md b/docs/workspace-roles.md index 02db77c3f8..e76b35ea37 100644 --- a/docs/workspace-roles.md +++ b/docs/workspace-roles.md @@ -35,6 +35,37 @@ deleting one that a member, invite, auto-invite or instance group mapping still and so is deleting an instance role that a workspace still overrides (the override would fall onto `base_for` instead of the definition it was written against). +## Hub scripts + +A role without `code` may not name a Hub script or flow (`check_can_name_runnable`), except the +Hub scripts a list allows: `{ : read | write }`, the integration being the script's +`app`. It is the same for every role without `code`. The instance has one (the `hub_access` global +setting, EE and frozen without a license like the roles, though it can always be cleared), and a +workspace may replace it as a whole (`workspace_settings.hub_access`): `NULL` follows the +instance's, an own list does not merge with it, and an empty one allows nothing. Keys are +lowercased, since the Hub has both `Slack` and `slack`, and one containing `/` is refused, as +`/` is reserved for per-script entries. Forks copy the workspace's list. + +`workspace_roles_on` puts the list that applies on `RoleCapabilities::hub` of each role without +`code`, so it is cached and loaded with the role and the rule reads nothing else; a per-role layer +would go there too. It is not part of `RoleCapabilitiesPatch`, so no role setting holds it and +`diff_capabilities` ignores it. + +When `hub` is non-empty, naming `hub//…` asks the Hub (`hub_script_meta`, `GET +{hub}/scripts/access_meta`, cached 5 minutes per version, with the private Hub's fallback to the +public one for ids below `PRIVATE_HUB_MIN_VERSION`), and allows it when the version's `app` (from +the Hub, never the path) is listed at `write`, or at `read` and the version is read-only, and the +script is approved and this version was ever approved. A version with no flag can write. Refused +otherwise, saying which: integration not allowed, script can write but is allowed at read, +version not approved or not on the Hub, or the Hub unreachable or too old to answer. An empty +list refuses without asking. Hub flows stay code-only. The UI offers less than the server +allows: the flow, app and schedule pickers and the AI chat (MCP instructions included) still follow +`code` alone. + +The lookup takes no pool connection, since it runs inside save transactions (see +`hub_script_meta`). The check runs when a path is chosen, never when something saved fires, so a +saved flow, trigger or schedule keeps running after an integration is withdrawn or a script unapproved. + ## Runs `run` withdrawn makes a role view-only: its members see what folder and item rights grant, diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index c618e8b9b4..a1d3d2bce5 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -2449,7 +2449,7 @@ export function getInstructions( external = false, /** The session cannot run a flow preview, which an agent's test run is. */ untestable = false, - /** The role has code, which the server requires to add a hub path. */ + /** The role has code, so it may add any hub path. The Hub access list is not offered here. */ hub = true ): string | Promise { switch (subject) { diff --git a/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte b/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte index a71173a809..e671ec5caf 100644 --- a/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte +++ b/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte @@ -302,7 +302,8 @@ : [] ) - // The server adds a hub path only for a role that has code, whatever its flows level. + // Whatever its flows level, a role needs code to add any hub path. The Hub access list, which the + // server also accepts, is not offered here. let showHub = $derived($roleCaps.code) // Every result row lives in one keyboard index space, and hovering a row moves that index, so diff --git a/frontend/src/lib/components/flows/map/InsertModuleInner.svelte b/frontend/src/lib/components/flows/map/InsertModuleInner.svelte index e9cb7e27fb..d284e406bc 100644 --- a/frontend/src/lib/components/flows/map/InsertModuleInner.svelte +++ b/frontend/src/lib/components/flows/map/InsertModuleInner.svelte @@ -60,7 +60,8 @@ | 'failure' | 'aisandbox' | 'aiagent' = $state(untrack(() => kind)) - // The server adds a hub path only for a role that has code, so without it never open on the hub. + // A role needs code to add any hub path, so without it never open on the hub. The Hub access list, + // which the server also accepts, is not offered here. let preFilter: 'all' | 'workspace' | 'hub' = $state( untrack(() => $roleCaps.code) ? 'all' : 'workspace' ) diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index e25d351740..848ff64159 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -1641,6 +1641,7 @@ write a secret you were not given: keep the placeholder. | \`default_scripts\` | \`{ order?, hidden?, default_script_content? }\` for the script language picker. | | \`deploy_ui\` | \`{ include_path?, include_type? }\`: what the deploy-to-workspace UI offers. | | \`role_overrides\` | \`{ : { label?, capabilities, workspace_only? } }\`: the workspace's overrides of the instance's roles, and with \`workspace_only: true\` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in \`role_overrides.operator\`. | +| \`hub_access\` | \`{ : read \\| write }\`: the Hub scripts members without code may use, replacing the instance's list. \`null\` uses the instance's list; \`{}\` allows none. | | \`operator_settings\` | Legacy view of the \`operator\` role, kept for older servers: page visibility flags (\`runs\`, \`schedules\`, \`resources\`, \`variables\`, \`assets\`, \`audit_logs\`, \`groups\`, \`folders\`, \`workers\`, \`triggers\`) and write rights (\`manage_schedules\`, \`manage_triggers\`, \`builder_flows\`, \`builder_apps\`). Not applied when the document also states \`role_overrides\`. | | \`mute_critical_alerts\` | Mute the workspace's critical alerts. | | \`slack_team_id\`, \`slack_name\` | Read only: set by connecting Slack on the settings page. | diff --git a/system_prompts/auto-generated/skills/workspace-settings/SKILL.md b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md index 6fbff099fc..637a75136d 100644 --- a/system_prompts/auto-generated/skills/workspace-settings/SKILL.md +++ b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md @@ -54,6 +54,7 @@ write a secret you were not given: keep the placeholder. | `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. | | `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. | | `role_overrides` | `{ : { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. | +| `hub_access` | `{ : read \| write }`: the Hub scripts members without code may use, replacing the instance's list. `null` uses the instance's list; `{}` allows none. | | `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. | | `mute_critical_alerts` | Mute the workspace's critical alerts. | | `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. | @@ -76,7 +77,7 @@ only show them, `-y` to skip the question, `--replace` to clear what the file om With `includeSettings: true` in `wmill.yaml`, `wmill sync pull` writes the document to `settings.yaml`, secrets encrypted with the workspace key (plaintext only with `plainSecrets`), and `wmill sync push` applies it. Unlike a partial apply, a push treats the file as the whole -document: a setting the file omits is cleared, except `operator_settings`, `role_overrides`, `color`, the auto-invite +document: a setting the file omits is cleared, except `operator_settings`, `role_overrides`, `hub_access`, `color`, the auto-invite instance groups, and the keys `ducklake`, `dbt_warehouses`, `deploy_ui`, `teams_command_script`, `public_app_execution_limit_per_minute`, `guest_jwt_public_key`, `guest_jwt_jwks_url`, `error_handler_fallback_to_instance_alerts` and diff --git a/system_prompts/base/workspace-settings.md b/system_prompts/base/workspace-settings.md index d37a501ff9..df8f7cb789 100644 --- a/system_prompts/base/workspace-settings.md +++ b/system_prompts/base/workspace-settings.md @@ -49,6 +49,7 @@ write a secret you were not given: keep the placeholder. | `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. | | `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. | | `role_overrides` | `{ : { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. | +| `hub_access` | `{ : read \| write }`: the Hub scripts members without code may use, replacing the instance's list. `null` uses the instance's list; `{}` allows none. | | `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. | | `mute_critical_alerts` | Mute the workspace's critical alerts. | | `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. | @@ -72,7 +73,7 @@ only show them, `-y` to skip the question, `--replace` to clear what the file om With `includeSettings: true` in `wmill.yaml`, `wmill sync pull` writes the document to `settings.yaml`, secrets encrypted with the workspace key (plaintext only with `plainSecrets`), and `wmill sync push` applies it. Unlike a partial apply, a push treats the file as the whole -document: a setting the file omits is cleared, except `operator_settings`, `role_overrides`, `color`, the auto-invite +document: a setting the file omits is cleared, except `operator_settings`, `role_overrides`, `hub_access`, `color`, the auto-invite instance groups, and the keys `ducklake`, `dbt_warehouses`, `deploy_ui`, `teams_command_script`, `public_app_execution_limit_per_minute`, `guest_jwt_public_key`, `guest_jwt_jwks_url`, `error_handler_fallback_to_instance_alerts` and