fix: check bulk cancel and restart against run, bound the run cache

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
hugocasa
2026-11-13 17:39:01 +01:00
co-authored by Claude Opus 5.5
parent 734b81a5d2
commit 3b9fcde00f
5 changed files with 120 additions and 24 deletions
@@ -100,6 +100,37 @@ async fn test_view_only_grants(db: Pool<Postgres>) -> anyhow::Result<()> {
403
);
// The viewer reads the admin's queued run but cannot stop it, one by one or in a selection.
let job = admin
.post(format!(
"http://localhost:{port}/api/w/{WS}/jobs/run/p/f/vo/s?scheduled_for=2100-01-01T00:00:00Z"
))
.json(&json!({}))
.send()
.await?
.text()
.await?;
assert_eq!(
post(
&viewer,
port,
&format!("jobs_u/queue/cancel/{job}"),
json!({})
)
.await?,
403
);
let cancelled: Vec<String> = viewer
.post(format!(
"http://localhost:{port}/api/w/{WS}/jobs/queue/cancel_selection"
))
.json(&json!([job]))
.send()
.await?
.json()
.await?;
assert!(cancelled.is_empty(), "cancelled {cancelled:?}");
// Grants add up: an item grant that runs lifts the folder's view-only one.
let item_grant = json!({"owner": "u/test-user-2", "level": "run"});
assert_eq!(
+66 -16
View File
@@ -2431,9 +2431,54 @@ async fn require_run_on_others_job(
kind: JobKind,
runnable_path: Option<String>,
) -> error::Result<()> {
// The kinds a job's path may name: a flow preview is a flow editor's run or a saved agent's
// (its chat turns under `<agent>.chat`), and a single-step flow wraps a script or a flow for
// retries or an error handler. Whichever lets the caller run passes.
match runnable_path {
Some(path) if created_by != authed.username => {
require_can_run_job_path(db, authed, w_id, kind, &path).await
}
_ => Ok(()),
}
}
/// [`require_run_on_others_job`] as a yes or no, for a selection that skips what it may not stop.
async fn may_stop_job(db: &DB, authed: &ApiAuthed, w_id: &str, id: Uuid) -> error::Result<bool> {
let Some(job) = sqlx::query!(
"SELECT created_by, runnable_path, kind AS \"kind: JobKind\" FROM v2_job
WHERE id = $1 AND workspace_id = $2",
id,
w_id,
)
.fetch_optional(db)
.await?
else {
return Ok(true);
};
match require_run_on_others_job(
db,
authed,
w_id,
&job.created_by,
job.kind,
job.runnable_path,
)
.await
{
Ok(()) => Ok(true),
Err(Error::PermissionDenied(_)) => Ok(false),
Err(e) => Err(e),
}
}
/// `require_can_run` on the runnable a job's path names, for a job of `kind`.
async fn require_can_run_job_path(
db: &DB,
authed: &ApiAuthed,
w_id: &str,
kind: JobKind,
path: &str,
) -> error::Result<()> {
// A flow preview is a flow editor's run or a saved agent's (its chat turns under
// `<agent>.chat`), and a single-step flow wraps a script or a flow for retries or an error
// handler. Whichever lets the caller run passes.
let candidates: &[RunnableAclKind] = match kind {
JobKind::Script | JobKind::Preview => &[RunnableAclKind::Script],
JobKind::Flow => &[RunnableAclKind::Flow],
@@ -2441,10 +2486,7 @@ async fn require_run_on_others_job(
JobKind::SingleStepFlow => &[RunnableAclKind::Script, RunnableAclKind::Flow],
_ => return Ok(()),
};
let Some(path) = runnable_path.filter(|_| created_by != authed.username) else {
return Ok(());
};
let path = path.strip_suffix(".chat").unwrap_or(&path);
let path = path.strip_suffix(".chat").unwrap_or(path);
let mut result = Ok(());
for kind in candidates {
result = require_can_run(db, &authed.to_authed_ref(), w_id, *kind, path).await;
@@ -4669,15 +4711,30 @@ async fn cancel_selection(
// workspace so cross-workspace selections (all_workspaces=true) aren't
// silently dropped. In single-workspace mode the SQL filter above ensures
// this collapses to a single call.
let force_cancel = query.force_cancel.unwrap_or(false);
let mut jobs_by_workspace: HashMap<String, Vec<Uuid>> = HashMap::new();
for row in rows {
// Dropped like a job the caller cannot read: stopping another member's run takes run on
// it, checked on the job a force cancel actually kills too.
if !authed.is_admin {
let target = if force_cancel {
force_cancel_target(&db, &row.workspace_id, row.id).await?
} else {
row.id
};
if !may_stop_job(&db, &authed, &row.workspace_id, row.id).await?
|| (target != row.id
&& !may_stop_job(&db, &authed, &row.workspace_id, target).await?)
{
continue;
}
}
jobs_by_workspace
.entry(row.workspace_id)
.or_default()
.push(row.id);
}
let force_cancel = query.force_cancel.unwrap_or(false);
let mut cancelled = Vec::new();
for (workspace_id, ids) in jobs_by_workspace {
let ids =
@@ -7705,14 +7762,7 @@ pub async fn restart_flow(
.script_path
.with_context(|| "No flow path set for completed flow job")?;
check_scopes(&authed, || format!("jobs:run:flows:{flow_path}"))?;
require_can_run(
&db,
&authed.to_authed_ref(),
&w_id,
RunnableAclKind::Flow,
&flow_path,
)
.await?;
require_can_run_job_path(&db, &authed, &w_id, completed_job.kind, &flow_path).await?;
let mut run_query = run_query;
drop_unclaimable_run_lineage(&db, &w_id, &mut run_query, &authed).await?;
// A restarted flow preview reruns the value its request supplied, while a flow preview
+1 -1
View File
@@ -2,7 +2,7 @@
//!
//! An agent answers only in the Slack channels it is shared in, to the workspace members whose
//! email matches the asker's Slack email, as Windmill would run it for them: through their own
//! permissions, so only if they can read it. With `slack_anyone`, set in its settings and kept
//! permissions, so only if they can run it (a view-only grant gets no answer). With `slack_anyone`, set in its settings and kept
//! only while it runs on behalf of an identity, it answers anyone in those channels instead: the
//! channel is the trust boundary, as Slack decides who is in it, and everyone runs it as that
//! identity, who agreed to it by deploying the agent so. Who may share it is then only who may
+20 -6
View File
@@ -180,10 +180,17 @@ lazy_static::lazy_static! {
// Cache for script hash permissions - (ApiAuthed hash, script_hash) -> permission result
pub static ref HASH_PERMS_CACHE: PermsCache = PermsCache::new();
pub static ref FLOW_PERMS_CACHE: PermsCache = PermsCache::new();
// (caller perms hash, runnable hash) -> the caller may run it
static ref RUN_PERMS_CACHE: PermsCache = PermsCache::new();
// (caller perms hash, runnable hash) -> when the caller was found able to run it
static ref RUN_PERMS_CACHE: Cache<(u64, u64), std::time::Instant> = Cache::new(10000);
}
/// Bounds what the invalidation cannot see: an item deleted and recreated at the same path
/// without the grant that let the caller run it.
const RUN_PERMS_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(60);
/// Bumped by every invalidation, so a check that read the grants before a demotion committed
/// does not cache what it found after the cache was cleared.
static RUN_PERMS_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
#[derive(Clone, Copy, Debug, Hash)]
pub enum RunnableAclKind {
Script,
@@ -218,7 +225,8 @@ pub async fn notify_run_perms_change(conn: &mut sqlx::PgConnection) -> Result<()
}
pub fn invalidate_run_perms_cache() {
RUN_PERMS_CACHE.0.clear();
RUN_PERMS_GENERATION.fetch_add(1, Ordering::SeqCst);
RUN_PERMS_CACHE.clear();
}
/// Whether the caller may start `path`, as opposed to only reading it. Readers run unless every
@@ -245,10 +253,14 @@ pub async fn require_can_run(
let mut hasher = DefaultHasher::new();
(w_id, kind, path).hash(&mut hasher);
let key = hasher.finish();
let (cached, authed_hash) = RUN_PERMS_CACHE.check_perms_in_cache(authed, key);
if cached {
let cache_key = (PermsCache::compute_hash(authed), key);
if RUN_PERMS_CACHE
.get(&cache_key)
.is_some_and(|at| at.elapsed() < RUN_PERMS_CACHE_TTL)
{
return Ok(());
}
let generation = RUN_PERMS_GENERATION.load(Ordering::SeqCst);
let folder = (prefix == Some("f")).then_some(owner).flatten();
let mut principals = authed
@@ -291,7 +303,9 @@ pub async fn require_can_run(
"You do not have run access to {path}"
)));
}
RUN_PERMS_CACHE.insert(authed_hash, key);
if RUN_PERMS_GENERATION.load(Ordering::SeqCst) == generation {
RUN_PERMS_CACHE.insert(cache_key, std::time::Instant::now());
}
Ok(())
}
+2 -1
View File
@@ -70,7 +70,8 @@ saving of schedules and triggers, and the firing of triggers, which fetch their
owner on every fire. A schedule's later runs are not re-checked, as they were never re-checked
for read either: demoting its owner does not stop it. Flow steps, subflows and agent tools are not
checked, as only the top-level run needs it. Its positive answers are cached, so every write that can take
run away calls `notify_run_perms_change`. Anything that copies one of those rows (a new script
run away calls `notify_run_perms_change`; the cache's 60s expiry bounds what that cannot see, such
as an item deleted and recreated without the grant. Anything that copies one of those rows (a new script
version, a rename, a fork, a workspace rename) must copy `view_only` too: a copy that drops it
turns its viewers into runners.