feat: let a role without code use the Hub scripts an admin allows

This commit is contained in:
AlexRV12
2026-11-27 14:30:22 +01:00
parent 5b3a40b1a4
commit 9c012b659e
47 changed files with 1115 additions and 165 deletions
@@ -1,15 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE workspace_settings SET role_overrides =\n (SELECT role_overrides FROM workspace_settings WHERE workspace_id = $2)\n WHERE workspace_id = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text"
]
},
"nullable": []
},
"hash": "0d73210f3ce58d0dd8fd850c1df8d16414daad90ad8b0ea35a769d78626039aa"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE workspace_settings SET (role_overrides, hub_access) =\n (SELECT role_overrides, hub_access FROM workspace_settings WHERE workspace_id = $2)\n WHERE workspace_id = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text"
]
},
"nullable": []
},
"hash": "17fca8d19f4e243eb7863efdb102efd37f0e83f38d65576ff9ba0a54e5305de6"
}
@@ -1,15 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Text"
]
},
"nullable": []
},
"hash": "4693a6932e0f09f8d0a929bde83cc0aa58df96928eed3c05c515476771538c3a"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, hub_access, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, hub_access, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Text"
]
},
"nullable": []
},
"hash": "c013762a78f431d4911132e44503f46c168973498385765c2403e4e780ed6814"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE workspace_settings SET hub_access = $1 WHERE workspace_id = $2",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Jsonb",
"Text"
]
},
"nullable": []
},
"hash": "f850b4c4579708431792503e56204f54f35feba001bb9ceafba62b22f6058c54"
}
+1 -1
View File
@@ -1 +1 @@
c05fadda9d6bd772e56cec00d5b9c721afab4aed
7f6594fffc090a061e84ec3ed5bc5a52a45e6ca0
@@ -0,0 +1 @@
ALTER TABLE workspace_settings DROP COLUMN IF EXISTS hub_access;
@@ -0,0 +1,3 @@
-- The workspace's own list of Hub integrations members without code may use,
-- `{"<integration>": "read" | "write"}`. NULL follows the instance's `hub_access` setting.
ALTER TABLE workspace_settings ADD COLUMN IF NOT EXISTS hub_access JSONB;
+2 -1
View File
@@ -2070,7 +2070,8 @@ async fn process_notify_event(
DISABLE_PASSWORD_LOGIN_SETTING => {
load_disable_password_login(db).await;
}
windmill_common::global_settings::WORKSPACE_ROLES_SETTING => {
windmill_common::global_settings::WORKSPACE_ROLES_SETTING
| windmill_common::global_settings::HUB_ACCESS_SETTING => {
windmill_common::roles::invalidate_all_roles_cache();
}
MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING => {
+11
View File
@@ -0,0 +1,11 @@
-- Workspace `hub-grant`, where `operator` composes flows and Slack's read-only Hub scripts are
-- allowed. Its own workspace: roles are cached per workspace id across a test binary's tests.
-- test-user is its admin, test-user-3 (SECRET_TOKEN_3) its operator.
INSERT INTO workspace (id, name, owner) VALUES ('hub-grant', 'hub-grant', 'test-user');
INSERT INTO workspace_key (workspace_id, kind, key) VALUES ('hub-grant', 'cloud', 'test-key');
INSERT INTO workspace_settings (workspace_id, role_overrides, hub_access) VALUES ('hub-grant',
'{"operator": {"capabilities": {"flows": "compose"}}}', '{"Slack": "read"}');
INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES ('hub-grant', 'all', 'All users', '{}');
INSERT INTO usr (workspace_id, email, username, is_admin, operator, role) VALUES
('hub-grant', 'test@windmill.dev', 'test-user', true, false, 'Admin'),
('hub-grant', 'test3@windmill.dev', 'test-user-3', false, true, 'Operator');
+71 -5
View File
@@ -1,5 +1,5 @@
//! A builder choosing a Hub step in a flow, an agent or an app is held to the run-time rule for
//! naming a Hub path: refused without `code`, allowed with it.
//! naming a Hub path: refused without `code` or a grant, allowed with either.
use reqwest::multipart;
use serde_json::{json, Value};
@@ -9,7 +9,7 @@ use windmill_test_utils::*;
const CODER: &str = "SECRET_TOKEN_2";
const OP: &str = "SECRET_TOKEN_3";
const HUB_PATH: &str = "hub/990000794/test/echo";
const REFUSAL: &str = "Hub scripts and flows require a role that can write code";
const REFUSAL: &str = "Your role may not use this Hub script";
fn flow(path: &str) -> Value {
json!({"modules": [{"id": "a", "value": {"type": "script", "path": path, "input_transforms": {}}}]})
@@ -110,9 +110,7 @@ async fn a_hub_step_follows_the_code_capability(db: Pool<Postgres>) -> anyhow::R
/// a personal one. Its own operator, so no other test has warmed the role cache for it; the
/// overrides match the other test's, since the workspace's roles are cached across tests.
#[sqlx::test(fixtures("base"))]
async fn a_hub_step_is_refused_on_a_one_connection_pool(
db: Pool<Postgres>,
) -> anyhow::Result<()> {
async fn a_hub_step_is_refused_on_a_one_connection_pool(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
sqlx::raw_sql(
r#"UPDATE workspace_settings SET role_overrides = '{
@@ -179,3 +177,71 @@ async fn a_hub_step_is_refused_on_a_one_connection_pool(
}
Ok(())
}
/// A save checks its Hub steps inside its transaction, so the Hub lookup must not need a second
/// connection: with the only one of the pool held, a granted step passes and a step the list does
/// not cover is refused with the reason. The Hub is asked once, whatever the steps.
#[sqlx::test(fixtures("base"))]
async fn the_hub_check_needs_no_second_connection(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let meta = |id: i32, read_only: bool| {
json!({ "version_id": id, "ask_id": 1, "app": "Slack", "read_only": read_only,
"script_approved": true, "version_ever_approved": true })
};
let (_, calls) = start_stub_hub(vec![
meta(990000821, true),
meta(990000822, false),
meta(990000823, true),
])
.await;
let one = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.acquire_timeout(std::time::Duration::from_secs(5))
.connect_with((*db.connect_options()).clone())
.await?;
let authed = windmill_api_auth::ApiAuthed {
email: "test3@windmill.dev".into(),
username: "test-user-3".into(),
is_operator: true,
capabilities: Some(windmill_common::roles::RoleCapabilities {
hub: serde_json::from_value(json!({"slack": "read"}))?,
..windmill_common::roles::RoleCapabilities::OPERATOR
}),
..Default::default()
};
for (ids, refusal) in [
([990000821, 990000823], None),
(
[990000821, 990000822],
Some("hub/990000822/slack/list: This Hub script can write"),
),
] {
let steps = ids
.iter()
.map(|id| {
windmill_common::runnable_ref::RunnableRef::from_path(
&format!("hub/{id}/slack/list"),
false,
)
.unwrap()
})
.collect::<Vec<_>>();
calls.store(0, std::sync::atomic::Ordering::SeqCst);
let tx = one.begin().await?;
let res = windmill_api_auth::composed::check_builder_can_name_hub(
&steps,
&authed,
&one,
"test-workspace",
)
.await;
tx.rollback().await?;
match (res, refusal) {
(Ok(()), None) => {}
(Err(e), Some(text)) if e.to_string().contains(text) => {}
(res, _) => panic!("{ids:?}: {res:?}"),
}
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
}
Ok(())
}
+200 -5
View File
@@ -1,5 +1,5 @@
//! A Hub path named at run time is refused to a member whose role cannot write code, on every
//! route that takes one.
//! A Hub path named at run time is refused to a member whose role does not write code, unless
//! the Hub access list allows that script, on every route that takes one.
use serde_json::json;
use sqlx::{Pool, Postgres};
@@ -12,8 +12,9 @@ use windmill_test_utils::*;
const DEV: &str = "SECRET_TOKEN_2";
const OP: &str = "OPERATOR_TOKEN";
const HUB_ID: i32 = 990000792;
const REFUSAL: &str = "Hub scripts and flows require a role that can write code";
const HUB_ID: i32 = 9990792;
const REFUSAL: &str = "Your role may not use this Hub script";
const FLOW_REFUSAL: &str = "Hub flows require a role that can write code";
#[sqlx::test(fixtures("base"))]
async fn a_hub_path_named_without_code_is_refused(db: Pool<Postgres>) -> anyhow::Result<()> {
@@ -135,8 +136,13 @@ async fn a_hub_path_named_without_code_is_refused(db: Pool<Postgres>) -> anyhow:
async {
for route in routes {
let (status, body) = send(OP, route).await;
let reason = if route == "app component flow" {
FLOW_REFUSAL
} else {
REFUSAL
};
// Batch rerun reports every failure as the same "Couldn't re-run" line.
let refused = (status == 403 && body.contains(REFUSAL))
let refused = (status == 403 && body.contains(reason))
|| (route == "batch_rerun" && body.starts_with("Error: "));
assert!(refused, "op on {route}: {status} {body}");
@@ -210,3 +216,192 @@ async fn the_rule_reads_code_from_the_caller(db: Pool<Postgres>) -> anyhow::Resu
check(op(Some(coder)), dead).await?;
Ok(())
}
const SLACK_READ: i32 = 990000801;
const SLACK_WRITE: i32 = 990000802;
const SLACK_SCRIPT_UNAPPROVED: i32 = 990000803;
const SLACK_VERSION_UNAPPROVED: i32 = 990000805;
const GITHUB: i32 = 990000804;
fn meta(
version_id: i32,
app: &str,
read_only: bool,
script_approved: bool,
version_ever_approved: bool,
) -> serde_json::Value {
json!({ "version_id": version_id, "ask_id": 1, "app": app, "read_only": read_only,
"script_approved": script_approved, "version_ever_approved": version_ever_approved })
}
/// A role without code, where Slack is allowed at read, names Slack's approved read-only Hub scripts and
/// nothing else, each refusal saying why; a role with nothing allowed never asks the Hub.
#[sqlx::test(fixtures("base", "hub_grant"))]
async fn a_hub_grant_admits_approved_scripts_of_its_integration(
db: Pool<Postgres>,
) -> anyhow::Result<()> {
initialize_tracing().await;
let (hub, calls) = start_stub_hub(vec![
meta(SLACK_READ, "Slack", true, true, true),
meta(SLACK_WRITE, "slack", false, true, true),
meta(SLACK_SCRIPT_UNAPPROVED, "slack", true, false, true),
meta(SLACK_VERSION_UNAPPROVED, "slack", true, true, false),
meta(GITHUB, "github", true, true, true),
])
.await;
let server = ApiServer::start(db.clone()).await?;
let ws = format!("http://localhost:{}/api/w/hub-grant", server.addr.port());
let client = reqwest::Client::new();
let resp = client
.post(format!("{ws}/jobs/run/p/hub/{SLACK_READ}/slack/list"))
.bearer_auth("SECRET_TOKEN_3")
.json(&json!({}))
.send()
.await?;
assert!(resp.status().is_success(), "{}", resp.text().await?);
let caps = |hub: serde_json::Value| RoleCapabilities {
hub: serde_json::from_value(hub).unwrap(),
..RoleCapabilities::OPERATOR
};
let check = |caps: RoleCapabilities, id: i32| {
let db = db.clone();
async move {
let authed = windmill_api_auth::ApiAuthed {
email: "test3@windmill.dev".into(),
username: "test-user-3".into(),
is_operator: true,
capabilities: Some(caps),
..Default::default()
};
let hub = RunnableRef::from_path(&format!("hub/{id}/slack/x"), false).unwrap();
check_can_name_runnable(
&RunOrigin::NamedBy(authed.to_authed_ref()),
&hub,
&db,
"hub-grant",
)
.await
.map_err(|e| e.to_string())
}
};
let slack_read = || caps(json!({"slack": "read"}));
for (id, reason) in [
(
SLACK_WRITE,
"can write to `slack` and your role may only use its read-only scripts",
),
(SLACK_SCRIPT_UNAPPROVED, "is not approved on the Hub"),
(SLACK_VERSION_UNAPPROVED, "is not approved on the Hub"),
(GITHUB, "may not use the Hub scripts of `github`"),
(990000806, "is not on the Hub"),
] {
let err = check(slack_read(), id).await.unwrap_err();
assert!(err.contains(reason), "{id}: {err}");
}
check(caps(json!({"slack": "write"})), SLACK_WRITE)
.await
.unwrap();
let before = calls.load(std::sync::atomic::Ordering::SeqCst);
let err = check(RoleCapabilities::OPERATOR, 990000809)
.await
.unwrap_err();
assert!(err.contains(REFUSAL), "{err}");
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), before);
// Another Hub's script of the same id, cached above, is not what this Hub's approval admits.
let (other_hub, _) = start_stub_hub(vec![]).await;
let script = windmill_common::scripts::get_full_hub_script_by_id(
SLACK_READ,
&windmill_common::utils::HTTP_CLIENT,
None,
)
.await?;
assert_eq!(script.content, format!("echo {other_hub}"));
for (url, id, reason) in [
(
"http://127.0.0.1:1".to_string(),
990000810,
"the Hub is unreachable",
),
(
format!("{hub}/predates-access-meta"),
990000811,
"needs an update",
),
] {
windmill_common::HUB_BASE_URL.store(std::sync::Arc::new(url));
let err = check(slack_read(), id).await.unwrap_err();
assert!(err.contains(reason), "{id}: {err}");
}
Ok(())
}
/// Only an admin writes the workspace's list. An empty one is not the instance's: it allows nothing.
/// Its own workspace: roles are cached per workspace id across the tests.
#[sqlx::test(fixtures("base"))]
async fn a_workspace_replaces_its_hub_access_list(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
sqlx::raw_sql(
"INSERT INTO workspace (id, name, owner) VALUES ('hub-list', 'hub-list', 'test-user');
INSERT INTO workspace_key (workspace_id, kind, key) VALUES ('hub-list', 'cloud', 'test-key');
INSERT INTO workspace_settings (workspace_id) VALUES ('hub-list');
INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES ('hub-list', 'all', '', '{}');
INSERT INTO usr (workspace_id, email, username, is_admin, operator, role) VALUES
('hub-list', 'test@windmill.dev', 'test-user', true, false, 'Admin'),
('hub-list', 'test2@windmill.dev', 'test-user-2', false, false, 'User');",
)
.execute(&db)
.await?;
let server = ApiServer::start(db.clone()).await?;
let ws = format!(
"http://localhost:{}/api/w/hub-list/workspaces",
server.addr.port()
);
let client = reqwest::Client::new();
let write = |token: &'static str, list: serde_json::Value| {
client
.post(format!("{ws}/hub_access"))
.bearer_auth(token)
.json(&json!({ "hub_access": list }))
.send()
};
let status = write(DEV, json!({"slack": "write"})).await?.status();
assert_eq!(status, 403);
let typo = client
.post(format!("{ws}/hub_access"))
.bearer_auth("SECRET_TOKEN")
.json(&json!({ "hubAccess": {} }))
.send()
.await?;
assert_eq!(typo.status(), 422);
for (list, stored) in [
(json!({"Slack": "read"}), json!({"slack": "read"})),
(json!({}), json!({})),
(json!(null), json!(null)),
] {
let resp = write("SECRET_TOKEN", list).await?;
assert!(resp.status().is_success(), "{}", resp.text().await?);
let roles: serde_json::Value = client
.get(format!("{ws}/roles"))
.bearer_auth("SECRET_TOKEN")
.send()
.await?
.json()
.await?;
assert_eq!(roles["hub_access"], stored);
let operator = roles["roles"]
.as_array()
.unwrap()
.iter()
.find(|r| r["name"] == "operator")
.unwrap();
let effective = if stored.is_null() { json!({}) } else { stored };
assert_eq!(operator["capabilities"]["hub"], effective);
}
Ok(())
}
+2 -2
View File
@@ -1,5 +1,5 @@
//! A Hub path saved into a trigger or a schedule is checked when it is chosen, against the member
//! saving it: refused without `code`, and only on the paths the save changes.
//! saving it: refused without `code` or the Hub access list, and only on the paths the save changes.
use serde_json::{json, Value};
use sqlx::{Pool, Postgres};
@@ -10,7 +10,7 @@ const OP: &str = "OPERATOR_TOKEN";
const HUB: &str = "hub/990000802/test/echo";
const OTHER_HUB: &str = "hub/990000803/test/echo";
const PRESET: &str = "hub/2431/slack/schedule-error-handler-slack";
const REFUSAL: &str = "Hub scripts and flows require a role that can write code";
const REFUSAL: &str = "Your role may not use this Hub script";
#[cfg(feature = "http_trigger")]
fn http(path: &str, script_path: &str, error_handler: Option<&str>) -> Value {
+1 -1
View File
@@ -16,7 +16,7 @@ async fn hub_target_with_retry_runs_its_preprocessor(db: Pool<Postgres>) -> anyh
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let version = "990000004";
let version = "9990004";
let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR;
tokio::fs::create_dir_all(hub_dir).await?;
tokio::fs::write(
+2 -2
View File
@@ -288,7 +288,7 @@ async fn test_error_handler_triggered_on_hub_script_failure(
let server = ApiServer::start(db.clone()).await?;
let version = "990000002";
let version = "9990002";
let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR;
tokio::fs::create_dir_all(hub_dir).await?;
tokio::fs::write(
@@ -386,7 +386,7 @@ async fn test_success_handler_triggered_on_hub_script_success(
let server = ApiServer::start(db.clone()).await?;
let version = "990000003";
let version = "9990003";
let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR;
tokio::fs::create_dir_all(hub_dir).await?;
tokio::fs::write(
+16 -20
View File
@@ -6,7 +6,7 @@ use sqlx::{Postgres, Transaction};
use windmill_common::{
error::{self, Error},
flows::FlowValue,
jobs::{check_can_name_runnable, RunOrigin},
jobs::{check_can_name_runnables, RunOrigin},
roles::AuthorLevel,
runnable_ref::RunnableRef,
workspaces::{check_operator_can_build, BuilderKind},
@@ -15,32 +15,32 @@ use windmill_common::{
use crate::{get_scope_tags, is_super_admin_authed, ApiAuthed};
/// The run-time rule for naming a Hub path, applied to one a builder saves. A save can hold many
/// Hub paths, so a refusal names the one it is about.
/// The run-time rule for naming a Hub path, applied to those a builder saves. A refusal names the
/// path it is about.
pub async fn check_builder_can_name_hub(
runnable: &RunnableRef,
runnables: &[RunnableRef],
authed: &ApiAuthed,
db: &DB,
w_id: &str,
) -> error::Result<()> {
let origin = RunOrigin::NamedBy(authed.to_authed_ref());
check_can_name_runnable(&origin, runnable, db, w_id)
check_can_name_runnables(&origin, runnables, db, w_id)
.await
.map_err(|e| name_refused_path(runnable, e))
.map_err(|(runnable, e)| name_refused_path(runnable, e))
}
fn name_refused_path(runnable: &RunnableRef, e: Error) -> Error {
match e {
Error::PermissionDenied(msg) => {
fn name_refused_path(runnable: Option<&RunnableRef>, e: Error) -> Error {
match (runnable, e) {
(Some(runnable), Error::PermissionDenied(msg)) => {
Error::PermissionDenied(format!("{}: {msg}", runnable.path()))
}
e => e,
(_, e) => e,
}
}
/// Refuses each of `new` that `old` does not hold and that needs `code`. A trigger or schedule
/// save is checked on the paths it changes only, so a member without `code` can still edit one
/// that already runs a Hub path; nothing is checked at fire. `old` must be the row locked by the
/// Refuses `new` if it holds a path that `old` does not and that the caller may not name. A trigger
/// or schedule save is checked on the paths it changes only, so a member can still edit one that
/// already runs a Hub path they may not name; nothing is checked at fire. `old` must be the row locked by the
/// save, or a concurrent edit could slip a removed Hub path back in as unchanged.
pub async fn check_new_hub_paths(
new: &[RunnableRef],
@@ -49,10 +49,8 @@ pub async fn check_new_hub_paths(
db: &DB,
w_id: &str,
) -> error::Result<()> {
for runnable in new.iter().filter(|r| !old.contains(r)) {
check_builder_can_name_hub(runnable, authed, db, w_id).await?;
}
Ok(())
let added: Vec<_> = new.iter().filter(|r| !old.contains(r)).cloned().collect();
check_builder_can_name_hub(&added, authed, db, w_id).await
}
/// `validate_operator_composed_flow` on a transaction the caller already holds, so a write that
@@ -67,9 +65,7 @@ pub async fn authorize_composed_flow(
w_id: &str,
) -> error::Result<()> {
let mut refs = windmill_common::flows::check_flow_is_composition_only(value)?;
for runnable in &refs.hub_runnables {
check_builder_can_name_hub(runnable, authed, db, w_id).await?;
}
check_builder_can_name_hub(&refs.hub_runnables, authed, db, w_id).await?;
// A builder links only an agent it can read, and binds only the tool inputs it leaves open.
for agent in &refs.agents {
+2 -2
View File
@@ -127,7 +127,7 @@ impl ApiAuthed {
folders: &self.folders,
scopes: &self.scopes,
token_prefix: &self.token_prefix,
capabilities: self.capabilities,
capabilities: self.capabilities.clone(),
}
}
@@ -240,7 +240,7 @@ impl Authable for ApiAuthed {
}
fn capabilities(&self) -> Option<RoleCapabilities> {
self.capabilities
self.capabilities.clone()
}
fn groups(&self) -> &[String] {
+8 -2
View File
@@ -69,8 +69,8 @@ use windmill_common::{
CRITICAL_ALERT_MUTE_UI_SETTING, CUSTOM_TAGS_SETTING, DEFAULT_TAGS_WORKSPACES_SETTING,
DISABLE_HUB_SETTING, EMAIL_DOMAIN_SETTING, ENV_SETTINGS, EXTERNAL_INSTANCE_PG_SETTING,
GITHUB_APP_WEBHOOK_BASE_URL_SETTING, HTTP_ROUTE_DEFAULT_ALLOWED_ORIGINS_SETTING,
HTTP_ROUTE_WORKSPACED_ROUTE_SETTING, HUB_ACCESSIBLE_URL_SETTING, HUB_BASE_URL_SETTING,
INSTANCE_BANNER_SETTING, MAX_RETENTION_OVERRIDE_WORKSPACES,
HTTP_ROUTE_WORKSPACED_ROUTE_SETTING, HUB_ACCESSIBLE_URL_SETTING, HUB_ACCESS_SETTING,
HUB_BASE_URL_SETTING, INSTANCE_BANNER_SETTING, MAX_RETENTION_OVERRIDE_WORKSPACES,
MAX_TOKEN_EXPIRATION_DAYS_SETTING, MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING,
RETENTION_PERIOD_SECS_OVERRIDES_SETTING, RUFF_CONFIG_SETTING, UNIQUE_ID_SETTING,
WORKSPACE_FAIRNESS_DURATION_SECS_SETTING, WORKSPACE_FAIRNESS_ENABLED_SETTING,
@@ -1006,6 +1006,9 @@ async fn run_setting_post_write_hook(db: &DB, key: &str) -> error::Result<()> {
if key == WORKSPACE_ROLES_SETTING {
windmill_common::roles::after_instance_roles_write(db).await?;
}
if key == HUB_ACCESS_SETTING {
windmill_common::roles::invalidate_all_roles_cache();
}
Ok(())
}
@@ -1042,6 +1045,9 @@ async fn run_setting_pre_write_hook(
WORKSPACE_ROLES_SETTING => {
windmill_common::roles::validate_instance_roles_write(db, Some(value)).await?;
}
HUB_ACCESS_SETTING => {
windmill_common::roles::validate_instance_hub_access_write(db, value).await?;
}
// Settings that fail validation would only surface on the next secret read, as an error
// on every secret of every workspace.
windmill_common::global_settings::SECRET_BACKEND_SETTING => {
+3 -3
View File
@@ -2585,18 +2585,18 @@ pub async fn set_workspace_role(
username: &str,
role: &str,
) -> Result<()> {
let caps = windmill_common::roles::workspace_roles_on(&mut **tx, w_id)
let code = windmill_common::roles::workspace_roles_on(&mut **tx, w_id)
.await?
.iter()
.find(|r| r.name == role)
.map(|r| r.capabilities)
.map(|r| r.capabilities.code)
.ok_or_else(|| {
Error::BadRequest(format!("role `{role}` is not defined in workspace {w_id}"))
})?;
sqlx::query!(
"UPDATE usr SET workspace_role = $1, operator = $2 WHERE username = $3 AND workspace_id = $4",
role,
!caps.code,
!code,
username,
w_id
)
@@ -11,8 +11,8 @@ use windmill_audit::{audit_oss::audit_log, ActionKind};
use windmill_common::{
error::{Error, JsonResult, Result},
roles::{
self, instance_roles, load_role_overrides, EffectiveRole, RoleCapabilities, RoleOverrides,
RoleSource, OPERATOR_ROLE,
self, instance_roles, load_role_overrides, EffectiveRole, HubAccessList, RoleCapabilities,
RoleOverrides, RoleSource, OPERATOR_ROLE,
},
utils::require_admin,
DB,
@@ -23,12 +23,16 @@ pub fn workspaced_service() -> Router {
Router::new()
.route("/roles", get(list_roles))
.route("/role_overrides", post(update_role_overrides))
.route("/hub_access", post(update_hub_access))
}
#[derive(Serialize)]
struct WorkspaceRoles {
roles: Vec<EffectiveRole>,
overrides: RoleOverrides,
/// The workspace's own Hub access list, `None` while it follows `instance_hub_access`.
hub_access: Option<HubAccessList>,
instance_hub_access: HubAccessList,
/// Whether this workspace may add roles of its own.
custom_roles_enabled: bool,
/// The caller's role, `None` for a caller with no membership (a superadmin, a guest).
@@ -43,6 +47,7 @@ async fn list_roles(
) -> JsonResult<WorkspaceRoles> {
let roles = roles::workspace_roles(&db, &w_id).await?;
let overrides = load_role_overrides(&db, &w_id).await?;
let hub = roles::load_hub_access(&mut *db.acquire().await?, &w_id).await?;
let my_role = sqlx::query!(
"SELECT workspace_role, operator FROM usr WHERE workspace_id = $1 AND username = $2",
&w_id,
@@ -61,6 +66,8 @@ async fn list_roles(
Ok(Json(WorkspaceRoles {
roles: roles.as_ref().clone(),
overrides,
hub_access: hub.workspace,
instance_hub_access: hub.instance,
custom_roles_enabled: roles::custom_roles_enabled(),
my_role,
my_capabilities,
@@ -182,6 +189,65 @@ pub(crate) async fn write_role_overrides(
Ok(())
}
#[derive(Deserialize)]
pub(crate) struct UpdateHubAccess {
/// `null` follows the instance's list; `{}` allows nothing. `deserialize_with`: an
/// absent key is refused, not read as `null`, so a typo does not drop the list.
#[serde(deserialize_with = "Option::deserialize")]
hub_access: Option<serde_json::Value>,
}
pub(crate) async fn update_hub_access(
authed: ApiAuthed,
Path(w_id): Path<String>,
Extension(db): Extension<DB>,
Json(body): Json<UpdateHubAccess>,
) -> Result<String> {
require_admin(authed.is_admin, &authed.username)?;
let hub_access = body
.hub_access
.as_ref()
.map(roles::parse_hub_access)
.transpose()?
.map(|list| serde_json::json!(list));
let mut tx = db.begin().await?;
sqlx::query!(
"UPDATE workspace_settings SET hub_access = $1 WHERE workspace_id = $2",
hub_access,
&w_id
)
.execute(&mut *tx)
.await?;
roles::notify_role_overrides_change(&mut tx, &w_id).await?;
let audited = hub_access.unwrap_or_default().to_string();
audit_log(
&mut *tx,
&authed,
"workspaces.update_hub_access",
ActionKind::Update,
&w_id,
None,
Some([("hub_access", audited.as_str())].into()),
)
.await?;
tx.commit().await?;
roles::invalidate_workspace_roles_cache(&w_id);
handle_deployment_metadata(
&authed.email,
&authed.username,
&db,
&w_id,
windmill_git_sync::DeployedObject::Settings { setting_type: "hub_access".to_string() },
Some("Workspace Hub scripts updated".to_string()),
false,
None,
)
.await?;
Ok("Hub access updated".to_string())
}
/// The legacy `/operator_settings` payload. Visibility flags always serialize; the rights are
/// `Option` because git-sync posts whole files that may predate them, and an absent key must
/// leave the stored value alone.
@@ -241,14 +307,13 @@ pub(crate) async fn update_operator_settings(
let base = base.capabilities;
let mut overrides = load_role_overrides(&db, &w_id).await?;
let current = roles::workspace_roles(&db, &w_id)
let mut target = roles::workspace_roles(&db, &w_id)
.await?
.iter()
.find(|r| r.name == OPERATOR_ROLE)
.map(|r| r.capabilities)
.unwrap_or(base);
.map(|r| r.capabilities.clone())
.unwrap_or_else(|| base.clone());
let mut target = current;
let v = &mut target.visibility;
(v.runs, v.schedules, v.resources, v.variables, v.assets) = (
settings.runs,
@@ -269,8 +334,8 @@ pub(crate) async fn update_operator_settings(
Some(false) => roles::AuthorLevel::None,
_ => cur,
};
target.flows = compose_or_keep(current.flows, settings.builder_flows);
target.apps = compose_or_keep(current.apps, settings.builder_apps);
target.flows = compose_or_keep(target.flows, settings.builder_flows);
target.apps = compose_or_keep(target.apps, settings.builder_apps);
if let Some(b) = settings.manage_schedules {
target.manage_schedules = b;
}
@@ -650,14 +650,15 @@ async fn resolve_new_member_role(
None if operator => windmill_common::roles::OPERATOR_ROLE.to_string(),
None => windmill_common::roles::default_role_name(roles.iter().map(|r| r.name.as_str())),
};
let caps = roles
let code = roles
.iter()
.find(|r| r.name == name)
.ok_or_else(|| {
Error::BadRequest(format!("role `{name}` is not defined in workspace {w_id}"))
})?
.capabilities;
Ok((name, !caps.code))
.capabilities
.code;
Ok((name, !code))
}
/// The role is one choice stored as two flags; both set would show as admin in the UI while the
@@ -8156,28 +8157,27 @@ async fn fork_roles(db: &DB, parent_workspace_id: &str) -> Result<ForkRoles> {
let mut out = ForkRoles { from: vec![], to: vec![], to_operator: vec![] };
for role in roles.iter() {
let to = mapping.get(&role.name).unwrap_or(&role.name);
let caps = roles
let code = roles
.iter()
.find(|r| &r.name == to)
.map(|r| r.capabilities)
.unwrap_or(windmill_common::roles::RoleCapabilities::NONE);
.is_some_and(|r| r.capabilities.code);
out.from.push(role.name.clone());
out.to.push(to.clone());
out.to_operator.push(!caps.code);
out.to_operator.push(!code);
}
Ok(out)
}
/// Give the fork the parent's workspace-only roles and overrides, so a role carried into the fork
/// means there what it means in the parent.
/// Give the fork the parent's workspace-only roles, overrides and Hub access list, so a role carried
/// into the fork means there what it means in the parent.
async fn copy_workspace_roles(
tx: &mut Transaction<'_, Postgres>,
source_workspace_id: &str,
target_workspace_id: &str,
) -> Result<()> {
sqlx::query!(
"UPDATE workspace_settings SET role_overrides =
(SELECT role_overrides FROM workspace_settings WHERE workspace_id = $2)
"UPDATE workspace_settings SET (role_overrides, hub_access) =
(SELECT role_overrides, hub_access FROM workspace_settings WHERE workspace_id = $2)
WHERE workspace_id = $1",
target_workspace_id,
source_workspace_id,
@@ -15950,6 +15950,7 @@ pub enum SettingsEdit {
OperatorSettings,
/// Body: the workspace's role overrides as a whole, `{ "<role>": { label?, capabilities } }`.
RoleOverrides,
HubAccess,
Datatable,
SlackCommand,
SetSlackOAuth,
@@ -16018,6 +16019,10 @@ pub async fn apply_settings_edit(
crate::workspace_roles::update_role_overrides(a, p, d, settings_edit_body(edit, body)?)
.await?
}
HubAccess => {
crate::workspace_roles::update_hub_access(a, p, d, settings_edit_body(edit, body)?)
.await?
}
Datatable => {
let Json(result) =
edit_datatable_config(a, d, p, settings_edit_body(edit, body)?).await?;
@@ -152,7 +152,7 @@ pub(crate) async fn change_workspace_id(
// Duplicate workspace settings (keep copy in old workspace for reference)
info!("Duplicating workspace_settings table");
sqlx::query!(
"INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2",
"INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, hub_access, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, hub_access, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2",
&rw.new_id,
&old_id
)
+57 -1
View File
@@ -4221,6 +4221,36 @@ paths:
schema:
type: string
/w/{workspace}/workspaces/hub_access:
post:
operationId: updateWorkspaceHubAccess
summary: Replace the workspace's Hub access list
description: The Hub integrations whose approved scripts members without code may use in this workspace. `null` follows the instance's list; a list replaces it, and an empty one allows nothing. Requires workspace admin privileges.
tags:
- workspace
parameters:
- $ref: "#/components/parameters/WorkspaceId"
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- hub_access
properties:
hub_access:
nullable: true
allOf:
- $ref: "#/components/schemas/HubAccessList"
responses:
"200":
description: Hub access list updated
content:
text/plain:
schema:
type: string
/w/{workspace}/workspaces/compare/{target_workspace_id}:
get:
operationId: compareWorkspaces
@@ -10429,6 +10459,12 @@ paths:
description: the label the hub curates for the integration, null or absent where it names none
type: string
nullable: true
approved_scripts:
description: how many standalone scripts of the integration are approved, of every kind, absent on a hub that does not count them
type: integer
read_only_scripts:
description: how many of the approved scripts are read-only, absent on a hub that does not count them
type: integer
required:
- name
@@ -41105,6 +41141,17 @@ components:
enum: [none, compose, full]
description: How much of a kind of runnable a role may author. `compose` assembles already-deployed runnables with no code of one's own.
HubAccess:
type: string
enum: [read, write]
description: What a role without code may do with the Hub scripts of one integration. `read` allows only versions the Hub approved as read-only; `write` implies `read`.
HubAccessList:
type: object
description: Hub integrations (lowercased) whose approved scripts a role without `code` may name, with the level allowed. A key may not contain `/`.
additionalProperties:
$ref: "#/components/schemas/HubAccess"
RoleVisibility:
type: object
description: Pages a role sees. Not enforced.
@@ -41143,6 +41190,8 @@ components:
description: Fork the workspace.
visibility:
$ref: "#/components/schemas/RoleVisibility"
hub:
$ref: "#/components/schemas/HubAccessList"
required: [code, flows, apps, manage_schedules, manage_triggers, run, fork, visibility]
RoleCapabilitiesPatch:
@@ -41214,6 +41263,13 @@ components:
$ref: "#/components/schemas/EffectiveRole"
overrides:
$ref: "#/components/schemas/RoleOverrides"
hub_access:
nullable: true
description: The workspace's own Hub access list, null while it follows `instance_hub_access`.
allOf:
- $ref: "#/components/schemas/HubAccessList"
instance_hub_access:
$ref: "#/components/schemas/HubAccessList"
custom_roles_enabled:
type: boolean
description: Whether this workspace may add roles of its own.
@@ -41222,7 +41278,7 @@ components:
nullable: true
my_capabilities:
$ref: "#/components/schemas/RoleCapabilities"
required: [roles, overrides, custom_roles_enabled, my_capabilities]
required: [roles, overrides, instance_hub_access, custom_roles_enabled, my_capabilities]
WorkspaceComparison:
type: object
File diff suppressed because one or more lines are too long
+4 -4
View File
@@ -2494,19 +2494,19 @@ pub(crate) async fn validate_operator_composed_app(
let referenced = check_operator_composed_app(write, raw_app, value, policy)?;
// A Hub path has no workspace row to be readable in: it is held to the rule for naming one.
let mut in_workspace = Vec::with_capacity(referenced.len());
let mut hub_runnables = vec![];
for (kind, path) in referenced {
if kind != AppRunnableKind::Agent {
let runnable = RunnableRef::from_path(&path, kind == AppRunnableKind::Flow)?;
if runnable.path().starts_with("hub/") {
windmill_api_auth::composed::check_builder_can_name_hub(
&runnable, authed, db, w_id,
)
.await?;
hub_runnables.push(runnable);
continue;
}
}
in_workspace.push((kind, path));
}
windmill_api_auth::composed::check_builder_can_name_hub(&hub_runnables, authed, db, w_id)
.await?;
require_runnables_readable(authed, db, user_db, w_id, in_workspace).await
}
@@ -81,6 +81,7 @@ struct SettingsRow {
slack_oauth_client_secret: Option<String>,
ducklake: Option<Value>,
dbt_warehouses: Option<Value>,
hub_access: Option<Value>,
deploy_ui: Option<Value>,
teams_command_script: Option<String>,
public_app_execution_limit_per_minute: Option<i32>,
@@ -356,7 +357,7 @@ pub async fn load_settings_document(
ai_config, large_file_storage,
git_sync, default_app, default_scripts, workspace.name AS name, mute_critical_alerts,
color, operator_settings, datatable, slack_team_id, slack_name, slack_command_script,
slack_oauth_client_id, slack_oauth_client_secret, ducklake, dbt_warehouses, deploy_ui,
slack_oauth_client_id, slack_oauth_client_secret, ducklake, dbt_warehouses, hub_access, deploy_ui,
teams_command_script, public_app_execution_limit_per_minute,
guest_jwt_public_key, guest_jwt_jwks_url, error_handler_fallback_to_instance_alerts,
add_admins_and_developers_to_forks
@@ -417,7 +418,7 @@ pub async fn load_settings_document(
// In the order `wmill sync pull` has always written settings.yaml. A key that predates the
// document and is not marked `always` is written only when set, as it always was; a key
// added since is always written, so a pulled file states it and from then on manages it.
let entries: [(&str, Option<Value>, bool); 33] = [
let entries: [(&str, Option<Value>, bool); 34] = [
("auto_invite", row.auto_invite, false),
("webhook", webhook.map(Value::String), false),
("webhook_events", row.webhook_events.map(|e| json!(e)), true),
@@ -442,6 +443,7 @@ pub async fn load_settings_document(
("color", row.color.map(Value::String), false),
("operator_settings", operator_settings, false),
("role_overrides", Some(role_overrides), true),
("hub_access", row.hub_access, true),
(
"datatable",
windmill_common::workspaces::strip_datatable_permissions(row.datatable),
@@ -764,6 +766,7 @@ const KNOWN_KEYS: &[&str] = &[
"color",
"operator_settings",
"role_overrides",
"hub_access",
"datatable",
"slack_team_id",
"slack_name",
@@ -1645,6 +1648,21 @@ fn plan_document(
|v| json!({ "dbt_warehouses": v }),
);
// Normalized, so a list spelled as the endpoint would not store it is no change.
let hub_access = p
.managed("hub_access")
.map(|v| match v {
Value::Null => Ok(Value::Null),
v => roles::parse_hub_access(&v).map(|list| json!(list)),
})
.transpose()?;
p.simple(
"hub_access",
hub_access,
Target::Edit(SettingsEdit::HubAccess),
|v| json!({ "hub_access": v }),
);
let deploy_ui = p.managed("deploy_ui");
p.simple(
"deploy_ui",
+3 -3
View File
@@ -37,7 +37,7 @@ impl Authed {
folders: &self.folders,
scopes: &self.scopes,
token_prefix: &self.token_prefix,
capabilities: self.capabilities,
capabilities: self.capabilities.clone(),
}
}
}
@@ -70,7 +70,7 @@ impl Authable for AuthedRef<'_> {
*self.is_operator
}
fn capabilities(&self) -> Option<RoleCapabilities> {
self.capabilities
self.capabilities.clone()
}
fn groups(&self) -> &[String] {
self.groups
@@ -111,7 +111,7 @@ impl Authable for Authed {
}
fn capabilities(&self) -> Option<RoleCapabilities> {
self.capabilities
self.capabilities.clone()
}
fn groups(&self) -> &[String] {
@@ -495,6 +495,9 @@ pub const ALERT_CONFIG_SETTING: &str = "alert_job_queue_waiting";
/// The instance's workspace roles (EE), a list of `crate::roles::RoleDefinition`.
pub const WORKSPACE_ROLES_SETTING: &str = "workspace_roles";
/// The instance's default `crate::roles::HubAccessList` (EE), which a workspace may replace.
pub const HUB_ACCESS_SETTING: &str = "hub_access";
// Workspace fairness (Enterprise): caps any single workspace at
// `workspace_fairness_max_percent`% of the shared worker pool once it has been
// occupying it for more than `workspace_fairness_duration_secs` seconds. See
@@ -1731,6 +1731,12 @@ pub async fn sync_global_settings_declarative(
.map_err(|e| anyhow::anyhow!("{idp_key}: {e}"))?;
let mut diff = diff_global_settings(current, desired, ApplyMode::Replace);
let hub_key = crate::global_settings::HUB_ACCESS_SETTING;
if let Some((_, hub_access)) = diff.upserts.iter().find(|(k, _)| k.as_str() == hub_key) {
crate::roles::validate_instance_hub_access_write(db, hub_access)
.await
.map_err(|e| anyhow::anyhow!("{hub_key}: {e}"))?;
}
let roles_key = crate::global_settings::WORKSPACE_ROLES_SETTING;
let roles_written = diff.upserts.iter().any(|(k, _)| k == roles_key)
|| diff.deletes.iter().any(|k| k == roles_key);
+88 -11
View File
@@ -177,28 +177,105 @@ impl ChosenBy {
}
}
/// Refuses a Hub script or flow named by a member whose role cannot write code, preset handlers
/// excepted. Gated on the path, not `hub_id()`: a flow at `hub/123` has none.
/// [`check_can_name_runnables`] for a single one.
pub async fn check_can_name_runnable(
origin: &RunOrigin<'_>,
runnable: &RunnableRef,
db: &DB,
w_id: &str,
) -> error::Result<()> {
check_can_name_runnables(origin, std::slice::from_ref(runnable), db, w_id)
.await
.map_err(|(_, e)| e)
}
/// Refuses a Hub script or flow named by a member whose role cannot write code, preset handlers
/// excepted. Gated on the path, not `hub_id()`: a flow at `hub/123` has none. A role without code
/// may still name a Hub script that the workspace's Hub access list allows, as the Hub reports it:
/// approved, in a listed integration, and read-only unless it is listed at `write`.
///
/// The error comes with the runnable it is about, if it is about one. Pass all that one request
/// names together: the Hub is asked about them at once, and a caller may hold a transaction meanwhile.
pub async fn check_can_name_runnables<'r>(
origin: &RunOrigin<'_>,
runnables: &'r [RunnableRef],
db: &DB,
w_id: &str,
) -> std::result::Result<(), (Option<&'r RunnableRef>, Error)> {
use crate::roles::HubAccess;
let RunOrigin::NamedBy(authed) = origin else {
return Ok(());
};
if !runnable.path().starts_with("hub/")
|| runnable.preset_handler().is_some()
|| crate::roles::caller_capabilities(db, w_id, authed)
.await?
.code
{
let named: Vec<&'r RunnableRef> = runnables
.iter()
.filter(|r| r.path().starts_with("hub/") && r.preset_handler().is_none())
.collect();
if named.is_empty() {
return Ok(());
}
Err(Error::PermissionDenied(
"Hub scripts and flows require a role that can write code. Ask a developer to deploy it to the workspace.".to_string(),
))
let caps = crate::roles::caller_capabilities(db, w_id, authed)
.await
.map_err(|e| (None, e))?;
if caps.code {
return Ok(());
}
let refuse = |r: &'r RunnableRef, reason: String| Err((Some(r), Error::PermissionDenied(reason)));
let mut scripts = Vec::with_capacity(named.len());
for r in named {
match r.hub_id() {
Some(id) if !r.is_flow() && !caps.hub.is_empty() => scripts.push((r, id)),
_ => {
let reason = if r.is_flow() {
"Hub flows require a role that can write code. Ask a developer to deploy it to the workspace."
} else {
"Your role may not use this Hub script. Ask an admin to allow its integration, or a developer to deploy it to the workspace."
};
return refuse(r, reason.to_string());
}
}
}
let mut ids: Vec<i32> = scripts.iter().map(|(_, id)| *id).collect();
ids.sort_unstable();
ids.dedup();
let metas = match crate::utils::hub_script_meta(&ids).await {
Ok(metas) => metas,
Err(Error::BadGateway(e)) => {
return Err((
None,
Error::PermissionDenied(format!("Could not check approvals on the Hub: {e}.")),
))
}
Err(e) => return Err((None, e)),
};
for (r, id) in scripts {
let Some(meta) = metas.get(&id) else {
return refuse(r, format!("Hub script version {id} is not on the Hub."));
};
let app = &meta.app;
match caps.hub.get(&app.to_lowercase()) {
Some(HubAccess::Write) => {}
Some(HubAccess::Read) if meta.read_only => {}
Some(HubAccess::Read) => {
return refuse(
r,
format!("This Hub script can write to `{app}` and your role may only use its read-only scripts. Ask an admin to allow writing, or a developer to deploy this one to the workspace."),
)
}
_ => {
return refuse(
r,
format!("Your role may not use the Hub scripts of `{app}`. Ask an admin to allow them, or a developer to deploy this one to the workspace."),
)
}
}
if !(meta.script_approved && meta.version_ever_approved) {
return refuse(
r,
format!("Hub script version {id} is not approved on the Hub, so your role cannot use it."),
);
}
}
Ok(())
}
pub async fn script_path_to_payload<'e>(
+193 -13
View File
@@ -11,7 +11,10 @@
//! computed at authentication from the role, never from `usr.operator` alone: every gate fast-paths
//! on it, so a stale flag would let a restricted member through.
use std::{collections::HashMap, sync::Arc};
use std::{
collections::{BTreeMap, HashMap},
sync::Arc,
};
use quick_cache::sync::Cache;
use serde::{Deserialize, Serialize};
@@ -19,7 +22,7 @@ use serde::{Deserialize, Serialize};
use crate::{
db::Authable,
error::{Error, Result},
global_settings::WORKSPACE_ROLES_SETTING,
global_settings::{HUB_ACCESS_SETTING, WORKSPACE_ROLES_SETTING},
DB,
};
@@ -41,6 +44,86 @@ pub enum AuthorLevel {
Full,
}
/// What a role without `code` may do with the Hub scripts of one integration. `Write` implies
/// `Read`: `Read` allows only versions the Hub approved as read-only. See
/// [`crate::jobs::check_can_name_runnable`].
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum HubAccess {
Read,
Write,
}
/// Hub integrations, lowercased, whose approved scripts a role without `code` may name.
pub type HubAccessList = BTreeMap<String, HubAccess>;
/// A [`HubAccessList`] that every role of a workspace shares. Capabilities are cloned several
/// times per request, so they hold a pointer rather than their own copy of up to every Hub
/// integration. Reads, compares and serializes as the list itself.
#[derive(Clone, Debug, Default)]
pub struct SharedHubAccess(Option<Arc<HubAccessList>>);
impl SharedHubAccess {
pub const EMPTY: Self = Self(None);
}
impl From<HubAccessList> for SharedHubAccess {
fn from(list: HubAccessList) -> Self {
Self((!list.is_empty()).then(|| Arc::new(list)))
}
}
impl std::ops::Deref for SharedHubAccess {
type Target = HubAccessList;
fn deref(&self) -> &HubAccessList {
static EMPTY: HubAccessList = BTreeMap::new();
self.0.as_deref().unwrap_or(&EMPTY)
}
}
impl PartialEq for SharedHubAccess {
fn eq(&self, other: &Self) -> bool {
**self == **other
}
}
impl Eq for SharedHubAccess {}
impl std::hash::Hash for SharedHubAccess {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(**self).hash(state)
}
}
impl Serialize for SharedHubAccess {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
(**self).serialize(s)
}
}
impl<'de> Deserialize<'de> for SharedHubAccess {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
HubAccessList::deserialize(d).map(Self::from)
}
}
/// Parses and normalizes a [`HUB_ACCESS_SETTING`] or `workspace_settings.hub_access` value.
/// Lowercased, since the Hub holds both `Slack` and `slack`. `/` is refused: it is reserved for
/// per-script keys, `<integration>/<ask_id>`.
pub fn parse_hub_access(value: &serde_json::Value) -> Result<HubAccessList> {
let raw: BTreeMap<String, HubAccess> = serde_json::from_value(value.clone())
.map_err(|e| Error::BadRequest(format!("invalid Hub access list: {e}")))?;
let mut out = HubAccessList::new();
for (k, v) in raw {
if k.is_empty() || k.contains('/') || out.insert(k.to_lowercase(), v).is_some() {
return Err(Error::BadRequest(format!(
"invalid or repeated Hub integration `{k}`"
)));
}
}
Ok(out)
}
/// Pages a role sees. Not enforced: hiding a page never stopped an API call, and the enforced
/// rights are the other fields of [`RoleCapabilities`].
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -84,12 +167,12 @@ impl RoleVisibility {
};
}
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
pub struct RoleCapabilities {
/// Author scripts and run code of one's own on a worker: script previews, dependency jobs,
/// dynamic selects, resolving a job's code, data table migrations. `Full` flows or apps
/// require it, since both carry inline code. Previews also need `run`. Also required to name
/// a Hub script or flow at run time (preset handlers excepted), see
/// a Hub script or flow at run time (preset handlers excepted, and scripts `hub` lists), see
/// [`crate::jobs::check_can_name_runnable`].
pub code: bool,
pub flows: AuthorLevel,
@@ -105,6 +188,10 @@ pub struct RoleCapabilities {
/// by every layer, it is granted exactly to an unrestricted role (see [`Self::resolve`]).
pub fork: bool,
pub visibility: RoleVisibility,
/// The Hub scripts a role without `code` may name. Not a setting of the role: filled in from
/// the workspace's [`HubAccessList`] by [`workspace_roles`], and empty on a role with `code`.
#[serde(default)]
pub hub: SharedHubAccess,
}
impl RoleCapabilities {
@@ -117,6 +204,7 @@ impl RoleCapabilities {
run: true,
fork: true,
visibility: RoleVisibility::ALL,
hub: SharedHubAccess::EMPTY,
};
/// The `operator` role as it stood before roles were configurable, and the base any other
@@ -130,6 +218,7 @@ impl RoleCapabilities {
run: true,
fork: false,
visibility: RoleVisibility::ALL,
hub: SharedHubAccess::EMPTY,
};
/// For a restricted caller whose role cannot be resolved: a guest, a removed member's job, a
@@ -143,6 +232,7 @@ impl RoleCapabilities {
run: false,
fork: false,
visibility: RoleVisibility::NONE,
hub: SharedHubAccess::EMPTY,
};
/// What a role named `name` holds before any configuration applies.
@@ -159,7 +249,7 @@ impl RoleCapabilities {
/// left out: it only hides pages, and must not turn a full author into an operator for the
/// raw `is_operator` checks, job permissions and credential caches keyed on it.
pub fn is_restricted(&self) -> bool {
Self { visibility: RoleVisibility::ALL, fork: true, ..*self } != Self::FULL
Self { visibility: RoleVisibility::ALL, fork: true, ..self.clone() } != Self::FULL
}
/// Whether the role authors deployable artifacts and so costs a full seat rather than half.
@@ -643,6 +733,50 @@ pub async fn load_role_overrides<'c, E: sqlx::PgExecutor<'c>>(
}
}
/// The Hub access lists that meet in a workspace.
pub struct HubAccessLists {
pub instance: HubAccessList,
/// `None` follows the instance; an empty list allows nothing.
pub workspace: Option<HubAccessList>,
}
impl HubAccessLists {
pub fn effective(self) -> HubAccessList {
self.workspace.unwrap_or(self.instance)
}
}
/// A stored list that does not parse allows nothing. Reads as the server: the caller must already
/// be a member of `workspace_id`, or act for the server itself.
pub async fn load_hub_access(
conn: &mut sqlx::PgConnection,
workspace_id: &str,
) -> Result<HubAccessLists> {
let (instance, workspace): (Option<serde_json::Value>, Option<serde_json::Value>) =
sqlx::query_as(
"SELECT (SELECT value FROM global_settings WHERE name = $1),
(SELECT hub_access FROM workspace_settings WHERE workspace_id = $2)",
)
.bind(HUB_ACCESS_SETTING)
.bind(workspace_id)
.fetch_one(conn)
.await?;
let parse = |v: Option<serde_json::Value>| {
v.filter(|v| !v.is_null()).map(|v| {
parse_hub_access(&v).unwrap_or_else(|e| {
tracing::error!("ignoring invalid Hub access list: {e:#}");
HubAccessList::new()
})
})
};
// As for the instance's roles, a CE build has none.
let instance = instance.filter(|_| custom_roles_built());
Ok(HubAccessLists {
instance: parse(instance).unwrap_or_default(),
workspace: parse(workspace),
})
}
fn cached_workspace_roles(workspace_id: &str) -> Option<Arc<Vec<EffectiveRole>>> {
let now = chrono::Utc::now().timestamp();
WORKSPACE_ROLES
@@ -651,8 +785,8 @@ fn cached_workspace_roles(workspace_id: &str) -> Option<Arc<Vec<EffectiveRole>>>
.map(|(r, _)| r)
}
/// The roles of `workspace_id`. Cached 60s; `role_overrides` writes and the instance setting drop
/// the entry on every replica.
/// The roles of `workspace_id`. Cached 60s; `role_overrides` and `hub_access` writes and the instance
/// settings drop the entry on every replica.
///
/// Call it before opening an RLS transaction: on a cache miss it takes a connection from the root
/// pool, and a second pooled connection held alongside a transaction self-deadlocks on a
@@ -674,7 +808,12 @@ pub async fn workspace_roles_on(
}
let instance = instance_roles_on(&mut *conn).await?;
let overrides = load_role_overrides(&mut *conn, workspace_id).await?;
let roles = Arc::new(effective_roles(&instance, &overrides)?);
let hub = SharedHubAccess::from(load_hub_access(&mut *conn, workspace_id).await?.effective());
let mut roles = effective_roles(&instance, &overrides)?;
for role in roles.iter_mut().filter(|r| !r.capabilities.code) {
role.capabilities.hub = hub.clone();
}
let roles = Arc::new(roles);
WORKSPACE_ROLES.insert(
workspace_id.to_string(),
(
@@ -719,9 +858,7 @@ pub async fn member_is_restricted(
.await?
.iter()
.find(|r| r.name == name)
.map(|r| r.capabilities)
.unwrap_or(RoleCapabilities::NONE)
.is_restricted())
.map_or(true, |r| r.capabilities.is_restricted()))
}
/// [`member_is_restricted`] for a caller holding no connection.
@@ -819,8 +956,8 @@ pub fn invalidate_workspace_roles_cache(workspace_id: &str) {
pub const ROLE_OVERRIDES_CHANGE_CHANNEL: &str = "notify_role_overrides_change";
/// Tells every replica to drop its cached roles for the workspace. Call it in the transaction
/// that writes `role_overrides`: a replica that missed it keeps authorizing whatever the workspace
/// just withdrew until its entry expires.
/// that writes `role_overrides` or `hub_access`: a replica that missed it keeps authorizing whatever
/// the workspace just withdrew until its entry expires.
pub async fn notify_role_overrides_change(
conn: &mut sqlx::PgConnection,
workspace_id: &str,
@@ -961,6 +1098,28 @@ pub async fn validate_instance_roles_write(
Ok(())
}
/// Checks a write of [`HUB_ACCESS_SETTING`] before it is stored. Every writer of the setting must
/// call it, the declarative config sync included. Without a license the stored list is frozen:
/// it can be cleared or written back unchanged.
pub async fn validate_instance_hub_access_write(db: &DB, value: &serde_json::Value) -> Result<()> {
if value.is_null() {
return Ok(());
}
let next = parse_hub_access(value)?;
if custom_roles_enabled() {
return Ok(());
}
let current =
crate::global_settings::load_value_from_global_settings(db, HUB_ACCESS_SETTING).await?;
if next.is_empty() || current.and_then(|v| parse_hub_access(&v).ok()) == Some(next) {
return Ok(());
}
Err(Error::BadRequest(
"changing the instance's Hub scripts requires a valid Windmill Enterprise Edition license"
.to_string(),
))
}
/// Side effects of a stored `workspace_roles` write, owed by every writer. The seat table is read
/// by billing on every replica, so it is rebuilt here rather than on the notify that drops the
/// role caches.
@@ -1092,6 +1251,27 @@ mod tests {
assert!(op.capabilities.is_author());
}
#[test]
fn hub_access_list_is_the_workspaces_own_or_the_instances() {
let parse = |v| parse_hub_access(&v);
let instance = parse(serde_json::json!({"Slack": "read"})).unwrap();
assert_eq!(instance.get("slack"), Some(&HubAccess::Read));
for bad in [
serde_json::json!({"slack/12": "read"}),
serde_json::json!({"": "read"}),
serde_json::json!({"Slack": "read", "slack": "write"}),
serde_json::json!({"slack": "none"}),
] {
assert!(parse(bad.clone()).is_err(), "{bad}");
}
let effective =
|workspace| HubAccessLists { instance: instance.clone(), workspace }.effective();
assert_eq!(effective(None), instance);
assert_eq!(effective(Some(HubAccessList::new())), HubAccessList::new());
let own = parse(serde_json::json!({"gmail": "write"})).unwrap();
assert_eq!(effective(Some(own.clone())), own);
}
#[test]
fn unset_fork_follows_restriction() {
let instance: Vec<RoleDefinition> = serde_json::from_value(serde_json::json!([
+18 -6
View File
@@ -22,7 +22,7 @@ use backon::ConstantBuilder;
use backon::{BackoffBuilder, Retryable};
use regex::Regex;
use crate::utils::{parse_hub_id, StripPath};
use crate::utils::{calculate_hash, parse_hub_id, StripPath};
/// The tag a script's dependency job runs on, given the script's own tag; `None` leaves it to
/// `push`'s default (the language tag). Every relock of a script must use this, or a relock
@@ -247,6 +247,17 @@ pub async fn get_full_hub_script_by_path(
get_full_hub_script_by_id(parse_hub_id(path.to_path(), "hub/")?, http_client, db).await
}
/// The name a version is cached under. Private Hubs number their scripts alike, so theirs carry
/// the Hub: what [`crate::jobs::check_can_name_runnables`] read from the configured Hub must not
/// admit a script cached from another. Public ones keep the bare id, which images ship.
fn hub_cache_name(hub_base_url: &str, version: i32) -> String {
if version < PRIVATE_HUB_MIN_VERSION {
version.to_string()
} else {
format!("{version}-{}", &calculate_hash(hub_base_url)[..16])
}
}
/// Performs no authorization and uses the instance's Hub credentials and shared cache: the caller
/// must already have decided this user may run or read this script.
pub async fn get_full_hub_script_by_id(
@@ -257,7 +268,9 @@ pub async fn get_full_hub_script_by_id(
// A cache entry that cannot be read or parsed counts as a miss rather than an error:
// a truncated write leaves a file that exists but deserializes to nothing, and refetching
// it is always preferable to failing the job push it was read for.
let cache_path = format!("{}/{version}", *HUB_CACHE_DIR);
let hub_base_url = (**HUB_BASE_URL.load()).clone();
let cache_name = hub_cache_name(&hub_base_url, version);
let cache_path = format!("{}/{cache_name}", *HUB_CACHE_DIR);
let cached = match tokio::fs::read_to_string(&cache_path).await {
Ok(content) => serde_json::from_str::<HubScript>(&content)
.inspect_err(|e| {
@@ -276,10 +289,10 @@ pub async fn get_full_hub_script_by_id(
return Ok(script);
}
let script = fetch_hub_script(version, http_client, db).await?;
let script = fetch_hub_script(&hub_base_url, version, http_client, db).await?;
if let Err(e) = crate::worker::write_file(
&HUB_CACHE_DIR,
&version.to_string(),
&cache_name,
&serde_json::to_string(&script).map_err(to_anyhow)?,
) {
tracing::error!("failed to write hub script {version} to cache: {e}");
@@ -290,12 +303,11 @@ pub async fn get_full_hub_script_by_id(
}
async fn fetch_hub_script(
hub_base_url: &str,
id: i32,
http_client: &reqwest::Client,
db: Option<&DB>,
) -> crate::error::Result<HubScript> {
let hub_base_url = (**HUB_BASE_URL.load()).clone();
let response = (|| async {
let response = http_get_from_hub(
http_client,
+133 -16
View File
@@ -629,22 +629,7 @@ pub async fn http_get_from_hub(
None => None,
};
let mut request = http_client.get(url).header(
"Accept",
if plain {
"text/plain"
} else {
"application/json"
},
);
if let Some(uid) = uid {
request = request.header("X-uid", uid);
}
if let Some(hub_api_secret) = (**HUB_API_SECRET.load()).clone() {
request = request.header("X-api-secret", hub_api_secret);
}
let mut request = hub_request(http_client, url, plain, uid);
if let Some(query_params) = query_params {
for (key, value) in query_params {
@@ -660,6 +645,137 @@ pub async fn http_get_from_hub(
Ok(response)
}
fn hub_request(
http_client: &reqwest::Client,
url: &str,
plain: bool,
uid: Option<String>,
) -> reqwest::RequestBuilder {
let mut request = http_client.get(url).header(
"Accept",
if plain {
"text/plain"
} else {
"application/json"
},
);
if let Some(uid) = uid {
request = request.header("X-uid", uid);
}
if let Some(hub_api_secret) = (**HUB_API_SECRET.load()).clone() {
request = request.header("X-api-secret", hub_api_secret);
}
request
}
/// What the Hub says about one script version, for [`crate::jobs::check_can_name_runnable`].
#[derive(Deserialize, Clone, Debug)]
pub struct HubScriptMeta {
pub version_id: i32,
/// The integration, as the Hub spells it ("Slack" and "slack" both occur).
pub app: String,
/// Absent on a version the Hub never flagged, which counts as able to write.
#[serde(default)]
pub read_only: bool,
pub script_approved: bool,
pub version_ever_approved: bool,
}
lazy_static::lazy_static! {
/// Keyed by the configured Hub too, so a changed `hub_base_url` is not answered from the old one.
static ref HUB_SCRIPT_META: quick_cache::sync::Cache<(String, i32), (HubScriptMeta, std::time::Instant)> =
quick_cache::sync::Cache::new(10_000);
}
static INSTANCE_UID: std::sync::OnceLock<String> = std::sync::OnceLock::new();
const HUB_SCRIPT_META_TTL: std::time::Duration = std::time::Duration::from_secs(300);
/// The Hub's metadata of each known version in `ids`; unknown ones are left out. Cached per version
/// for [`HUB_SCRIPT_META_TTL`], so an unapproval takes up to that long to be seen.
///
/// Takes no pool connection: it runs inside save transactions, where a second one held alongside
/// self-deadlocks on a one-connection pool. The `X-uid` it sends is read from memory, so a server
/// that never read its uid yet sends none.
pub async fn hub_script_meta(ids: &[i32]) -> Result<std::collections::HashMap<i32, HubScriptMeta>> {
let hub = (**crate::HUB_BASE_URL.load()).clone();
let mut out = std::collections::HashMap::new();
let mut missing = vec![];
for &id in ids {
match HUB_SCRIPT_META.get(&(hub.clone(), id)) {
Some((m, at)) if at.elapsed() < HUB_SCRIPT_META_TTL => {
out.insert(id, m);
}
_ => missing.push(id),
}
}
if missing.is_empty() {
return Ok(out);
}
let mut found = fetch_hub_script_meta(&hub, &missing).await?;
if hub != crate::DEFAULT_HUB_BASE_URL {
// Same fallback as the script fetch: low ids a private Hub lacks are public Hub scripts.
let public: Vec<i32> = missing
.into_iter()
.filter(|id| {
*id < crate::PRIVATE_HUB_MIN_VERSION && !found.iter().any(|m| m.version_id == *id)
})
.collect();
if !public.is_empty() {
found.extend(fetch_hub_script_meta(crate::DEFAULT_HUB_BASE_URL, &public).await?);
}
}
let now = std::time::Instant::now();
for m in found {
HUB_SCRIPT_META.insert((hub.clone(), m.version_id), (m.clone(), now));
out.insert(m.version_id, m);
}
Ok(out)
}
/// The Hub's URL goes to the log only: a private Hub's address is not every member's business.
fn hub_meta_err(hub: &str, what: &str, e: impl Display) -> Error {
tracing::warn!("hub script access lookup at {hub}: {what}: {e}");
Error::BadGateway(what.to_string())
}
async fn fetch_hub_script_meta(hub: &str, ids: &[i32]) -> Result<Vec<HubScriptMeta>> {
let uid = match (**LICENSE_KEY_ID.load()).clone() {
id if !id.is_empty() => Some(id),
_ => INSTANCE_UID.get().cloned(),
};
let mut out = vec![];
for chunk in ids.chunks(100) {
let resp = hub_request(
&HTTP_CLIENT,
&format!("{hub}/scripts/access_meta"),
false,
uid.clone(),
)
.query(&[("ids", chunk.iter().join(","))])
.timeout(std::time::Duration::from_secs(5))
.send()
.await
.map_err(|e| hub_meta_err(hub, "the Hub is unreachable", e))?;
if resp.status() == reqwest::StatusCode::NOT_FOUND {
return Err(hub_meta_err(
hub,
"the Hub cannot report script approvals and needs an update",
"404",
));
}
let resp = resp
.error_for_status()
.map_err(|e| hub_meta_err(hub, "the Hub failed", e))?;
out.extend(
resp.json::<Vec<HubScriptMeta>>()
.await
.map_err(|e| hub_meta_err(hub, "the Hub answered badly", e))?,
);
}
Ok(out)
}
pub fn rd_string(len: usize) -> String {
rng()
.sample_iter(&Alphanumeric)
@@ -697,6 +813,7 @@ pub async fn get_instance_uid<'c, E: sqlx::Executor<'c, Database = Postgres>>(
.await?;
let uid = serde_json::from_value::<String>(uid_value).map_err(to_anyhow)?;
let _ = INSTANCE_UID.set(uid.clone());
Ok(uid)
}
@@ -1,13 +1,14 @@
#![cfg(feature = "enterprise")]
//! Flips the process-wide `LICENSE_KEY_VALID`, so it keeps a test binary of its own.
use std::sync::atomic::Ordering;
use std::{collections::BTreeMap, sync::atomic::Ordering};
use sqlx::{Pool, Postgres};
use windmill_common::ee_oss::LICENSE_KEY_VALID;
use windmill_common::instance_config::sync_global_settings_declarative;
use windmill_common::roles::{
self, check_frozen_overrides, instance_roles, load_role_overrides,
validate_instance_roles_write, RoleOverrides,
validate_instance_hub_access_write, validate_instance_roles_write, RoleOverrides,
};
/// A lapsed license freezes the configured roles: falling back to the defaults would give a
@@ -65,6 +66,39 @@ async fn lapsed_license_freezes_roles(db: Pool<Postgres>) {
check_frozen_overrides(&instance, &previous, &RoleOverrides::new())
.expect("removing a workspace-only role stays open");
// The instance's Hub access list is frozen the same way, and can always be cleared.
let slack = BTreeMap::from([(
"hub_access".to_string(),
serde_json::json!({"slack": "read"}),
)]);
sync_global_settings_declarative(&db, &BTreeMap::new(), &slack, &())
.await
.expect_err("changing the instance's Hub scripts needs a license");
validate_instance_hub_access_write(&db, &serde_json::json!({}))
.await
.expect("clearing stays open");
LICENSE_KEY_VALID.store(true, Ordering::Relaxed);
sync_global_settings_declarative(&db, &BTreeMap::new(), &slack, &())
.await
.expect("licensed again");
validate_instance_hub_access_write(&db, &serde_json::json!({"slack/x": "read"}))
.await
.expect_err("a license does not let a malformed list through");
LICENSE_KEY_VALID.store(false, Ordering::Relaxed);
validate_instance_hub_access_write(&db, &serde_json::json!({"Slack": "read"}))
.await
.expect("writing the stored list back unchanged stays open");
validate_instance_hub_access_write(&db, &serde_json::json!({"slack": "write"}))
.await
.expect_err("changing the stored list still needs a license");
roles::invalidate_all_roles_cache();
let ws = roles::workspace_roles(&db, "test-workspace").await.unwrap();
let dev = ws.iter().find(|r| r.name == "developer").unwrap();
assert!(
dev.capabilities.hub.contains_key("slack"),
"the stored list keeps applying"
);
LICENSE_KEY_VALID.store(true, Ordering::Relaxed);
check_frozen_overrides(&instance, &previous, &relabelled).expect("licensed again");
}
@@ -1880,7 +1880,7 @@ mod schedule_push {
#[sqlx::test(migrations = "../migrations", fixtures("base", "schedule_push"))]
async fn test_push_hub_script_schedule(db: Pool<Postgres>) -> anyhow::Result<()> {
// Seed the hub cache so the push resolves the script without the network.
let version = "990000001";
let version = "9990001";
let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR;
tokio::fs::create_dir_all(hub_dir).await?;
tokio::fs::write(
+41
View File
@@ -1173,3 +1173,44 @@ pub fn parse_dedicated_worker_line(line: &str) -> DedicatedWorkerResult {
DedicatedWorkerResult::Other(line.to_string())
}
/// A Hub serving `GET /scripts/access_meta` from `rows`, each a version's metadata, and for every
/// script a bash one echoing the Hub's URL, set as the instance's Hub. Returns its URL and the
/// number of lookups it served.
pub async fn start_stub_hub(
rows: Vec<serde_json::Value>,
) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
use std::sync::{atomic::AtomicUsize, Arc};
let calls = Arc::new(AtomicUsize::new(0));
let served = calls.clone();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let script = serde_json::json!({ "content": format!("echo {url}"), "lockfile": null,
"language": "bash", "schema": {}, "summary": null });
let app = axum::Router::new()
.route(
"/scripts/access_meta",
axum::routing::get(
move |axum::extract::Query(q): axum::extract::Query<
std::collections::HashMap<String, String>,
>| async move {
served.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let ids: Vec<i64> =
q["ids"].split(',').filter_map(|s| s.parse().ok()).collect();
let known: Vec<_> = rows
.iter()
.filter(|r| ids.contains(&r["version_id"].as_i64().unwrap()))
.cloned()
.collect();
axum::Json(known)
},
),
)
.route(
"/raw2/{id}/script",
axum::routing::get(move || async move { axum::Json(script) }),
);
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
windmill_common::HUB_BASE_URL.store(Arc::new(url.clone()));
(url, calls)
}
+2
View File
@@ -63,6 +63,7 @@ export interface SimplifiedSettings {
color?: string;
operator_settings?: any;
role_overrides?: any;
hub_access?: any;
datatable?: any;
slack_team_id?: string;
slack_name?: string;
@@ -96,6 +97,7 @@ export const SETTINGS_MANAGED_ONLY_WHEN_PRESENT = [
"add_admins_and_developers_to_forks",
"variable_expiration_handler",
"role_overrides",
"hub_access",
"webhook_events",
] as const;
+2 -1
View File
@@ -8667,6 +8667,7 @@ write a secret you were not given: keep the placeholder.
| \`default_scripts\` | \`{ order?, hidden?, default_script_content? }\` for the script language picker. |
| \`deploy_ui\` | \`{ include_path?, include_type? }\`: what the deploy-to-workspace UI offers. |
| \`role_overrides\` | \`{ <role>: { label?, capabilities, workspace_only? } }\`: the workspace's overrides of the instance's roles, and with \`workspace_only: true\` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in \`role_overrides.operator\`. |
| \`hub_access\` | \`{ <Hub integration>: read \\| write }\`: the Hub scripts members without code may use, replacing the instance's list. \`null\` uses the instance's list; \`{}\` allows none. |
| \`operator_settings\` | Legacy view of the \`operator\` role, kept for older servers: page visibility flags (\`runs\`, \`schedules\`, \`resources\`, \`variables\`, \`assets\`, \`audit_logs\`, \`groups\`, \`folders\`, \`workers\`, \`triggers\`) and write rights (\`manage_schedules\`, \`manage_triggers\`, \`builder_flows\`, \`builder_apps\`). Not applied when the document also states \`role_overrides\`. |
| \`mute_critical_alerts\` | Mute the workspace's critical alerts. |
| \`slack_team_id\`, \`slack_name\` | Read only: set by connecting Slack on the settings page. |
@@ -8689,7 +8690,7 @@ only show them, \`-y\` to skip the question, \`--replace\` to clear what the fil
With \`includeSettings: true\` in \`wmill.yaml\`, \`wmill sync pull\` writes the document to
\`settings.yaml\`, secrets encrypted with the workspace key (plaintext only with \`plainSecrets\`), and
\`wmill sync push\` applies it. Unlike a partial apply, a push treats the file as the whole
document: a setting the file omits is cleared, except \`operator_settings\`, \`role_overrides\`, \`color\`, the auto-invite
document: a setting the file omits is cleared, except \`operator_settings\`, \`role_overrides\`, \`hub_access\`, \`color\`, the auto-invite
instance groups, and the keys \`ducklake\`, \`dbt_warehouses\`, \`deploy_ui\`, \`teams_command_script\`,
\`public_app_execution_limit_per_minute\`, \`guest_jwt_public_key\`, \`guest_jwt_jwks_url\`,
\`error_handler_fallback_to_instance_alerts\` and
+4 -3
View File
@@ -57,8 +57,9 @@ permissions:
it as whoever it runs as: `validate_operator_composed_flow` re-checks each path under the
caller's RLS. This is the general case; the one below is on top of it, not instead of it.
A Hub step has no workspace row to read, so it is collected apart and held to the run-time rule
for naming a Hub path (`check_can_name_runnable`) against the builder: Hub steps follow the
`code` capability, and preset handlers are allowed to every role.
for naming a Hub path (`check_can_name_runnable`) against the builder: Hub steps need
the `code` capability or the Hub access list (`docs/workspace-roles.md`, "Hub scripts"), and preset
handlers are allowed to every role.
- **the `(path, hash)` of every version-pinned step**. A step carrying a `hash` is dispatched by
that hash alone, with the path beside it never consulted, so a readable path paired with another
script's hash still runs that other script.
@@ -92,7 +93,7 @@ that function.
The same reasoning applies to a builder-authored app, with one extra step. `execute_component`
resolves the runnable it runs on the root handle, so `validate_operator_composed_app` checks every
referenced path under the caller's RLS and holds a Hub one to `check_can_name_runnable`, as in a
flow, so Hub steps follow the `code` capability. For a script it checks the version a
flow, so Hub steps need `code` or the Hub access list. For a script it checks the version a
run would pick: grants are per version, and a path reused after its versions were archived starts
with none while the archived ones keep theirs. But it has to check **two** surfaces,
because they are not the same list: the policy's `script/<path>`, `flow/<path>` and
+4 -2
View File
@@ -57,12 +57,14 @@ app rather than telling them why. Both integration tests assert the status for t
## Hub paths in triggers and schedules
Whatever write rights they hold, a member without `code` cannot save a new Hub path into a trigger,
a schedule or a WebSocket capture config (`check_new_hub_paths`). Paths already saved keep working,
a schedule or a WebSocket capture config (`check_new_hub_paths`), unless the Hub
access list allows that script (see `docs/workspace-roles.md`, "Hub scripts", for the list and its
refusal reasons). Paths already saved keep working,
and are not rechecked when the trigger or schedule is edited, even when the edit moves one between
a trigger's fields (an error handler to the main script) or among a schedule's handlers; a handler
cannot take the schedule's Hub target. The edit makes the editor its run-as identity unless they
may keep the stored one (admins, `wm_deployers`), so a saved Hub path then runs as the editor, with
the arguments they save: accepted so that rows a member with `code` set up stay editable, since the
the arguments they save: accepted so that rows set up by a member who could name the path stay editable, since the
choice of which Hub code runs stays with that member.
## Drafts
+31
View File
@@ -35,6 +35,37 @@ deleting one that a member, invite, auto-invite or instance group mapping still
and so is deleting an instance role that a workspace still overrides (the override would fall onto
`base_for` instead of the definition it was written against).
## Hub scripts
A role without `code` may not name a Hub script or flow (`check_can_name_runnable`), except the
Hub scripts a list allows: `{ <integration>: read | write }`, the integration being the script's
`app`. It is the same for every role without `code`. The instance has one (the `hub_access` global
setting, EE and frozen without a license like the roles, though it can always be cleared), and a
workspace may replace it as a whole (`workspace_settings.hub_access`): `NULL` follows the
instance's, an own list does not merge with it, and an empty one allows nothing. Keys are
lowercased, since the Hub has both `Slack` and `slack`, and one containing `/` is refused, as
`<integration>/<ask_id>` is reserved for per-script entries. Forks copy the workspace's list.
`workspace_roles_on` puts the list that applies on `RoleCapabilities::hub` of each role without
`code`, so it is cached and loaded with the role and the rule reads nothing else; a per-role layer
would go there too. It is not part of `RoleCapabilitiesPatch`, so no role setting holds it and
`diff_capabilities` ignores it.
When `hub` is non-empty, naming `hub/<id>/…` asks the Hub (`hub_script_meta`, `GET
{hub}/scripts/access_meta`, cached 5 minutes per version, with the private Hub's fallback to the
public one for ids below `PRIVATE_HUB_MIN_VERSION`), and allows it when the version's `app` (from
the Hub, never the path) is listed at `write`, or at `read` and the version is read-only, and the
script is approved and this version was ever approved. A version with no flag can write. Refused
otherwise, saying which: integration not allowed, script can write but is allowed at read,
version not approved or not on the Hub, or the Hub unreachable or too old to answer. An empty
list refuses without asking. Hub flows stay code-only. The UI offers less than the server
allows: the flow, app and schedule pickers and the AI chat (MCP instructions included) still follow
`code` alone.
The lookup takes no pool connection, since it runs inside save transactions (see
`hub_script_meta`). The check runs when a path is chosen, never when something saved fires, so a
saved flow, trigger or schedule keeps running after an integration is withdrawn or a script unapproved.
## Runs
`run` withdrawn makes a role view-only: its members see what folder and item rights grant,
@@ -2449,7 +2449,7 @@ export function getInstructions(
external = false,
/** The session cannot run a flow preview, which an agent's test run is. */
untestable = false,
/** The role has code, which the server requires to add a hub path. */
/** The role has code, so it may add any hub path. The Hub access list is not offered here. */
hub = true
): string | Promise<string> {
switch (subject) {
@@ -302,7 +302,8 @@
: []
)
// The server adds a hub path only for a role that has code, whatever its flows level.
// Whatever its flows level, a role needs code to add any hub path. The Hub access list, which the
// server also accepts, is not offered here.
let showHub = $derived($roleCaps.code)
// Every result row lives in one keyboard index space, and hovering a row moves that index, so
@@ -60,7 +60,8 @@
| 'failure'
| 'aisandbox'
| 'aiagent' = $state(untrack(() => kind))
// The server adds a hub path only for a role that has code, so without it never open on the hub.
// A role needs code to add any hub path, so without it never open on the hub. The Hub access list,
// which the server also accepts, is not offered here.
let preFilter: 'all' | 'workspace' | 'hub' = $state(
untrack(() => $roleCaps.code) ? 'all' : 'workspace'
)
+1
View File
@@ -1641,6 +1641,7 @@ write a secret you were not given: keep the placeholder.
| \`default_scripts\` | \`{ order?, hidden?, default_script_content? }\` for the script language picker. |
| \`deploy_ui\` | \`{ include_path?, include_type? }\`: what the deploy-to-workspace UI offers. |
| \`role_overrides\` | \`{ <role>: { label?, capabilities, workspace_only? } }\`: the workspace's overrides of the instance's roles, and with \`workspace_only: true\` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in \`role_overrides.operator\`. |
| \`hub_access\` | \`{ <Hub integration>: read \\| write }\`: the Hub scripts members without code may use, replacing the instance's list. \`null\` uses the instance's list; \`{}\` allows none. |
| \`operator_settings\` | Legacy view of the \`operator\` role, kept for older servers: page visibility flags (\`runs\`, \`schedules\`, \`resources\`, \`variables\`, \`assets\`, \`audit_logs\`, \`groups\`, \`folders\`, \`workers\`, \`triggers\`) and write rights (\`manage_schedules\`, \`manage_triggers\`, \`builder_flows\`, \`builder_apps\`). Not applied when the document also states \`role_overrides\`. |
| \`mute_critical_alerts\` | Mute the workspace's critical alerts. |
| \`slack_team_id\`, \`slack_name\` | Read only: set by connecting Slack on the settings page. |
@@ -54,6 +54,7 @@ write a secret you were not given: keep the placeholder.
| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |
| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |
| `role_overrides` | `{ <role>: { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |
| `hub_access` | `{ <Hub integration>: read \| write }`: the Hub scripts members without code may use, replacing the instance's list. `null` uses the instance's list; `{}` allows none. |
| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |
| `mute_critical_alerts` | Mute the workspace's critical alerts. |
| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |
@@ -76,7 +77,7 @@ only show them, `-y` to skip the question, `--replace` to clear what the file om
With `includeSettings: true` in `wmill.yaml`, `wmill sync pull` writes the document to
`settings.yaml`, secrets encrypted with the workspace key (plaintext only with `plainSecrets`), and
`wmill sync push` applies it. Unlike a partial apply, a push treats the file as the whole
document: a setting the file omits is cleared, except `operator_settings`, `role_overrides`, `color`, the auto-invite
document: a setting the file omits is cleared, except `operator_settings`, `role_overrides`, `hub_access`, `color`, the auto-invite
instance groups, and the keys `ducklake`, `dbt_warehouses`, `deploy_ui`, `teams_command_script`,
`public_app_execution_limit_per_minute`, `guest_jwt_public_key`, `guest_jwt_jwks_url`,
`error_handler_fallback_to_instance_alerts` and
+2 -1
View File
@@ -49,6 +49,7 @@ write a secret you were not given: keep the placeholder.
| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |
| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |
| `role_overrides` | `{ <role>: { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |
| `hub_access` | `{ <Hub integration>: read \| write }`: the Hub scripts members without code may use, replacing the instance's list. `null` uses the instance's list; `{}` allows none. |
| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |
| `mute_critical_alerts` | Mute the workspace's critical alerts. |
| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |
@@ -72,7 +73,7 @@ only show them, `-y` to skip the question, `--replace` to clear what the file om
With `includeSettings: true` in `wmill.yaml`, `wmill sync pull` writes the document to
`settings.yaml`, secrets encrypted with the workspace key (plaintext only with `plainSecrets`), and
`wmill sync push` applies it. Unlike a partial apply, a push treats the file as the whole
document: a setting the file omits is cleared, except `operator_settings`, `role_overrides`, `color`, the auto-invite
document: a setting the file omits is cleared, except `operator_settings`, `role_overrides`, `hub_access`, `color`, the auto-invite
instance groups, and the keys `ducklake`, `dbt_warehouses`, `deploy_ui`, `teams_command_script`,
`public_app_execution_limit_per_minute`, `guest_jwt_public_key`, `guest_jwt_jwks_url`,
`error_handler_fallback_to_instance_alerts` and