From 93ff437332b16f7ea09e28cf1099e1e4bd158f7a Mon Sep 17 00:00:00 2001 From: Alexander Petric Date: Thu, 29 Oct 2026 19:50:40 +0000 Subject: [PATCH] fix: carry workspace role overrides in the synced settings document Co-Authored-By: Claude Opus 5.5 --- .../tests/role_overrides_sync.rs | 294 ++++++++++ .../windmill-api-workspaces/src/workspaces.rs | 7 + .../src/mcp/session/gen/instructions.json | 2 +- .../src/workspace_settings_document.rs | 524 ++++++++++++++++-- cli/src/core/settings.ts | 4 + cli/src/guidance/skills.gen.ts | 6 +- cli/test/role_overrides_settings_sync.test.ts | 141 +++++ cli/test/settings_unit.test.ts | 19 + docs/workspace-roles.md | 10 + system_prompts/auto-generated/prompts.ts | 2 + .../skills/workspace-settings/SKILL.md | 6 +- system_prompts/base/workspace-settings.md | 6 +- 12 files changed, 983 insertions(+), 38 deletions(-) create mode 100644 backend/windmill-api-integration-tests/tests/role_overrides_sync.rs create mode 100644 cli/test/role_overrides_settings_sync.test.ts diff --git a/backend/windmill-api-integration-tests/tests/role_overrides_sync.rs b/backend/windmill-api-integration-tests/tests/role_overrides_sync.rs new file mode 100644 index 0000000000..6c568fa07b --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/role_overrides_sync.rs @@ -0,0 +1,294 @@ +//! Workspace role overrides travel in the settings document that workspace export, `wmill sync` +//! and git sync carry, and come back through its apply. + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +fn client() -> reqwest::Client { + reqwest::Client::new() +} + +fn authed(builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder { + builder.header("Authorization", "Bearer SECRET_TOKEN") +} + +/// The contents of `name` in an uncompressed tar archive. +fn tar_entry(archive: &[u8], name: &str) -> Option { + let mut at = 0; + while at + 512 <= archive.len() { + let header = &archive[at..at + 512]; + if header.iter().all(|b| *b == 0) { + return None; + } + let entry_name = String::from_utf8_lossy(&header[..100]) + .trim_end_matches('\0') + .to_string(); + let size = usize::from_str_radix( + String::from_utf8_lossy(&header[124..136]) + .trim_matches(|c: char| c == '\0' || c == ' '), + 8, + ) + .unwrap(); + let body = at + 512; + if entry_name == name { + return Some(String::from_utf8_lossy(&archive[body..body + size]).to_string()); + } + at = body + size.div_ceil(512) * 512; + } + None +} + +async fn create_workspace(db: &Pool, id: &str) { + for q in [ + "INSERT INTO workspace (id, name, owner) VALUES ($1, $1, 'test-user')", + "INSERT INTO workspace_settings (workspace_id) VALUES ($1)", + "INSERT INTO workspace_key (workspace_id, kind, key) VALUES ($1, 'cloud', 'target-key')", + "INSERT INTO usr (workspace_id, email, username, is_admin, role) + VALUES ($1, 'test@windmill.dev', 'test-user', true, 'Admin')", + "INSERT INTO group_ (workspace_id, name, summary, extra_perms) + VALUES ($1, 'all', 'All users', '{}')", + ] { + sqlx::query(q).bind(id).execute(db).await.unwrap(); + } +} + +async fn stored_overrides(db: &Pool, w_id: &str) -> Option { + sqlx::query_scalar("SELECT role_overrides FROM workspace_settings WHERE workspace_id = $1") + .bind(w_id) + .fetch_one(db) + .await + .unwrap() +} + +async fn apply(port: u16, w_id: &str, document: Value, dry_run: bool) -> reqwest::Response { + authed(client().post(format!( + "http://localhost:{port}/api/w/{w_id}/workspaces/settings_document" + ))) + .json(&json!({ "document": document, "replace": true, "dry_run": dry_run })) + .send() + .await + .unwrap() +} + +fn overrides_of_default_roles() -> Value { + json!({ + "developer": { "capabilities": { "fork": false } }, + "operator": { "label": "Runner", "capabilities": { "flows": "compose" } }, + }) +} + +/// A workspace-only role is EE: a CE workspace has only overrides of the default roles. +fn workspace_only_roles() -> Value { + if cfg!(feature = "enterprise") { + json!({ "auditor": { "label": "Auditor", "capabilities": { "code": false } } }) + } else { + json!({}) + } +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn role_overrides_round_trip_through_export_and_import( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let mut all = overrides_of_default_roles(); + all.as_object_mut() + .unwrap() + .extend(workspace_only_roles().as_object().unwrap().clone()); + let resp = authed(client().post(format!( + "http://localhost:{port}/api/w/test-workspace/workspaces/role_overrides" + ))) + .json(&all) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let resp = authed(client().get(format!( + "http://localhost:{port}/api/w/test-workspace/workspaces/tarball\ + ?include_settings=true&settings_version=v2&archive_type=tar" + ))) + .send() + .await?; + assert_eq!(resp.status(), 200); + let archive = resp.bytes().await?; + let settings: Value = serde_json::from_str( + &tar_entry(&archive, "settings.json").expect("the export carries settings.json"), + )?; + assert_eq!(settings["role_overrides"], overrides_of_default_roles()); + assert_eq!(settings["workspace_only_roles"], workspace_only_roles()); + + // The settings document `wmill sync pull` writes states the same. + let pulled: Value = authed(client().get(format!( + "http://localhost:{port}/api/w/test-workspace/workspaces/settings_document?secrets=encrypted" + ))) + .send() + .await? + .json() + .await?; + assert_eq!(pulled["role_overrides"], settings["role_overrides"]); + assert_eq!( + pulled["workspace_only_roles"], + settings["workspace_only_roles"] + ); + + // Importing the export into another workspace reproduces the roles. + create_workspace(&db, "target-ws").await; + let resp = apply(port, "target-ws", settings.clone(), false).await; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let result: Value = resp.json().await?; + assert_eq!(result["applied"], true); + assert_eq!( + stored_overrides(&db, "target-ws").await, + stored_overrides(&db, "test-workspace").await + ); + let roles: Value = authed(client().get(format!( + "http://localhost:{port}/api/w/target-ws/workspaces/roles" + ))) + .send() + .await? + .json() + .await?; + let role = |name: &str| { + roles["roles"] + .as_array() + .unwrap() + .iter() + .find(|r| r["name"] == name) + .cloned() + }; + assert_eq!(role("operator").unwrap()["label"], "Runner"); + assert_eq!( + role("operator").unwrap()["capabilities"]["flows"], + "compose" + ); + assert_eq!(role("developer").unwrap()["capabilities"]["fork"], false); + if cfg!(feature = "enterprise") { + let auditor = role("auditor").expect("the workspace-only role is imported"); + assert_eq!(auditor["source"], "workspace"); + assert_eq!(auditor["label"], "Auditor"); + } + + // A second import changes nothing, so a repeated push does not rewrite the roles. + let result: Value = apply(port, "target-ws", settings, false) + .await + .json() + .await?; + assert_eq!(result["changes"], json!([]), "{result}"); + Ok(()) +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn an_override_of_a_role_the_instance_lacks_is_refused( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let before = stored_overrides(&db, "test-workspace").await; + + let document = json!({ + "name": "test-workspace", + "webhook": "https://example.com/hook", + "role_overrides": { + "operator": { "capabilities": { "manage_schedules": true } }, + "reviewer": { "capabilities": { "code": false } }, + }, + }); + for dry_run in [true, false] { + let resp = apply(port, "test-workspace", document.clone(), dry_run).await; + assert_eq!(resp.status(), 400, "dry_run: {dry_run}"); + let message = resp.text().await?; + assert!( + message.contains("`reviewer`") && message.contains("does not define"), + "{message}" + ); + } + assert_eq!(stored_overrides(&db, "test-workspace").await, before); + let webhook: Option = + sqlx::query_scalar("SELECT webhook FROM workspace_settings WHERE workspace_id = $1") + .bind("test-workspace") + .fetch_one(&db) + .await?; + assert_eq!( + webhook, None, + "the refusal comes before any setting is written" + ); + + // A role the instance defines cannot be added as a workspace-only one either. + let resp = apply( + port, + "test-workspace", + json!({ "workspace_only_roles": { "operator": { "label": "Mine" } } }), + true, + ) + .await; + assert_eq!(resp.status(), 400); + assert!(resp.text().await?.contains("already defines")); + Ok(()) +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn a_document_without_the_roles_keys_leaves_them_alone( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + sqlx::query("UPDATE workspace_settings SET role_overrides = $1 WHERE workspace_id = $2") + .bind(json!({ "operator": { "capabilities": { "flows": "compose" } } })) + .bind("test-workspace") + .execute(&db) + .await?; + + // A settings.yaml pulled before the keys existed. + let resp = apply( + port, + "test-workspace", + json!({ "name": "test-workspace", "webhook": "https://example.com/hook" }), + false, + ) + .await; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + assert_eq!( + stored_overrides(&db, "test-workspace").await, + Some(json!({ "operator": { "capabilities": { "flows": "compose" } } })) + ); + Ok(()) +} + +/// Stating only `role_overrides` keeps the workspace-only roles, and stating it as empty clears +/// the overrides. +#[cfg(feature = "enterprise")] +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn each_roles_key_is_managed_on_its_own(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + sqlx::query("UPDATE workspace_settings SET role_overrides = $1 WHERE workspace_id = $2") + .bind(json!({ + "operator": { "capabilities": { "flows": "compose" } }, + "auditor": { "label": "Auditor", "capabilities": {} }, + })) + .bind("test-workspace") + .execute(&db) + .await?; + + let resp = apply( + port, + "test-workspace", + json!({ "role_overrides": {} }), + false, + ) + .await; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + assert_eq!( + stored_overrides(&db, "test-workspace").await, + Some(json!({ "auditor": { "label": "Auditor", "capabilities": {} } })) + ); + Ok(()) +} diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index b909220ec4..e6c78c95d4 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -15757,6 +15757,8 @@ pub enum SettingsEdit { DefaultApp, Color, OperatorSettings, + /// Body: the whole `role_overrides` map, workspace-only roles included. + RoleOverrides, Datatable, SlackCommand, SetSlackOAuth, @@ -15821,6 +15823,11 @@ pub async fn apply_settings_edit( ) .await? } + RoleOverrides => { + let Json(overrides) = settings_edit_body(edit, body)?; + crate::workspace_roles::write_role_overrides(&d.0, &a, &p.0, overrides, None).await?; + "Role overrides updated".to_string() + } Datatable => { let Json(result) = edit_datatable_config(a, d, p, settings_edit_body(edit, body)?).await?; diff --git a/backend/windmill-api/src/mcp/session/gen/instructions.json b/backend/windmill-api/src/mcp/session/gen/instructions.json index f197f795ce..fb05ab0d58 100644 --- a/backend/windmill-api/src/mcp/session/gen/instructions.json +++ b/backend/windmill-api/src/mcp/session/gen/instructions.json @@ -261,6 +261,6 @@ "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.) Write 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. 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\nSELECT date_trunc('day', ts) AS day, count(*) AS n\nFROM ducklake.main.orders GROUP BY 1\n```\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`slack_oauth_client_secret` is the one secret. 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? }`, `path` being `script/` or `flow/`. |\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`. 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| `operator_settings` | What operators see and do: 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`). A write right the value omits keeps its stored value. |\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`slack_oauth_client_secret` is the one secret. 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? }`, `path` being `script/` or `flow/`. |\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`. 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| `operator_settings` | What operators see and do: 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`). A write right the value omits keeps its stored value. |\n| `role_overrides` | `{ : { label?, capabilities: { code?, flows?, apps?, manage_schedules?, manage_triggers?, fork?, visibility? } } }`: this workspace's overrides of roles the instance defines. A capability left out follows the instance definition. A role the instance does not define is refused, not skipped. |\n| `workspace_only_roles` | Same shape: roles this workspace adds (Enterprise only). A role the instance defines is refused here. |\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" } } diff --git a/backend/windmill-api/src/workspace_settings_document.rs b/backend/windmill-api/src/workspace_settings_document.rs index 5f0f062d10..40d5a5264e 100644 --- a/backend/windmill-api/src/workspace_settings_document.rs +++ b/backend/windmill-api/src/workspace_settings_document.rs @@ -25,6 +25,7 @@ use windmill_common::{ read_role_catalog, DatatableRoleCluster, ADMIN_DATATABLE_ROLE, NO_DEFAULT_DATATABLE_ROLE, }, error::{Error, JsonResult, Result}, + roles::{self, RoleDefinition, RoleOverrides}, utils::require_admin, variables::build_crypt, workspaces::{ @@ -85,6 +86,7 @@ struct SettingsRow { guest_jwt_jwks_url: Option, error_handler_fallback_to_instance_alerts: Option, add_admins_and_developers_to_forks: Option, + role_overrides: Option, } /// Server-owned git sync state (the webhook secret and hook id, the synced sha, the admin @@ -294,6 +296,25 @@ fn with_fork_role_mapping(rule: &mut Value, mapping: Value) { } } +/// The stored `role_overrides` split by what each entry is on this instance: an override of a role +/// the instance defines, or a role the workspace adds. A promotion target can then tell an +/// override whose instance role it lacks from a role to add. Sorted, so a pull does not churn. +fn role_overrides_document(stored: Option, instance: &[RoleDefinition]) -> (Value, Value) { + let (mut overrides, mut added) = (BTreeMap::new(), BTreeMap::new()); + if let Some(Value::Object(stored)) = stored { + for (name, entry) in stored { + let entry = serde_json::from_value::(entry.clone()) + .map_or(entry, |o| json!(o)); + if instance.iter().any(|d| d.name == name) { + overrides.insert(name, entry); + } else { + added.insert(name, entry); + } + } + } + (json!(overrides), json!(added)) +} + fn rule_kinds(rules: ProtectionRules) -> Value { json!(rules.kinds()) } @@ -315,7 +336,7 @@ pub async fn load_settings_document( slack_oauth_client_id, slack_oauth_client_secret, 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, - add_admins_and_developers_to_forks + add_admins_and_developers_to_forks, role_overrides FROM workspace_settings LEFT JOIN workspace ON workspace.id = workspace_settings.workspace_id WHERE workspace_id = $1"#, @@ -352,6 +373,9 @@ pub async fn load_settings_document( }; let datatable_permissions = datatable_permissions_document(row.datatable.as_ref(), &role_names); let protection_rules = protection_rules_document(&mut *conn, w_id).await?; + let instance = roles::instance_roles(db).await?; + let (role_overrides, workspace_only_roles) = + role_overrides_document(row.role_overrides, &instance); let git_sync = redact_git_sync(row.git_sync); let git_sync = match fork_parent(&mut *conn, w_id).await? { Some(parent) => fork_git_sync_document(git_sync, parent.git_sync), @@ -361,7 +385,7 @@ pub async fn load_settings_document( // In the order `wmill sync pull` has always written settings.yaml. A key that predates the // document and is not marked `always` is written only when set, as it always was; a key // added since is always written, so a pulled file states it and from then on manages it. - let entries: [(&str, Option, bool); 31] = [ + let entries: [(&str, Option, bool); 33] = [ ("auto_invite", row.auto_invite, false), ("webhook", row.webhook.map(Value::String), false), ("error_handler", row.error_handler, true), @@ -445,6 +469,8 @@ pub async fn load_settings_document( ), ("datatable_permissions", Some(datatable_permissions), true), ("protection_rules", Some(protection_rules), true), + ("role_overrides", Some(role_overrides), true), + ("workspace_only_roles", Some(workspace_only_roles), true), ]; let mut doc = Map::new(); for (key, value, always) in entries { @@ -721,6 +747,8 @@ const KNOWN_KEYS: &[&str] = &[ "add_admins_and_developers_to_forks", "datatable_permissions", "protection_rules", + "role_overrides", + "workspace_only_roles", ]; fn string_list(v: Option<&Value>, what: &str) -> Result { @@ -915,7 +943,8 @@ async fn plan(db: &DB, w_id: &str, mut desired: Map, replace: boo Some(v) if !v.is_null() => DatatableNames::load(db, w_id, v).await?, _ => DatatableNames::default(), }; - plan_document(current, desired, replace, &mc, &names) + let instance = roles::instance_roles(db).await?; + plan_document(current, desired, replace, &mc, &names, &instance) } /// A fork's parent, read for its `git_sync`. @@ -1065,6 +1094,7 @@ fn plan_document( replace: bool, mc: &windmill_common::variables::WorkspaceCrypt, names: &DatatableNames, + instance: &[RoleDefinition], ) -> Result { let mut warnings = vec![]; let unknown: Vec<&str> = desired @@ -1431,6 +1461,7 @@ fn plan_document( p.write(Target::Edit(SettingsEdit::OperatorSettings), desired); } } + plan_role_overrides(&mut p, instance)?; let datatable = p.legacy("datatable"); p.simple( @@ -1617,6 +1648,99 @@ fn object_of(v: Option<&Value>) -> Map { v.and_then(Value::as_object).cloned().unwrap_or_default() } +/// Plans `role_overrides` and `workspace_only_roles`, each managed only when stated: an unstated one +/// keeps the stored entries of its kind. Both are one column, written whole. An override of a +/// role this instance does not define is refused rather than skipped: stored, it would turn into +/// a workspace-only role, and dropped, the role would take the instance's capabilities the moment +/// it is defined here. +fn plan_role_overrides(p: &mut Plan, instance: &[RoleDefinition]) -> Result<()> { + let stated = |key: &str| -> Result>> { + match p.managed(key) { + None => Ok(None), + Some(Value::Null) => Ok(Some(Map::new())), + Some(v) => { + let parsed: BTreeMap = serde_json::from_value(v) + .map_err(|e| { + Error::BadRequest(format!("{key} must map role names to roles: {e}")) + })?; + Ok(Some( + parsed + .into_iter() + .map(|(name, o)| (name, json!(o))) + .collect(), + )) + } + } + }; + let (overrides, added) = (stated("role_overrides")?, stated("workspace_only_roles")?); + if overrides.is_none() && added.is_none() { + return Ok(()); + } + let defined = |name: &str| instance.iter().any(|d| d.name == name); + let mut errors = vec![]; + for name in overrides.iter().flat_map(|o| o.keys()) { + if !defined(name) { + errors.push(format!( + "role_overrides overrides role `{name}`, which this instance does not define: \ + define it in the instance settings (Workspace roles) first" + )); + } + } + for name in added.iter().flat_map(|a| a.keys()) { + if defined(name) { + errors.push(format!( + "workspace_only_roles adds role `{name}`, which this instance already defines: \ + state it under role_overrides instead" + )); + } + } + if !errors.is_empty() { + return Err(Error::BadRequest(errors.join("; "))); + } + + let (current_overrides, current_added) = ( + object_of(p.current.get("role_overrides")), + object_of(p.current.get("workspace_only_roles")), + ); + let previous: RoleOverrides = current_overrides + .clone() + .into_iter() + .chain(current_added.clone()) + .filter_map(|(name, v)| Some((name, serde_json::from_value(v).ok()?))) + .collect(); + let mut changed = false; + for (key, desired, current) in [ + ("role_overrides", overrides, current_overrides), + ("workspace_only_roles", added, current_added), + ] { + let desired = Value::Object(desired.unwrap_or(current)); + if p.differs(key, &desired) { + p.record(key, desired.clone()); + changed = true; + } + p.desired.insert(key.to_string(), desired); + } + // The legacy write before this one rewrites the `operator` override, so the stated roles are + // written after it even when they match what is stored. + let operator_settings_written = p + .writes + .iter() + .any(|w| matches!(w.target, Target::Edit(SettingsEdit::OperatorSettings))); + if !changed && !operator_settings_written { + return Ok(()); + } + let next: RoleOverrides = ["role_overrides", "workspace_only_roles"] + .iter() + .flat_map(|key| object_of(p.desired.get(*key))) + .map(|(name, v)| Ok((name, serde_json::from_value(v)?))) + .collect::>() + .map_err(|e| Error::internal_err(format!("re-reading role overrides: {e:#}")))?; + roles::validate_overrides(instance, &next)?; + roles::check_frozen_overrides(instance, &previous, &next)?; + p.write(Target::Edit(SettingsEdit::RoleOverrides), json!(next)); + Ok(()) +} + fn plan_datatable_permissions( p: &mut Plan, desired: Value, @@ -1953,11 +2077,27 @@ mod tests { fn replace_clears_an_omitted_setting_only_when_a_stated_one_changes() { let mc = WorkspaceCrypt::new("k"); let unchanged = doc(json!({ "name": "other", "webhook": "https://a" })); - let p = plan_document(current(), unchanged, true, &mc, &DatatableNames::default()).unwrap(); + let p = plan_document( + current(), + unchanged, + true, + &mc, + &DatatableNames::default(), + &roles::default_instance_roles(), + ) + .unwrap(); assert!(p.writes.is_empty(), "{:?}", keys(&p)); let changed = doc(json!({ "webhook": "https://b" })); - let p = plan_document(current(), changed, true, &mc, &DatatableNames::default()).unwrap(); + let p = plan_document( + current(), + changed, + true, + &mc, + &DatatableNames::default(), + &roles::default_instance_roles(), + ) + .unwrap(); assert_eq!( keys(&p), [ @@ -1988,6 +2128,7 @@ mod tests { false, &mc, &DatatableNames::default(), + &roles::default_instance_roles(), ) .unwrap(); assert!(p.changes.is_empty(), "{secret}: {:?}", keys(&p)); @@ -2002,19 +2143,32 @@ mod tests { "mute_critical_alerts": false, "add_admins_and_developers_to_forks": null })); - assert!( - plan_document(current(), d, false, &mc, &DatatableNames::default()) - .unwrap() - .changes - .is_empty() - ); + assert!(plan_document( + current(), + d, + false, + &mc, + &DatatableNames::default(), + &roles::default_instance_roles() + ) + .unwrap() + .changes + .is_empty()); } #[test] fn retired_keys_are_dropped_without_a_warning() { let mc = WorkspaceCrypt::new("k"); let d = doc(json!({ "guest_access_enabled": true })); - let p = plan_document(current(), d, false, &mc, &DatatableNames::default()).unwrap(); + let p = plan_document( + current(), + d, + false, + &mc, + &DatatableNames::default(), + &roles::default_instance_roles(), + ) + .unwrap(); assert!(p.changes.is_empty() && p.writes.is_empty() && p.warnings.is_empty()); } @@ -2022,7 +2176,15 @@ mod tests { fn stating_one_guest_key_clears_the_other() { let mc = WorkspaceCrypt::new("k"); let d = doc(json!({ "guest_jwt_jwks_url": "https://jwks" })); - let p = plan_document(current(), d, false, &mc, &DatatableNames::default()).unwrap(); + let p = plan_document( + current(), + d, + false, + &mc, + &DatatableNames::default(), + &roles::default_instance_roles(), + ) + .unwrap(); assert_eq!(p.writes.len(), 1); assert_eq!( p.writes[0].body, @@ -2049,7 +2211,8 @@ mod tests { doc(d.clone()), false, &mc, - &DatatableNames::default() + &DatatableNames::default(), + &roles::default_instance_roles() ) .is_err(), "{d}" @@ -2066,11 +2229,27 @@ mod tests { json!({ "path": "f/x", "extra_args": {}, "muted_on_cancel": false, "muted_on_user_path": false }), ); let d = doc(json!({ "error_handler": { "path": "f/x", "extra_args": { "input": null } } })); - let p = plan_document(cur.clone(), d, false, &mc, &DatatableNames::default()).unwrap(); + let p = plan_document( + cur.clone(), + d, + false, + &mc, + &DatatableNames::default(), + &roles::default_instance_roles(), + ) + .unwrap(); assert_eq!(keys(&p), ["error_handler"]); let d = doc(json!({ "error_handler": { "path": "f/x", "extra_args": {} } })); - let p = plan_document(cur, d, false, &mc, &DatatableNames::default()).unwrap(); + let p = plan_document( + cur, + d, + false, + &mc, + &DatatableNames::default(), + &roles::default_instance_roles(), + ) + .unwrap(); assert!(p.changes.is_empty(), "{:?}", keys(&p)); } @@ -2084,15 +2263,39 @@ mod tests { json!({ "path": "script/f/x", "muted_on_user_path": false }), ); let omitted = doc(json!({ "webhook": "https://b" })); - let p = plan_document(cur.clone(), omitted, true, &mc, &names).unwrap(); + let p = plan_document( + cur.clone(), + omitted, + true, + &mc, + &names, + &roles::default_instance_roles(), + ) + .unwrap(); assert!(!keys(&p).contains(&"variable_expiration_handler")); let same = doc(json!({ "variable_expiration_handler": { "path": "script/f/x" } })); - let p = plan_document(cur.clone(), same, false, &mc, &names).unwrap(); + let p = plan_document( + cur.clone(), + same, + false, + &mc, + &names, + &roles::default_instance_roles(), + ) + .unwrap(); assert!(p.changes.is_empty(), "{:?}", keys(&p)); let cleared = doc(json!({ "variable_expiration_handler": null })); - let p = plan_document(cur, cleared, false, &mc, &names).unwrap(); + let p = plan_document( + cur, + cleared, + false, + &mc, + &names, + &roles::default_instance_roles(), + ) + .unwrap(); assert_eq!(keys(&p), ["variable_expiration_handler"]); assert_eq!(p.writes[0].body["path"], Value::Null); } @@ -2118,7 +2321,15 @@ mod tests { let d = doc( json!({ "datatable_permissions": { "main": { "default_role": "readers", "roles": { "readers": ["g/x", "u/bob"] } } } }), ); - let p = plan_document(cur.clone(), d, false, &mc, &roles).unwrap(); + let p = plan_document( + cur.clone(), + d, + false, + &mc, + &roles, + &roles::default_instance_roles(), + ) + .unwrap(); assert_eq!(keys(&p), ["datatable_permissions.main"]); assert_eq!( p.writes[0].body, @@ -2127,17 +2338,41 @@ mod tests { ); let d = doc(json!({ "datatable_permissions": {} })); - let p = plan_document(cur.clone(), d, false, &mc, &roles).unwrap(); + let p = plan_document( + cur.clone(), + d, + false, + &mc, + &roles, + &roles::default_instance_roles(), + ) + .unwrap(); assert_eq!( p.writes[0].body, json!({ "datatable": "main", "permissioned": false }) ); let d = doc(json!({ "datatable_permissions": { "main": { "roles": { "writers": [] } } } })); - assert!(plan_document(cur.clone(), d, false, &mc, &roles).is_err()); + assert!(plan_document( + cur.clone(), + d, + false, + &mc, + &roles, + &roles::default_instance_roles() + ) + .is_err()); let d = doc(json!({ "datatable_permissions": { "main": { "default_role": "readers" } } })); - assert!(plan_document(cur.clone(), d, false, &mc, &roles).is_err()); + assert!(plan_document( + cur.clone(), + d, + false, + &mc, + &roles, + &roles::default_instance_roles() + ) + .is_err()); // A tenant that names nobody is refused when granted, not when already stored, and every // data table's errors come back together. @@ -2150,17 +2385,34 @@ mod tests { json!({ "datatable_permissions": { "main": { "default_role": "readers", "roles": { "readers": ["g/x"] } } } }), ); assert_eq!( - keys(&plan_document(cur.clone(), d, false, &mc, &strict).unwrap()), + keys( + &plan_document( + cur.clone(), + d, + false, + &mc, + &strict, + &roles::default_instance_roles() + ) + .unwrap() + ), ["datatable_permissions.main"] ); let d = doc(json!({ "datatable_permissions": { "main": { "roles": { "readers": ["g/x", "u/bob"], "writers": [] } }, "other": { "roles": { "readers": ["x/y"] } }, } })); - let e = plan_document(cur.clone(), d, false, &mc, &strict) - .err() - .unwrap() - .to_string(); + let e = plan_document( + cur.clone(), + d, + false, + &mc, + &strict, + &roles::default_instance_roles(), + ) + .err() + .unwrap() + .to_string(); for part in [ "tenant 'u/bob' names no user", "'writers' is not a data table role", @@ -2171,13 +2423,23 @@ mod tests { // Under replace an omitted `datatable` is cleared, taking its tables' roles with it. let d = doc(json!({ "datatable_permissions": {} })); - let p = plan_document(cur.clone(), d, true, &mc, &roles).unwrap(); + let p = plan_document( + cur.clone(), + d, + true, + &mc, + &roles, + &roles::default_instance_roles(), + ) + .unwrap(); assert!(!p .writes .iter() .any(|w| matches!(w.target, Target::Edit(SettingsEdit::DatatablePermissions)))); let d = doc(json!({ "datatable_permissions": { "main": {} } })); - assert!(plan_document(cur, d, true, &mc, &roles).is_err()); + assert!( + plan_document(cur, d, true, &mc, &roles, &roles::default_instance_roles()).is_err() + ); } #[test] @@ -2193,7 +2455,15 @@ mod tests { "fork_role_mapping": { "operator": "developer" } }, "dev_workspace_lock": { "rules": [] }, } })); - let p = plan_document(cur, d, false, &mc, &DatatableNames::default()).unwrap(); + let p = plan_document( + cur, + d, + false, + &mc, + &DatatableNames::default(), + &roles::default_instance_roles(), + ) + .unwrap(); assert_eq!(keys(&p), ["protection_rules.new", "protection_rules.old"]); assert_eq!( p.writes[0].body, @@ -2302,4 +2572,196 @@ mod tests { Value::Null ); } + + fn instance_with(extra: &str) -> Vec { + let mut roles = roles::default_instance_roles(); + roles.push(RoleDefinition { + name: extra.to_string(), + label: None, + capabilities: Default::default(), + }); + roles + } + + #[test] + fn the_document_splits_overrides_from_workspace_only_roles() { + let stored = json!({ + "reviewer": { "capabilities": { "code": false } }, + "auditor": { "label": "Auditor" }, + "operator": { "capabilities": { "flows": "compose" } }, + }); + let (overrides, added) = + role_overrides_document(Some(stored.clone()), &instance_with("reviewer")); + assert_eq!( + overrides, + json!({ + "operator": { "capabilities": { "flows": "compose" } }, + "reviewer": { "capabilities": { "code": false } }, + }) + ); + assert_eq!( + overrides.as_object().unwrap().keys().collect::>(), + ["operator", "reviewer"], + "sorted, so a pull writes the same file every time" + ); + assert_eq!( + added, + json!({ "auditor": { "label": "Auditor", "capabilities": {} } }) + ); + + let (overrides, added) = + role_overrides_document(Some(stored), &roles::default_instance_roles()); + assert_eq!( + overrides, + json!({ "operator": { "capabilities": { "flows": "compose" } } }) + ); + assert_eq!(added.as_object().unwrap().len(), 2); + assert_eq!( + role_overrides_document(None, &roles::default_instance_roles()), + (json!({}), json!({})) + ); + } + + fn roles_current() -> Map { + let mut cur = current(); + cur.insert( + "role_overrides".to_string(), + json!({ "operator": { "capabilities": { "flows": "compose" } } }), + ); + cur.insert( + "workspace_only_roles".to_string(), + if cfg!(feature = "enterprise") { + json!({ "auditor": { "label": "Auditor", "capabilities": {} } }) + } else { + json!({}) + }, + ); + cur + } + + fn plan_roles(d: Value, replace: bool, instance: &[RoleDefinition]) -> Result { + let mc = WorkspaceCrypt::new("k"); + plan_document( + roles_current(), + doc(d), + replace, + &mc, + &DatatableNames::default(), + instance, + ) + } + + fn role_write(p: &Plan) -> Option<&Value> { + p.writes + .iter() + .find(|w| matches!(w.target, Target::Edit(SettingsEdit::RoleOverrides))) + .map(|w| &w.body) + } + + #[test] + fn a_stated_override_is_written_with_the_other_kind_kept() { + let instance = roles::default_instance_roles(); + let p = plan_roles( + json!({ "role_overrides": { + "operator": { "capabilities": { "flows": "full", "code": true } }, + } }), + false, + &instance, + ) + .unwrap(); + assert_eq!(keys(&p), ["role_overrides"]); + let mut expected = json!({ + "operator": { "capabilities": { "code": true, "flows": "full" } }, + }); + if cfg!(feature = "enterprise") { + expected["auditor"] = json!({ "label": "Auditor", "capabilities": {} }); + } + assert_eq!(role_write(&p), Some(&expected)); + } + + #[test] + fn unchanged_or_unstated_roles_write_nothing() { + let instance = roles::default_instance_roles(); + let same = roles_current(); + let p = plan_roles( + json!({ + "role_overrides": same["role_overrides"], + "workspace_only_roles": same["workspace_only_roles"], + }), + false, + &instance, + ) + .unwrap(); + assert!(p.writes.is_empty(), "{:?}", keys(&p)); + + // Under replace, an omitted key is not cleared: a file pulled before it existed. + let p = plan_roles(json!({ "webhook": "https://b" }), true, &instance).unwrap(); + assert!(role_write(&p).is_none(), "{:?}", keys(&p)); + } + + #[test] + fn an_override_of_an_undefined_instance_role_is_refused() { + let d = json!({ + "webhook": "https://b", + "role_overrides": { "reviewer": { "capabilities": { "code": false } } }, + }); + let e = plan_roles(d.clone(), true, &roles::default_instance_roles()) + .err() + .expect("refused, not skipped"); + assert!( + e.to_string().contains("`reviewer`") && e.to_string().contains("does not define"), + "{e}" + ); + let p = plan_roles(d, true, &instance_with("reviewer")).unwrap(); + assert!(role_write(&p).unwrap().get("reviewer").is_some()); + } + + #[test] + fn a_workspace_only_role_the_instance_defines_is_refused() { + let e = plan_roles( + json!({ "workspace_only_roles": { "reviewer": { "label": "R" } } }), + false, + &instance_with("reviewer"), + ) + .err() + .unwrap(); + assert!(e.to_string().contains("already defines"), "{e}"); + } + + #[test] + fn workspace_only_roles_follow_the_edition() { + let r = plan_roles( + json!({ "workspace_only_roles": { "scripter": { "capabilities": { "code": true } } } }), + false, + &roles::default_instance_roles(), + ); + if cfg!(feature = "enterprise") { + let p = r.unwrap(); + assert_eq!(keys(&p), ["workspace_only_roles"]); + assert!(role_write(&p).unwrap().get("scripter").is_some()); + } else { + let e = r.err().expect("adding a role is EE"); + assert!(e.to_string().contains("Enterprise Edition"), "{e}"); + } + } + + #[test] + fn roles_are_written_after_a_legacy_operator_settings_write() { + let same = roles_current(); + let p = plan_roles( + json!({ + "operator_settings": { "runs": true }, + "role_overrides": same["role_overrides"], + }), + false, + &roles::default_instance_roles(), + ) + .unwrap(); + let targets: Vec<_> = p.writes.iter().map(|w| format!("{:?}", w.target)).collect(); + assert_eq!( + targets, + ["Edit(OperatorSettings)", "Edit(RoleOverrides)"], + "the stated roles win over what the legacy write leaves" + ); + } } diff --git a/cli/src/core/settings.ts b/cli/src/core/settings.ts index 9891440dd4..c4a37b1ed5 100644 --- a/cli/src/core/settings.ts +++ b/cli/src/core/settings.ts @@ -77,6 +77,8 @@ export interface SimplifiedSettings { error_handler_fallback_to_instance_alerts?: boolean; add_admins_and_developers_to_forks?: boolean; datatable_permissions?: Record | null; + role_overrides?: Record | null; + workspace_only_roles?: Record | null; } /** Settings the server manages only when settings.yaml states them: a file written before @@ -93,6 +95,8 @@ export const SETTINGS_MANAGED_ONLY_WHEN_PRESENT = [ "error_handler_fallback_to_instance_alerts", "add_admins_and_developers_to_forks", "variable_expiration_handler", + "role_overrides", + "workspace_only_roles", ] as const; /** Keys earlier versions wrote that no longer configure anything; the server ignores them, diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index 537f531523..6047d56845 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -8504,6 +8504,8 @@ 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. | | \`operator_settings\` | What operators see and do: 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\`). A write right the value omits keeps its stored value. | +| \`role_overrides\` | \`{ : { label?, capabilities: { code?, flows?, apps?, manage_schedules?, manage_triggers?, fork?, visibility? } } }\`: this workspace's overrides of roles the instance defines. A capability left out follows the instance definition. A role the instance does not define is refused, not skipped. | +| \`workspace_only_roles\` | Same shape: roles this workspace adds (Enterprise only). A role the instance defines is refused here. | | \`mute_critical_alerts\` | Mute the workspace's critical alerts. | | \`slack_team_id\`, \`slack_name\` | Read only: set by connecting Slack on the settings page. | | \`slack_command_script\` / \`teams_command_script\` | Script or flow handling the Slack / Teams command. | @@ -8528,8 +8530,8 @@ With \`includeSettings: true\` in \`wmill.yaml\`, \`wmill sync pull\` writes the document: a setting the file omits is cleared, except \`operator_settings\`, \`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 -\`add_admins_and_developers_to_forks\`, which are managed only when the file states them. +\`error_handler_fallback_to_instance_alerts\`, \`add_admins_and_developers_to_forks\`, +\`role_overrides\` and \`workspace_only_roles\`, which are managed only when the file states them. \`datatable_permissions\` is pushed only with \`includeDatatablePermissions: true\` (or \`--include-datatable-permissions\`). A push ignores \`protection_rules\`: \`protection-rules.yaml\` and \`wmill protection-rules push\` sync them. diff --git a/cli/test/role_overrides_settings_sync.test.ts b/cli/test/role_overrides_settings_sync.test.ts new file mode 100644 index 0000000000..a4607c71b8 --- /dev/null +++ b/cli/test/role_overrides_settings_sync.test.ts @@ -0,0 +1,141 @@ +/** + * Workspace role overrides sync through settings.yaml: `sync pull` writes them, `sync push` + * applies them, and an override of a role the instance does not define fails the push. + */ + +import { expect, test } from "bun:test"; +import { writeFile, readFile } from "node:fs/promises"; +import { parse, stringify } from "yaml"; +import { withTestBackend } from "./test_backend.ts"; +import { shouldSkipOnCI } from "./cargo_backend.ts"; +import { addWorkspace } from "../workspace.ts"; + +const WMILL_YAML = `defaultTs: bun +includes: + - "**" +includeSettings: true`; + +async function setup(backend: any, tempDir: string, name: string) { + await addWorkspace( + { remote: backend.baseUrl, workspaceId: backend.workspace, name, token: backend.token }, + { force: true, configDir: backend.testConfigDir }, + ); + await writeFile(`${tempDir}/wmill.yaml`, WMILL_YAML, "utf-8"); +} + +async function setRoleOverrides(backend: any, overrides: unknown) { + const resp = await backend.apiRequest!( + `/api/w/${backend.workspace}/workspaces/role_overrides`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(overrides), + }, + ); + expect(resp.ok).toBe(true); +} + +async function storedRoles(backend: any) { + const resp = await backend.apiRequest!(`/api/w/${backend.workspace}/workspaces/roles`); + expect(resp.ok).toBe(true); + return (await resp.json()) as { + overrides: Record; + roles: { name: string; label: string; source: string; capabilities: any }[]; + }; +} + +test.skipIf(shouldSkipOnCI())("Role overrides: pulled into settings.yaml and pushed back", async () => { + await withTestBackend(async (backend, tempDir) => { + await setup(backend, tempDir, "role_overrides_roundtrip"); + await setRoleOverrides(backend, { + operator: { label: "Runner", capabilities: { flows: "compose" } }, + auditor: { label: "Auditor", capabilities: { code: false } }, + }); + + const pull = await backend.runCLICommand(["sync", "pull", "--yes"], tempDir); + expect(pull.code).toEqual(0); + const settings = parse(await readFile(`${tempDir}/settings.yaml`, "utf-8")) as any; + expect(settings.role_overrides).toEqual({ + operator: { label: "Runner", capabilities: { flows: "compose" } }, + }); + expect(settings.workspace_only_roles).toEqual({ + auditor: { label: "Auditor", capabilities: { code: false } }, + }); + + // Edit both kinds in the file: override developer too, swap the workspace-only role. + settings.role_overrides.developer = { capabilities: { fork: false } }; + settings.workspace_only_roles = { + scripter: { label: "Scripter", capabilities: { code: true, flows: "none", apps: "none" } }, + }; + await writeFile(`${tempDir}/settings.yaml`, stringify(settings), "utf-8"); + + const push = await backend.runCLICommand(["sync", "push", "--yes"], tempDir); + expect(push.code).toEqual(0); + + const roles = await storedRoles(backend); + expect(roles.overrides).toEqual({ + operator: { label: "Runner", capabilities: { flows: "compose" } }, + developer: { capabilities: { fork: false } }, + scripter: { label: "Scripter", capabilities: { code: true, flows: "none", apps: "none" } }, + }); + const scripter = roles.roles.find((r) => r.name === "scripter"); + expect(scripter?.source).toEqual("workspace"); + expect(roles.roles.some((r) => r.name === "auditor")).toBe(false); + + // Pulling again writes the file that was pushed, so a synced repo does not churn. + const before = await readFile(`${tempDir}/settings.yaml`, "utf-8"); + const repull = await backend.runCLICommand(["sync", "pull", "--yes"], tempDir); + expect(repull.code).toEqual(0); + const after = parse(await readFile(`${tempDir}/settings.yaml`, "utf-8")) as any; + expect(after.role_overrides).toEqual(parse(before).role_overrides); + expect(after.workspace_only_roles).toEqual(parse(before).workspace_only_roles); + }); +}); + +test.skipIf(shouldSkipOnCI())("Role overrides: an override of an undefined instance role fails the push", async () => { + await withTestBackend(async (backend, tempDir) => { + await setup(backend, tempDir, "role_overrides_missing_role"); + await setRoleOverrides(backend, { operator: { capabilities: { flows: "compose" } } }); + + const pull = await backend.runCLICommand(["sync", "pull", "--yes"], tempDir); + expect(pull.code).toEqual(0); + const settings = parse(await readFile(`${tempDir}/settings.yaml`, "utf-8")) as any; + settings.role_overrides.reviewer = { capabilities: { code: false } }; + settings.role_overrides.operator = { capabilities: { flows: "none" } }; + await writeFile(`${tempDir}/settings.yaml`, stringify(settings), "utf-8"); + + const push = await backend.runCLICommand(["sync", "push", "--yes"], tempDir); + expect(push.code).not.toEqual(0); + expect(push.stdout + push.stderr).toContain("`reviewer`"); + expect(push.stdout + push.stderr).toContain("does not define"); + + const roles = await storedRoles(backend); + expect(roles.overrides).toEqual({ operator: { capabilities: { flows: "compose" } } }); + }); +}); + +test.skipIf(shouldSkipOnCI())("Role overrides: a settings.yaml without the keys leaves them alone", async () => { + await withTestBackend(async (backend, tempDir) => { + await setup(backend, tempDir, "role_overrides_unmanaged"); + await setRoleOverrides(backend, { + operator: { capabilities: { flows: "compose" } }, + auditor: { label: "Auditor", capabilities: {} }, + }); + + const pull = await backend.runCLICommand(["sync", "pull", "--yes"], tempDir); + expect(pull.code).toEqual(0); + const settings = parse(await readFile(`${tempDir}/settings.yaml`, "utf-8")) as any; + delete settings.role_overrides; + delete settings.workspace_only_roles; + settings.webhook = "https://example.com/hook"; + await writeFile(`${tempDir}/settings.yaml`, stringify(settings), "utf-8"); + + const push = await backend.runCLICommand(["sync", "push", "--yes"], tempDir); + expect(push.code).toEqual(0); + const roles = await storedRoles(backend); + expect(roles.overrides).toEqual({ + operator: { capabilities: { flows: "compose" } }, + auditor: { label: "Auditor", capabilities: {} }, + }); + }); +}); diff --git a/cli/test/settings_unit.test.ts b/cli/test/settings_unit.test.ts index fb5271aa19..03909abfd7 100644 --- a/cli/test/settings_unit.test.ts +++ b/cli/test/settings_unit.test.ts @@ -269,3 +269,22 @@ describe("migrateToGroupedFormat", () => { expect(result.slack_oauth_client_secret).toBeNull(); }); }); + +describe("migrateToGroupedFormat role overrides", () => { + test("keeps role_overrides and workspace_only_roles for the push", () => { + const settings = { + name: "ws", + role_overrides: { operator: { capabilities: { flows: "compose" } } }, + workspace_only_roles: { auditor: { label: "Auditor", capabilities: {} } }, + }; + const result = migrateToGroupedFormat(settings); + expect(result.role_overrides).toEqual(settings.role_overrides); + expect(result.workspace_only_roles).toEqual(settings.workspace_only_roles); + }); + + test("leaves them unset when the file omits them", () => { + const result = migrateToGroupedFormat({ name: "ws" }); + expect("role_overrides" in result).toBe(false); + expect("workspace_only_roles" in result).toBe(false); + }); +}); diff --git a/docs/workspace-roles.md b/docs/workspace-roles.md index 96c6d3c796..fd7f557498 100644 --- a/docs/workspace-roles.md +++ b/docs/workspace-roles.md @@ -48,6 +48,16 @@ re-adding cannot undo a mapping that restricts. turn every developer into an operator for the raw `is_operator` checks. So the fork routes read it from the member's role (`caller_can_fork`), never through `caller_capabilities`' fast path. +## Git sync and export + +The settings document (`settings.yaml`, `settings.json` in an export) states `role_overrides` in +two keys, split by the instance that writes it: `role_overrides` for overrides of instance roles, +`workspace_only_roles` for roles the workspace adds. The stored column cannot tell them apart, and +a promotion target may define different instance roles. Each key is applied only when stated. +An override naming a role the target instance does not define refuses the whole apply rather than +skipping it: stored, it would become a workspace-only role; dropped, the role would take the +instance's capabilities once defined there. + ## Who is restricted `ApiAuthed::is_operator` means "this member's role is restricted", computed at authentication from diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index 3ee03a96f8..60e200222d 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -1612,6 +1612,8 @@ 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. | | \`operator_settings\` | What operators see and do: 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\`). A write right the value omits keeps its stored value. | +| \`role_overrides\` | \`{ : { label?, capabilities: { code?, flows?, apps?, manage_schedules?, manage_triggers?, fork?, visibility? } } }\`: this workspace's overrides of roles the instance defines. A capability left out follows the instance definition. A role the instance does not define is refused, not skipped. | +| \`workspace_only_roles\` | Same shape: roles this workspace adds (Enterprise only). A role the instance defines is refused here. | | \`mute_critical_alerts\` | Mute the workspace's critical alerts. | | \`slack_team_id\`, \`slack_name\` | Read only: set by connecting Slack on the settings page. | | \`slack_command_script\` / \`teams_command_script\` | Script or flow handling the Slack / Teams command. | diff --git a/system_prompts/auto-generated/skills/workspace-settings/SKILL.md b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md index f739f95aa7..05e05fcfd5 100644 --- a/system_prompts/auto-generated/skills/workspace-settings/SKILL.md +++ b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md @@ -53,6 +53,8 @@ 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. | | `operator_settings` | What operators see and do: 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`). A write right the value omits keeps its stored value. | +| `role_overrides` | `{ : { label?, capabilities: { code?, flows?, apps?, manage_schedules?, manage_triggers?, fork?, visibility? } } }`: this workspace's overrides of roles the instance defines. A capability left out follows the instance definition. A role the instance does not define is refused, not skipped. | +| `workspace_only_roles` | Same shape: roles this workspace adds (Enterprise only). A role the instance defines is refused here. | | `mute_critical_alerts` | Mute the workspace's critical alerts. | | `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. | | `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. | @@ -77,8 +79,8 @@ With `includeSettings: true` in `wmill.yaml`, `wmill sync pull` writes the docum document: a setting the file omits is cleared, except `operator_settings`, `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 -`add_admins_and_developers_to_forks`, which are managed only when the file states them. +`error_handler_fallback_to_instance_alerts`, `add_admins_and_developers_to_forks`, +`role_overrides` and `workspace_only_roles`, which are managed only when the file states them. `datatable_permissions` is pushed only with `includeDatatablePermissions: true` (or `--include-datatable-permissions`). A push ignores `protection_rules`: `protection-rules.yaml` and `wmill protection-rules push` sync them. diff --git a/system_prompts/base/workspace-settings.md b/system_prompts/base/workspace-settings.md index f5e4c7e7d1..415f255c8e 100644 --- a/system_prompts/base/workspace-settings.md +++ b/system_prompts/base/workspace-settings.md @@ -48,6 +48,8 @@ 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. | | `operator_settings` | What operators see and do: 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`). A write right the value omits keeps its stored value. | +| `role_overrides` | `{ : { label?, capabilities: { code?, flows?, apps?, manage_schedules?, manage_triggers?, fork?, visibility? } } }`: this workspace's overrides of roles the instance defines. A capability left out follows the instance definition. A role the instance does not define is refused, not skipped. | +| `workspace_only_roles` | Same shape: roles this workspace adds (Enterprise only). A role the instance defines is refused here. | | `mute_critical_alerts` | Mute the workspace's critical alerts. | | `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. | | `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. | @@ -73,8 +75,8 @@ With `includeSettings: true` in `wmill.yaml`, `wmill sync pull` writes the docum document: a setting the file omits is cleared, except `operator_settings`, `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 -`add_admins_and_developers_to_forks`, which are managed only when the file states them. +`error_handler_fallback_to_instance_alerts`, `add_admins_and_developers_to_forks`, +`role_overrides` and `workspace_only_roles`, which are managed only when the file states them. `datatable_permissions` is pushed only with `includeDatatablePermissions: true` (or `--include-datatable-permissions`). A push ignores `protection_rules`: `protection-rules.yaml` and `wmill protection-rules push` sync them.