mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-21 16:06:54 +00:00
fix: resolve the caller's role capabilities at authentication (#12501)
* fix: resolve the caller's role capabilities at authentication * chore: update ee-repo-ref to e4bfe4229dfd07f6c356835c2ac0e80c2729d582 This commit updates the EE repository reference after PR #990 was merged in windmill-ee-private. Previous ee-repo-ref: 637d417668a1c3b4203cfedf782bd72648fdb102 New ee-repo-ref: e4bfe4229dfd07f6c356835c2ac0e80c2729d582 Automated by sync-ee-ref workflow. --------- Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com> Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
This commit is contained in:
co-authored by
windmill-internal-app[bot]
Ruben Fiszel
parent
258b5564c0
commit
e24a4309d0
@@ -1 +1 @@
|
||||
000a83d34767b44c041612df31e2a3e7e305d63a
|
||||
e4bfe4229dfd07f6c356835c2ac0e80c2729d582
|
||||
|
||||
@@ -360,6 +360,7 @@ async fn test_job_token_run_keeps_end_user_email(db: Pool<Postgres>) -> anyhow::
|
||||
scopes: None,
|
||||
token_prefix: None,
|
||||
mcp_client: None,
|
||||
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
|
||||
},
|
||||
"test-workspace",
|
||||
3600,
|
||||
|
||||
@@ -103,3 +103,79 @@ async fn a_hub_step_follows_the_code_capability(db: Pool<Postgres>) -> 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<Postgres>,
|
||||
) -> 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(())
|
||||
}
|
||||
|
||||
@@ -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<Postgres>) -> 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<Postgres>) -> 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<Postgres>| {
|
||||
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(())
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -38,6 +38,7 @@ async fn run_by_path_of_a_missing_script_uses_one_connection(db: Pool<Postgres>)
|
||||
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()) }),
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ fn outsider() -> ApiAuthed {
|
||||
job_id: None,
|
||||
credential_expiry: None,
|
||||
mcp_client: None,
|
||||
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<bool> {
|
||||
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?;
|
||||
}
|
||||
|
||||
@@ -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<String>,
|
||||
/// The role's capabilities in the request's workspace (`AuthCache::get_opt_job_authed`); `None`
|
||||
/// outside a request.
|
||||
pub capabilities: Option<RoleCapabilities>,
|
||||
}
|
||||
|
||||
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<ApiAuthed> for Authed {
|
||||
scopes: value.scopes,
|
||||
token_prefix: value.token_prefix,
|
||||
mcp_client: value.mcp_client,
|
||||
capabilities: value.capabilities,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -183,6 +189,7 @@ impl From<Authed> 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<RoleCapabilities> {
|
||||
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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -106,6 +106,7 @@ async fn test_preview_on_behalf_of(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
scopes: None,
|
||||
token_prefix: None,
|
||||
mcp_client: None,
|
||||
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
|
||||
},
|
||||
"test-workspace",
|
||||
3600,
|
||||
|
||||
@@ -61,7 +61,14 @@ async fn test_withdrawn_run_refuses_runs(db: Pool<Postgres>) -> 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));
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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?;
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -399,6 +399,7 @@ async fn inject_agent_authed(
|
||||
job_id: None,
|
||||
credential_expiry: None,
|
||||
mcp_client: None,
|
||||
capabilities: None,
|
||||
},
|
||||
job_id: None,
|
||||
});
|
||||
|
||||
@@ -1466,6 +1466,7 @@ mod tests {
|
||||
job_id,
|
||||
credential_expiry: None,
|
||||
mcp_client: None,
|
||||
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -413,6 +413,7 @@ impl From<JobPerms> 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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Postgres>;
|
||||
|
||||
@@ -22,6 +22,8 @@ pub struct Authed {
|
||||
pub token_prefix: Option<String>,
|
||||
/// See `ApiAuthed::mcp_client`.
|
||||
pub mcp_client: Option<String>,
|
||||
/// See `ApiAuthed::capabilities`.
|
||||
pub capabilities: Option<RoleCapabilities>,
|
||||
}
|
||||
|
||||
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<Vec<String>>,
|
||||
pub token_prefix: &'a Option<String>,
|
||||
pub capabilities: Option<RoleCapabilities>,
|
||||
}
|
||||
|
||||
impl Authable for AuthedRef<'_> {
|
||||
@@ -65,6 +69,9 @@ impl Authable for AuthedRef<'_> {
|
||||
fn is_operator(&self) -> bool {
|
||||
*self.is_operator
|
||||
}
|
||||
fn capabilities(&self) -> Option<RoleCapabilities> {
|
||||
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<RoleCapabilities>;
|
||||
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<RoleCapabilities> {
|
||||
self.capabilities
|
||||
}
|
||||
|
||||
fn groups(&self) -> &[String] {
|
||||
&self.groups
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<Opti
|
||||
/// restricted, holds everything; a restricted caller holds its role's capabilities, or none if it
|
||||
/// has no membership (a guest, a removed member's job). `workspace_id` MUST be the route's.
|
||||
///
|
||||
/// Call it before opening an RLS transaction; see [`workspace_roles`].
|
||||
/// Queries nothing for a caller whose capabilities authentication filled in
|
||||
/// ([`Authable::capabilities`]): a request's, unless reading its role failed then. Any other
|
||||
/// caller has its role read from the pool, so for one call it before opening an RLS transaction;
|
||||
/// see [`workspace_roles`].
|
||||
pub async fn caller_capabilities<A: Authable + ?Sized>(
|
||||
db: &DB,
|
||||
workspace_id: &str,
|
||||
@@ -768,6 +773,9 @@ pub async fn caller_capabilities<A: Authable + ?Sized>(
|
||||
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),
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -66,6 +66,7 @@ mod schedule_push {
|
||||
scopes: None,
|
||||
token_prefix: None,
|
||||
mcp_client: None,
|
||||
capabilities: Some(windmill_common::roles::RoleCapabilities::FULL),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -250,6 +250,9 @@ mod tests {
|
||||
fn is_operator(&self) -> bool {
|
||||
self.is_operator
|
||||
}
|
||||
fn capabilities(&self) -> Option<windmill_common::roles::RoleCapabilities> {
|
||||
None
|
||||
}
|
||||
fn groups(&self) -> &[String] {
|
||||
&self.groups
|
||||
}
|
||||
|
||||
@@ -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::<HttpTrigger>(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::<HttpTrigger>(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?;
|
||||
|
||||
@@ -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<T: TriggerCrud>(trigger: &serde_json::Value) -> Vec<Runnabl
|
||||
runnables
|
||||
}
|
||||
|
||||
/// The runnables a trigger save names, and whether the saver may name the Hub ones among them,
|
||||
/// for `check_new_hub_paths`. Resolve it before the save's transaction opens.
|
||||
pub async fn trigger_save_runnables<T: TriggerCrud>(
|
||||
/// The runnables a trigger save names, for `check_new_hub_paths`.
|
||||
pub fn trigger_save_runnables<T: TriggerCrud>(
|
||||
trigger: &TriggerData<T::TriggerConfigRequest>,
|
||||
authed: &ApiAuthed,
|
||||
db: &DB,
|
||||
workspace_id: &str,
|
||||
) -> Result<(Vec<RunnableRef>, bool)> {
|
||||
let new = trigger_runnables::<T>(&serde_json::to_value(trigger)?);
|
||||
let can_name_hub = can_name_hub(&new, authed, db, workspace_id).await?;
|
||||
Ok((new, can_name_hub))
|
||||
) -> Result<Vec<RunnableRef>> {
|
||||
Ok(trigger_runnables::<T>(&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<T: TriggerCrud>(
|
||||
handler
|
||||
.validate_new(&db, &workspace_id, &new_trigger.config)
|
||||
.await?;
|
||||
let (new, can_name_hub) =
|
||||
trigger_save_runnables::<T>(&new_trigger, &authed, &db, &workspace_id).await?;
|
||||
check_new_hub_paths(&new, &[], can_name_hub)?;
|
||||
let new = trigger_save_runnables::<T>(&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<T: TriggerCrud>(
|
||||
handler
|
||||
.validate_edit(&db, &workspace_id, &edit_trigger.config, path)
|
||||
.await?;
|
||||
let (new_runnables, can_name_hub) =
|
||||
trigger_save_runnables::<T>(&edit_trigger, &authed, &db, &workspace_id).await?;
|
||||
let new_runnables = trigger_save_runnables::<T>(&edit_trigger)?;
|
||||
|
||||
let mut tx = user_db.begin(&authed).await?;
|
||||
|
||||
@@ -929,8 +921,11 @@ async fn update_trigger<T: TriggerCrud>(
|
||||
.as_ref()
|
||||
.map(trigger_runnables::<T>)
|
||||
.unwrap_or_default(),
|
||||
can_name_hub,
|
||||
)?;
|
||||
&authed,
|
||||
&db,
|
||||
&workspace_id,
|
||||
)
|
||||
.await?;
|
||||
|
||||
handler
|
||||
.update_trigger(&db, &mut *tx, &authed, &workspace_id, path, edit_trigger)
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user