diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index ffba720167..6e6ea31ba7 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -000a83d34767b44c041612df31e2a3e7e305d63a +e4bfe4229dfd07f6c356835c2ac0e80c2729d582 diff --git a/backend/tests/end_user_email.rs b/backend/tests/end_user_email.rs index bde142ef69..8d6c0d167c 100644 --- a/backend/tests/end_user_email.rs +++ b/backend/tests/end_user_email.rs @@ -360,6 +360,7 @@ async fn test_job_token_run_keeps_end_user_email(db: Pool) -> anyhow:: scopes: None, token_prefix: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), }, "test-workspace", 3600, diff --git a/backend/tests/hub_composed_step.rs b/backend/tests/hub_composed_step.rs index 1bb04955e7..5943789597 100644 --- a/backend/tests/hub_composed_step.rs +++ b/backend/tests/hub_composed_step.rs @@ -103,3 +103,79 @@ async fn a_hub_step_follows_the_code_capability(db: Pool) -> anyhow::R ); Ok(()) } + +/// An agent save checks its Hub tools inside its transaction, so the check must not need a second +/// connection: on a one-connection pool, with the member's role never read before, the save is +/// refused rather than left waiting, from a job's token (sent first, while nothing is cached) as from +/// a personal one. Its own operator, so no other test has warmed the role cache for it; the +/// overrides match the other test's, since the workspace's roles are cached across tests. +#[sqlx::test(fixtures("base"))] +async fn a_hub_step_is_refused_on_a_one_connection_pool( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + r#"UPDATE workspace_settings SET role_overrides = '{ + "operator": {"capabilities": {"flows": "compose", "apps": "compose"}}, + "developer": {"capabilities": {"flows": "compose", "apps": "compose"}} + }' WHERE workspace_id = 'test-workspace'; + INSERT INTO password(email, password_hash, login_type, super_admin, verified, name) + VALUES ('solo@windmill.dev', 'x', 'password', false, true, 'Solo'); + INSERT INTO usr(workspace_id, email, username, is_admin, operator, role) + VALUES ('test-workspace', 'solo@windmill.dev', 'solo', false, true, 'Operator'); + INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256('SOLO_TOKEN'::bytea), 'hex'), 'SOLO_TOKEN', 'SOLO_TOKEN', + 'solo@windmill.dev', 'solo', false);"#, + ) + .execute(&db) + .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 server = ApiServer::start(one).await?; + set_jwt_secret().await; + let job_token = windmill_common::auth::create_jwt_token( + windmill_common::db::Authed { + email: "solo@windmill.dev".to_string(), + username: "solo".to_string(), + is_admin: false, + is_operator: true, + groups: vec![], + folders: vec![], + scopes: None, + token_prefix: None, + mcp_client: None, + capabilities: None, + }, + "test-workspace", + 3600, + None, + None, + None, + None, + ) + .await?; + for token in [job_token, "SOLO_TOKEN".to_string()] { + let resp = reqwest::Client::new() + .post(format!( + "http://localhost:{}/api/w/test-workspace/resources/create", + server.addr.port() + )) + .bearer_auth(&token) + .json(&json!({ + "path": "u/solo/agent", "resource_type": "ai_agent", + "value": {"tools": [{"id": "t", "value": {"tool_type": "flowmodule", + "type": "script", "path": HUB_PATH, "input_transforms": {}}}]}, + })) + .send() + .await?; + let (status, body) = (resp.status(), resp.text().await?); + assert!( + status == 403 && body.contains(&format!("{HUB_PATH}: {REFUSAL}")), + "{status} {body}" + ); + } + Ok(()) +} diff --git a/backend/tests/hub_named_path.rs b/backend/tests/hub_named_path.rs index 72530e7b4e..0c432f83aa 100644 --- a/backend/tests/hub_named_path.rs +++ b/backend/tests/hub_named_path.rs @@ -5,6 +5,7 @@ use serde_json::json; use sqlx::{Pool, Postgres}; use windmill_common::{ jobs::{check_can_name_runnable, RunOrigin}, + roles::RoleCapabilities, runnable_ref::RunnableRef, }; use windmill_test_utils::*; @@ -163,3 +164,49 @@ async fn a_hub_path_named_without_code_is_refused(db: Pool) -> anyhow: check_can_name_runnable(&origin, &preset, &db, "test-workspace").await?; Ok(()) } + +/// The rule reads the capabilities authentication resolved and queries nothing; only a restricted +/// caller built without a role lookup reads the role, and is still refused. +#[sqlx::test(fixtures("base"))] +async fn the_rule_reads_code_from_the_caller(db: Pool) -> anyhow::Result<()> { + sqlx::raw_sql( + "INSERT INTO usr(workspace_id, email, username, is_admin, operator, role) + VALUES ('test-workspace', 'op@windmill.dev', 'op', false, true, 'Operator');", + ) + .execute(&db) + .await?; + let hub = RunnableRef::from_path(&format!("hub/{HUB_ID}/test/echo"), false)?; + let op = |capabilities| windmill_api_auth::ApiAuthed { + email: "op@windmill.dev".into(), + username: "op".into(), + is_operator: true, + capabilities, + ..Default::default() + }; + let check = |authed: windmill_api_auth::ApiAuthed, db: Pool| { + let hub = hub.clone(); + async move { + let origin = RunOrigin::NamedBy(authed.to_authed_ref()); + check_can_name_runnable(&origin, &hub, &db, "test-workspace").await + } + }; + + let unresolved = check(op(None), db.clone()).await; + assert!( + matches!(&unresolved, Err(e) if e.to_string().contains(REFUSAL)), + "{unresolved:?}" + ); + + // Any query on this pool fails. + let dead = sqlx::postgres::PgPoolOptions::new() + .acquire_timeout(std::time::Duration::from_millis(200)) + .connect_lazy("postgres://nobody@127.0.0.1:1/none")?; + let refused = check(op(Some(RoleCapabilities::OPERATOR)), dead.clone()).await; + assert!( + matches!(&refused, Err(e) if e.to_string().contains(REFUSAL)), + "{refused:?}" + ); + let coder = RoleCapabilities { code: true, ..RoleCapabilities::OPERATOR }; + check(op(Some(coder)), dead).await?; + Ok(()) +} diff --git a/backend/tests/inline_preview_auth.rs b/backend/tests/inline_preview_auth.rs index ec7042a4af..4fdb5b77b5 100644 --- a/backend/tests/inline_preview_auth.rs +++ b/backend/tests/inline_preview_auth.rs @@ -78,6 +78,7 @@ async fn operator_job_token(job_id: uuid::Uuid) -> String { scopes: None, token_prefix: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::NONE), }; create_jwt_token( authed, diff --git a/backend/tests/pool_hold_and_wait.rs b/backend/tests/pool_hold_and_wait.rs index 44af05ab39..4f05c3adb4 100644 --- a/backend/tests/pool_hold_and_wait.rs +++ b/backend/tests/pool_hold_and_wait.rs @@ -38,6 +38,7 @@ async fn run_by_path_of_a_missing_script_uses_one_connection(db: Pool) folders: &folders, scopes: &None, token_prefix: &None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), }; let lookup = windmill_common::get_latest_deployed_hash_for_path( Some(UserDbWithAuthed { authed: &authed, db: UserDB::new(one.clone()) }), diff --git a/backend/tests/postgres_trigger_scope.rs b/backend/tests/postgres_trigger_scope.rs index 7171812fa9..9e7d8a665b 100644 --- a/backend/tests/postgres_trigger_scope.rs +++ b/backend/tests/postgres_trigger_scope.rs @@ -27,6 +27,7 @@ fn scoped_authed(scopes: Vec<&str>) -> ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/tests/reserved_control_args.rs b/backend/tests/reserved_control_args.rs index 0090a130f1..ed0fa6d002 100644 --- a/backend/tests/reserved_control_args.rs +++ b/backend/tests/reserved_control_args.rs @@ -91,6 +91,7 @@ fn trigger_authed() -> windmill_api_auth::ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/tests/trigger_listener_queries.rs b/backend/tests/trigger_listener_queries.rs index 88dcab82ac..c2392202a8 100644 --- a/backend/tests/trigger_listener_queries.rs +++ b/backend/tests/trigger_listener_queries.rs @@ -180,6 +180,7 @@ fn make_authed() -> windmill_api_auth::ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/tests/wm_token_confinement.rs b/backend/tests/wm_token_confinement.rs index af5974f85a..6b995115c2 100644 --- a/backend/tests/wm_token_confinement.rs +++ b/backend/tests/wm_token_confinement.rs @@ -52,6 +52,7 @@ async fn wm_token(email: &str, is_admin: bool) -> String { scopes: None, token_prefix: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), }; create_jwt_token( authed, @@ -1129,6 +1130,7 @@ async fn test_privilege_gates_reject_a_job_token_directly( job_id, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/windmill-api-assets/tests/dbt_pinned_graph.rs b/backend/windmill-api-assets/tests/dbt_pinned_graph.rs index ac9b5b740c..eaa531dc4b 100644 --- a/backend/windmill-api-assets/tests/dbt_pinned_graph.rs +++ b/backend/windmill-api-assets/tests/dbt_pinned_graph.rs @@ -37,6 +37,7 @@ fn outsider() -> ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index 1b53b546c4..889f1f09a0 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -171,6 +171,15 @@ impl AuthCache { // from a job's WM_TOKEN, even on an AUTH_CACHE hit whose cached authed // predates this field. opt_job_authed.authed.job_id = opt_job_authed.job_id; + // Read for each request, before any handler opens a transaction, so a check inside one + // never needs a second connection. Never cached with the login: the role caches it reads + // are the ones role changes clear. An unreadable role stays `None`, read again later. + if let Some(w_id) = w_id.as_deref() { + opt_job_authed.authed.capabilities = + windmill_common::roles::caller_capabilities(&self.db, w_id, &opt_job_authed.authed) + .await + .ok(); + } // The no-account rule is enforced here, once, for every guest request — not per // handler, where each guest-reachable route would have to remember it. Uncached, // so an account provisioned after the mint ends the guest session, and every @@ -348,6 +357,7 @@ impl AuthCache { job_id: None, credential_expiry: Some(credential_expiry), mcp_client: None, + capabilities: None, }; AUTH_CACHE.insert( key, @@ -394,6 +404,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: claims.mcp_client, + capabilities: None, }; // Fail closed: a `job_id` claim that does not parse must reject // the token rather than resolve to `None`, which would clear the @@ -526,6 +537,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }) } else { tracing::warn!( @@ -581,6 +593,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }) } else { tracing::warn!( @@ -681,6 +694,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }) } None if super_admin => { @@ -707,6 +721,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }), Err(e) => { tracing::error!( @@ -746,6 +761,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }) } None => None, @@ -767,6 +783,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }) } } @@ -808,6 +825,7 @@ impl AuthCache { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }; Some(OptJobAuthed { authed, job_id: None }) } else { @@ -1183,6 +1201,7 @@ fn no_auth_admin_authed() -> ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, } } diff --git a/backend/windmill-api-auth/src/composed.rs b/backend/windmill-api-auth/src/composed.rs index ca7ca72773..7860409c50 100644 --- a/backend/windmill-api-auth/src/composed.rs +++ b/backend/windmill-api-auth/src/composed.rs @@ -6,8 +6,8 @@ use sqlx::{Postgres, Transaction}; use windmill_common::{ error::{self, Error}, flows::FlowValue, - jobs::{check_can_name_runnable, check_can_name_with, naming_needs_code, RunOrigin}, - roles::{caller_capabilities, AuthorLevel}, + jobs::{check_can_name_runnable, RunOrigin}, + roles::AuthorLevel, runnable_ref::RunnableRef, workspaces::{check_operator_can_build, BuilderKind}, DB, @@ -38,31 +38,19 @@ fn name_refused_path(runnable: &RunnableRef, e: Error) -> Error { } } -/// Whether the caller may name the Hub paths among `new`, for `check_new_hub_paths`. Resolve it -/// before the save's transaction opens: on a role-cache miss it reads from the pool. -pub async fn can_name_hub( - new: &[RunnableRef], - authed: &ApiAuthed, - db: &DB, - w_id: &str, -) -> error::Result { - if !new.iter().any(naming_needs_code) { - return Ok(true); - } - Ok(caller_capabilities(db, w_id, authed).await?.code) -} - /// 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 /// save, or a concurrent edit could slip a removed Hub path back in as unchanged. -pub fn check_new_hub_paths( +pub async fn check_new_hub_paths( new: &[RunnableRef], old: &[RunnableRef], - can_name_hub: bool, + authed: &ApiAuthed, + db: &DB, + w_id: &str, ) -> error::Result<()> { for runnable in new.iter().filter(|r| !old.contains(r)) { - check_can_name_with(runnable, can_name_hub).map_err(|e| name_refused_path(runnable, e))?; + check_builder_can_name_hub(runnable, authed, db, w_id).await?; } Ok(()) } @@ -79,10 +67,6 @@ pub async fn authorize_composed_flow( w_id: &str, ) -> error::Result<()> { let mut refs = windmill_common::flows::check_flow_is_composition_only(value)?; - // Each check reads the caller's role; a flow can step through the same Hub script many times. - refs.hub_runnables - .sort_by(|a, b| (a.is_flow(), a.path()).cmp(&(b.is_flow(), b.path()))); - refs.hub_runnables.dedup(); for runnable in &refs.hub_runnables { check_builder_can_name_hub(runnable, authed, db, w_id).await?; } diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index afddad0a6c..13ad961b86 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -29,6 +29,7 @@ use windmill_common::{ db::{Authable, Authed, AuthedRef}, error::{self, Error, Result}, jobs::JobTriggerKind, + roles::RoleCapabilities, triggers::TriggerMetadata, users::username_to_permissioned_as, workspaces::{check_operator_can_manage, ManageKind}, @@ -93,6 +94,9 @@ pub struct ApiAuthed { /// The OAuth client of an external issuer acting for this user (`mcp_external_idp`). /// Recorded on the runs it starts and handed to their steps as `WM_MCP_CLIENT`. pub mcp_client: Option, + /// The role's capabilities in the request's workspace (`AuthCache::get_opt_job_authed`); `None` + /// outside a request. + pub capabilities: Option, } impl ApiAuthed { @@ -106,6 +110,7 @@ impl ApiAuthed { folders: &self.folders, scopes: &self.scopes, token_prefix: &self.token_prefix, + capabilities: self.capabilities, } } @@ -161,6 +166,7 @@ impl From for Authed { scopes: value.scopes, token_prefix: value.token_prefix, mcp_client: value.mcp_client, + capabilities: value.capabilities, } } } @@ -183,6 +189,7 @@ impl From for ApiAuthed { job_id: None, credential_expiry: None, mcp_client: value.mcp_client, + capabilities: value.capabilities, } } } @@ -211,6 +218,10 @@ impl Authable for ApiAuthed { self.is_operator } + fn capabilities(&self) -> Option { + self.capabilities + } + fn groups(&self) -> &[String] { &self.groups } @@ -1166,6 +1177,7 @@ pub async fn fetch_api_authed_from_permissioned_as( job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }; API_AUTHED_CACHE.insert( diff --git a/backend/windmill-api-integration-tests/tests/native_triggers.rs b/backend/windmill-api-integration-tests/tests/native_triggers.rs index e05a1f1ed5..327c9ab9b9 100644 --- a/backend/windmill-api-integration-tests/tests/native_triggers.rs +++ b/backend/windmill-api-integration-tests/tests/native_triggers.rs @@ -68,6 +68,7 @@ fn test_authed() -> ApiAuthed { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } @@ -484,6 +485,7 @@ async fn test_require_native_integration_use_needs_code_and_manage_triggers( operator.username = "operator".to_string(); operator.is_admin = false; operator.is_operator = true; + operator.capabilities = None; assert!( require_native_integration_use(&db, "test-workspace", &operator) .await diff --git a/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs b/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs index 43342907d6..3564cfccd1 100644 --- a/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs +++ b/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs @@ -106,6 +106,7 @@ async fn test_preview_on_behalf_of(db: Pool) -> anyhow::Result<()> { scopes: None, token_prefix: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), }, "test-workspace", 3600, diff --git a/backend/windmill-api-integration-tests/tests/role_run_capability.rs b/backend/windmill-api-integration-tests/tests/role_run_capability.rs index dd1f206a55..42e8fb76ac 100644 --- a/backend/windmill-api-integration-tests/tests/role_run_capability.rs +++ b/backend/windmill-api-integration-tests/tests/role_run_capability.rs @@ -61,7 +61,14 @@ async fn test_withdrawn_run_refuses_runs(db: Pool) -> anyhow::Result<( set_overrides(r#"{"code": true}"#).await?; assert!(run("OPERATOR_TOKEN_1").await?.iter().all(|s| *s != 403)); - set_overrides(r#"{"code": true, "run": false}"#).await?; + // Through the route: the operator's login, cached above with `run` granted, must not keep it. + let resp = reqwest::Client::new() + .post(format!("{api}/workspaces/role_overrides")) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&serde_json::json!({"operator": {"capabilities": {"code": true, "run": false}}})) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); // 403, not 401, which the frontend reads as a dead session. assert_eq!(run("OPERATOR_TOKEN_1").await?, vec![403, 403, 403]); assert!(run("SECRET_TOKEN").await?.iter().all(|s| *s != 403)); diff --git a/backend/windmill-api-schedule/src/lib.rs b/backend/windmill-api-schedule/src/lib.rs index da48c94fa5..04da02c7ad 100644 --- a/backend/windmill-api-schedule/src/lib.rs +++ b/backend/windmill-api-schedule/src/lib.rs @@ -18,7 +18,7 @@ use sqlx::{Postgres, Transaction}; use std::str::FromStr; use windmill_api_auth::{ build_scope_path_predicate, check_scopes, - composed::{can_name_hub, check_new_hub_paths}, + composed::check_new_hub_paths, maybe_refresh_folders, require_super_admin, ApiAuthed, }; use windmill_audit::audit_oss::audit_log; @@ -372,11 +372,7 @@ async fn create_schedule( ns.on_success.as_deref(), ]); new_runnables.extend(target); - check_new_hub_paths( - &new_runnables, - &[], - can_name_hub(&new_runnables, &authed, &db, &w_id).await?, - )?; + check_new_hub_paths(&new_runnables, &[], &authed, &db, &w_id).await?; let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?; @@ -619,8 +615,6 @@ async fn edit_schedule( es.on_recovery.as_deref(), es.on_success.as_deref(), ]); - let can_name_hub = can_name_hub(&new_handlers, &authed, &db, &w_id).await?; - let mut tx = user_db.begin(&authed).await?; // Validate dynamic_skip if provided @@ -635,8 +629,11 @@ async fn edit_schedule( ["on_failure", "on_recovery", "on_success"] .map(|f| before.as_ref().and_then(|b| b.get(f)?.as_str())), ), - can_name_hub, - )?; + &authed, + &db, + &w_id, + ) + .await?; let schedule = sqlx::query_as!( Schedule, diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 89d907c3d1..e5044cdb8a 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -14407,6 +14407,7 @@ async fn load_workspace_authed( job_id: base_authed.job_id, credential_expiry: base_authed.credential_expiry, mcp_client: base_authed.mcp_client.clone(), + capabilities: None, }); }; @@ -14448,6 +14449,7 @@ async fn load_workspace_authed( job_id: base_authed.job_id, credential_expiry: base_authed.credential_expiry, mcp_client: base_authed.mcp_client.clone(), + capabilities: None, }) } diff --git a/backend/windmill-api/src/capture.rs b/backend/windmill-api/src/capture.rs index d9275c5058..87d9b41714 100644 --- a/backend/windmill-api/src/capture.rs +++ b/backend/windmill-api/src/capture.rs @@ -573,11 +573,11 @@ async fn set_config( // trigger's, so the URL takes the trigger save's Hub rule. A capture keeps nothing to compare. #[cfg(feature = "websocket")] if matches!(nc.trigger_kind, TriggerKind::Websocket) { - use windmill_api_auth::composed::{can_name_hub, check_new_hub_paths}; + use windmill_api_auth::composed::check_new_hub_paths; use windmill_trigger::TriggerCrud; let config = serde_json::to_value(&nc.trigger_config)?; let new = windmill_trigger_websocket::WebsocketTrigger::config_runnables(&config); - check_new_hub_paths(&new, &[], can_name_hub(&new, &authed, &db, &w_id).await?)?; + check_new_hub_paths(&new, &[], &authed, &db, &w_id).await?; } let mut tx = user_db.begin(&authed).await?; diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index 7b70acce62..7c684dbb39 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -13358,6 +13358,7 @@ mod approval_view_gate_tests { job_id: None, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 83df75f5ca..15243e7cbf 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -399,6 +399,7 @@ async fn inject_agent_authed( job_id: None, credential_expiry: None, mcp_client: None, + capabilities: None, }, job_id: None, }); diff --git a/backend/windmill-api/src/mcp/utils.rs b/backend/windmill-api/src/mcp/utils.rs index 72ed0ca03e..1330d7cbca 100644 --- a/backend/windmill-api/src/mcp/utils.rs +++ b/backend/windmill-api/src/mcp/utils.rs @@ -1466,6 +1466,7 @@ mod tests { job_id, credential_expiry: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/windmill-common/src/auth.rs b/backend/windmill-common/src/auth.rs index 330566f5f3..b91bdf68a8 100644 --- a/backend/windmill-common/src/auth.rs +++ b/backend/windmill-common/src/auth.rs @@ -413,6 +413,7 @@ impl From for Authed { scopes: None, token_prefix: None, mcp_client: value.mcp_client, + capabilities: None, } } } @@ -606,6 +607,7 @@ async fn fetch_authed_from_permissioned_as_inner( scopes: None, token_prefix: None, mcp_client: None, + capabilities: None, }) } else { let groups = vec![name.to_string()]; @@ -620,6 +622,7 @@ async fn fetch_authed_from_permissioned_as_inner( scopes: None, token_prefix: None, mcp_client: None, + capabilities: None, }) } } else { @@ -642,6 +645,7 @@ async fn fetch_authed_from_permissioned_as_inner( scopes: None, token_prefix: None, mcp_client: None, + capabilities: None, }) } } diff --git a/backend/windmill-common/src/db.rs b/backend/windmill-common/src/db.rs index edda7fca07..6093ffa76a 100644 --- a/backend/windmill-common/src/db.rs +++ b/backend/windmill-common/src/db.rs @@ -1,6 +1,6 @@ use sqlx::{Acquire, PgConnection, PgExecutor, Pool, Postgres, Transaction}; -use crate::audit::AuditAuthor; +use crate::{audit::AuditAuthor, roles::RoleCapabilities}; pub type DB = Pool; @@ -22,6 +22,8 @@ pub struct Authed { pub token_prefix: Option, /// See `ApiAuthed::mcp_client`. pub mcp_client: Option, + /// See `ApiAuthed::capabilities`. + pub capabilities: Option, } impl Authed { @@ -35,6 +37,7 @@ impl Authed { folders: &self.folders, scopes: &self.scopes, token_prefix: &self.token_prefix, + capabilities: self.capabilities, } } } @@ -50,6 +53,7 @@ pub struct AuthedRef<'a> { pub folders: &'a Vec<(String, bool, bool)>, pub scopes: &'a Option>, pub token_prefix: &'a Option, + pub capabilities: Option, } impl Authable for AuthedRef<'_> { @@ -65,6 +69,9 @@ impl Authable for AuthedRef<'_> { fn is_operator(&self) -> bool { *self.is_operator } + fn capabilities(&self) -> Option { + self.capabilities + } fn groups(&self) -> &[String] { self.groups } @@ -86,6 +93,9 @@ pub trait Authable { fn username(&self) -> &str; fn is_admin(&self) -> bool; fn is_operator(&self) -> bool; + /// The role's capabilities as read for the request, `None` if they were not read. Read them + /// through `roles::caller_capabilities`, never directly. + fn capabilities(&self) -> Option; fn groups(&self) -> &[String]; fn folders(&self) -> &[(String, bool, bool)]; fn scopes(&self) -> Option<&[String]>; @@ -100,6 +110,10 @@ impl Authable for Authed { self.is_operator } + fn capabilities(&self) -> Option { + self.capabilities + } + fn groups(&self) -> &[String] { &self.groups } diff --git a/backend/windmill-common/src/jobs.rs b/backend/windmill-common/src/jobs.rs index a9e40c50e2..2e5dafe1b2 100644 --- a/backend/windmill-common/src/jobs.rs +++ b/backend/windmill-common/src/jobs.rs @@ -188,26 +188,12 @@ pub async fn check_can_name_runnable( let RunOrigin::NamedBy(authed) = origin else { return Ok(()); }; - if !naming_needs_code(runnable) { - return Ok(()); - } - check_can_name_with( - runnable, - crate::roles::caller_capabilities(db, w_id, authed) + if !runnable.path().starts_with("hub/") + || runnable.preset_handler().is_some() + || crate::roles::caller_capabilities(db, w_id, authed) .await? - .code, - ) -} - -/// A Hub path that is not a preset handler. -pub fn naming_needs_code(runnable: &RunnableRef) -> bool { - runnable.path().starts_with("hub/") && runnable.preset_handler().is_none() -} - -/// `check_can_name_runnable` for a caller whose `code` capability is already resolved, so a check -/// inside a transaction does not take a second pooled connection. -pub fn check_can_name_with(runnable: &RunnableRef, code: bool) -> error::Result<()> { - if code || !naming_needs_code(runnable) { + .code + { return Ok(()); } Err(Error::PermissionDenied( diff --git a/backend/windmill-common/src/roles.rs b/backend/windmill-common/src/roles.rs index 1f7822437a..f1db372cf3 100644 --- a/backend/windmill-common/src/roles.rs +++ b/backend/windmill-common/src/roles.rs @@ -27,7 +27,9 @@ pub const DEVELOPER_ROLE: &str = "developer"; pub const OPERATOR_ROLE: &str = "operator"; /// How much of a kind of runnable a role may author. -#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Default, PartialOrd, Ord)] +#[derive( + Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash, Default, PartialOrd, Ord, +)] #[serde(rename_all = "snake_case")] pub enum AuthorLevel { #[default] @@ -41,7 +43,7 @@ pub enum AuthorLevel { /// 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)] +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct RoleVisibility { pub runs: bool, pub schedules: bool, @@ -82,7 +84,7 @@ impl RoleVisibility { }; } -#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Serialize, Deserialize, Clone, Copy, 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 @@ -759,7 +761,10 @@ async fn member_role(db: &DB, workspace_id: &str, username: &str) -> Result( db: &DB, workspace_id: &str, @@ -768,6 +773,9 @@ pub async fn caller_capabilities( if authed.is_admin() || !authed.is_operator() { return Ok(RoleCapabilities::FULL); } + if let Some(caps) = authed.capabilities() { + return Ok(caps); + } match member_role(db, workspace_id, authed.username()).await? { Some(role) => role_capabilities_by_name(db, workspace_id, &role).await, None => Ok(RoleCapabilities::NONE), diff --git a/backend/windmill-common/src/workspaces.rs b/backend/windmill-common/src/workspaces.rs index b101a4ea39..2c43456896 100644 --- a/backend/windmill-common/src/workspaces.rs +++ b/backend/windmill-common/src/workspaces.rs @@ -4006,6 +4006,7 @@ mod tests { folders: &folders, scopes: &scopes, token_prefix: &token_prefix, + capabilities: Some(crate::roles::RoleCapabilities::FULL), }; assert!(can_use_datatable_role(&tenants(&["u/alice"]), &authed)); @@ -4044,6 +4045,7 @@ mod tests { folders: &folders, scopes: &scopes, token_prefix: &token_prefix, + capabilities: Some(crate::roles::RoleCapabilities::FULL), }; assert!(!can_use_datatable_role(&tenants(&["*"]), &admin)); assert!(!can_use_datatable_role(&tenants(&["u/alice"]), &admin)); diff --git a/backend/windmill-queue/tests/schedule_push.rs b/backend/windmill-queue/tests/schedule_push.rs index 0cda6d3766..7de6be09ff 100644 --- a/backend/windmill-queue/tests/schedule_push.rs +++ b/backend/windmill-queue/tests/schedule_push.rs @@ -66,6 +66,7 @@ mod schedule_push { scopes: None, token_prefix: None, mcp_client: None, + capabilities: Some(windmill_common::roles::RoleCapabilities::FULL), } } diff --git a/backend/windmill-store/src/var_resource_cache.rs b/backend/windmill-store/src/var_resource_cache.rs index 3e89f8579e..8fc05797c8 100644 --- a/backend/windmill-store/src/var_resource_cache.rs +++ b/backend/windmill-store/src/var_resource_cache.rs @@ -250,6 +250,9 @@ mod tests { fn is_operator(&self) -> bool { self.is_operator } + fn capabilities(&self) -> Option { + None + } fn groups(&self) -> &[String] { &self.groups } diff --git a/backend/windmill-trigger-http/src/handler.rs b/backend/windmill-trigger-http/src/handler.rs index f1cba37519..20c51dffb4 100644 --- a/backend/windmill-trigger-http/src/handler.rs +++ b/backend/windmill-trigger-http/src/handler.rs @@ -294,17 +294,16 @@ pub async fn create_many_http_triggers( .validate_new(&db, &w_id, &new_http_trigger.config) .await .map_err(|err| error_wrapper(&new_http_trigger.config.route_path, err))?; - let (new, can_name_hub) = - trigger_save_runnables::(new_http_trigger, &authed, &db, &w_id).await?; - windmill_api_auth::composed::check_new_hub_paths(&new, &[], can_name_hub).map_err( - |err| match err { + let new = trigger_save_runnables::(new_http_trigger)?; + windmill_api_auth::composed::check_new_hub_paths(&new, &[], &authed, &db, &w_id) + .await + .map_err(|err| match err { Error::PermissionDenied(msg) => Error::PermissionDenied(format!( "Error occurred for HTTP route at route path: {}, error: {msg}", new_http_trigger.config.route_path )), err => err, - }, - )?; + })?; let route_path_key = check_if_route_exist(&db, &new_http_trigger.config, &w_id, None).await?; diff --git a/backend/windmill-trigger/src/handler.rs b/backend/windmill-trigger/src/handler.rs index 533958469b..512ce51f82 100644 --- a/backend/windmill-trigger/src/handler.rs +++ b/backend/windmill-trigger/src/handler.rs @@ -14,7 +14,7 @@ use sqlx::{FromRow, PgConnection}; use std::fmt::Debug; use windmill_api_auth::{ build_scope_path_predicate, check_scopes, - composed::{can_name_hub, check_new_hub_paths}, + composed::check_new_hub_paths, ApiAuthed, }; use windmill_common::{ @@ -503,17 +503,11 @@ fn trigger_runnables(trigger: &serde_json::Value) -> Vec( +/// The runnables a trigger save names, for `check_new_hub_paths`. +pub fn trigger_save_runnables( trigger: &TriggerData, - authed: &ApiAuthed, - db: &DB, - workspace_id: &str, -) -> Result<(Vec, bool)> { - let new = trigger_runnables::(&serde_json::to_value(trigger)?); - let can_name_hub = can_name_hub(&new, authed, db, workspace_id).await?; - Ok((new, can_name_hub)) +) -> Result> { + Ok(trigger_runnables::(&serde_json::to_value(trigger)?)) } /// Append this mutation to `trigger_history`, diffing the row at `path` against @@ -602,9 +596,8 @@ async fn create_trigger( handler .validate_new(&db, &workspace_id, &new_trigger.config) .await?; - let (new, can_name_hub) = - trigger_save_runnables::(&new_trigger, &authed, &db, &workspace_id).await?; - check_new_hub_paths(&new, &[], can_name_hub)?; + let new = trigger_save_runnables::(&new_trigger)?; + check_new_hub_paths(&new, &[], &authed, &db, &workspace_id).await?; let mut tx = user_db.begin(&authed).await?; @@ -878,8 +871,7 @@ async fn update_trigger( handler .validate_edit(&db, &workspace_id, &edit_trigger.config, path) .await?; - let (new_runnables, can_name_hub) = - trigger_save_runnables::(&edit_trigger, &authed, &db, &workspace_id).await?; + let new_runnables = trigger_save_runnables::(&edit_trigger)?; let mut tx = user_db.begin(&authed).await?; @@ -929,8 +921,11 @@ async fn update_trigger( .as_ref() .map(trigger_runnables::) .unwrap_or_default(), - can_name_hub, - )?; + &authed, + &db, + &workspace_id, + ) + .await?; handler .update_trigger(&db, &mut *tx, &authed, &workspace_id, path, edit_trigger) diff --git a/docs/workspace-roles.md b/docs/workspace-roles.md index 53d843d153..02db77c3f8 100644 --- a/docs/workspace-roles.md +++ b/docs/workspace-roles.md @@ -79,6 +79,12 @@ returns `FULL` for an unrestricted or admin caller without reading the role), so derived from the role: a stale flag lets a restricted member through. The authentication cache holds it for up to 120s. +`ApiAuthed::capabilities` is the role itself, read for each request before its handler runs, so a +capability check inside a save's transaction, the Hub rule included, never needs a second +connection. It is read from the role caches and never stored with the cached login: storing it +there would need every role change to clear the login on every server, running jobs' tokens +included. An identity built outside a request has none, and `caller_capabilities` reads the role. + `usr.operator` is kept as "this role cannot write code", which is what clients that predate roles read it as. A member's role is `usr.workspace_role`, or, while that is NULL, `operator` / `developer` from `usr.operator`: rows written by paths that know nothing of roles stay meaningful.