fix: let a folder rule claim a new item that names only its creator

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
hugocasa
2026-10-19 13:44:30 +02:00
co-authored by Claude Opus 5.5
parent 617ec38c44
commit 7c6b54e670
10 changed files with 97 additions and 53 deletions
@@ -521,6 +521,45 @@ async fn test_folder_default_permissioned_as(db: Pool<Postgres>) -> anyhow::Resu
"a rule naming an address stores the principal it names, which is what carries that user's groups and folders"
);
// 5b'. Naming only yourself is not a choice: the run-as pickers start on "me", so the rule
// still applies; naming someone else is, and wins over it.
let mut named_self = new_flow("f/prodfolder/jobs/flow_named_self");
named_self["on_behalf_of_email"] = json!("test@windmill.dev");
let mut named_other = new_flow("f/prodfolder/jobs/flow_named_other");
named_other["on_behalf_of_email"] = json!("original@windmill.dev");
for body in [&named_self, &named_other] {
let resp = authed(
client().post(format!("{base}/flows/create")),
"SECRET_TOKEN",
)
.json(body)
.send()
.await?;
assert_eq!(resp.status(), 201, "{}", resp.text().await?);
}
let identity = |path: &'static str| {
sqlx::query_scalar!(
"SELECT on_behalf_of FROM flow WHERE path = $1 AND workspace_id = $2",
path,
"test-workspace"
)
.fetch_one(&db)
};
assert_eq!(
identity("f/prodfolder/jobs/flow_named_self")
.await?
.as_deref(),
Some("g/wm_deployers"),
"a flow naming only its creator takes the folder default"
);
assert_eq!(
identity("f/prodfolder/jobs/flow_named_other")
.await?
.as_deref(),
Some("u/original-user"),
"a flow naming someone else keeps them"
);
// 5c. Non-matching flow path — no default
let resp = authed(
client().post(format!("{base}/flows/create")),
+6 -4
View File
@@ -790,10 +790,12 @@ async fn create_flow(
// cron::Schedule::from_str(&ns.schedule).map_err(|e| error::Error::BadRequest(e.to_string()))?;
let authed = maybe_refresh_folders(&nf.path, &w_id, authed, &db).await;
// A deploy naming any identity, the caller's own included, has chosen one: the folder's
// default only fills in for a deploy that names none.
let names_identity = nf.on_behalf_of_email.is_some() || nf.on_behalf_of.is_some();
if !names_identity && windmill_common::can_preserve_on_behalf_of(&authed) {
if windmill_common::names_only_caller(
nf.on_behalf_of_email.as_deref(),
nf.on_behalf_of.as_deref(),
&authed,
) && windmill_common::can_preserve_on_behalf_of(&authed)
{
if let Some((default_email, default_permissioned_as)) =
windmill_common::folders::resolve_folder_default_on_behalf_of(&db, &w_id, &nf.path)
.await?
+6 -2
View File
@@ -44,7 +44,8 @@ use windmill_queue::schedule::push_scheduled_job;
/// The identity a schedule write stores: the one it names for a caller allowed to keep it (see
/// `resolve_on_behalf_of`, which also refuses one that names nobody), the caller's own otherwise,
/// and on create (`create_path`) the folder's `default_permissioned_as` when it names none.
/// and on create (`create_path`) the folder's `default_permissioned_as` when it names nobody but
/// the caller (see `names_only_caller`).
async fn resolve_permissioned_as(
permissioned_as: Option<&str>,
create_path: Option<&str>,
@@ -53,7 +54,10 @@ async fn resolve_permissioned_as(
w_id: &str,
) -> Result<String> {
let requested = permissioned_as.filter(|pa| !pa.is_empty());
if requested.is_none() && can_preserve_on_behalf_of(authed) {
let names_only_caller = requested.map_or(true, |pa| {
pa == authed.email || windmill_common::names_only_caller(None, Some(pa), authed)
});
if names_only_caller && can_preserve_on_behalf_of(authed) {
if let Some(path) = create_path {
if let Some(default) =
windmill_common::folders::resolve_folder_default_permissioned_as(db, w_id, path)
+6 -4
View File
@@ -1400,12 +1400,14 @@ async fn create_script_internal<'c>(
// Everything read from `db` happens before `tx` opens: `user_db` wraps the same pool, so a
// deploy taking a second connection while holding `tx` lets N concurrent deploys hold the
// whole pool between them and each wait out the acquire timeout for one more.
// A deploy naming any identity, the caller's own included, has chosen one: the folder's
// default only fills in for a deploy that names none.
let names_identity = ns.on_behalf_of_email.is_some() || ns.on_behalf_of.is_some();
let takes_folder_default = windmill_common::names_only_caller(
ns.on_behalf_of_email.as_deref(),
ns.on_behalf_of.as_deref(),
&authed,
) && windmill_common::can_preserve_on_behalf_of(&authed);
// Held rather than raised: a rule naming a principal that no longer exists fails here, and
// must fail only a first deploy, which is all the default applies to.
let folder_default = if !names_identity && windmill_common::can_preserve_on_behalf_of(&authed) {
let folder_default = if takes_folder_default {
resolve_folder_default_identity(&authed, &w_id, &ns.path, &db).await
} else {
Ok(None)
+6 -1
View File
@@ -2839,8 +2839,13 @@ async fn create_app_internal<'a>(
// a second simultaneous connection while `tx` is still checked out. The race this
// leaves with a concurrent rename or removal, including a freed username later
// rebinding the stored principal, is known and accepted: see `resolve_on_behalf_of`.
// A policy naming only the caller takes the branch below, which is also the caller.
let should_preserve = windmill_common::can_preserve_on_behalf_of(&authed)
&& (app.policy.on_behalf_of.is_some() || app.policy.on_behalf_of_email.is_some());
&& !windmill_common::names_only_caller(
app.policy.on_behalf_of_email.as_deref(),
app.policy.on_behalf_of.as_deref(),
&authed,
);
let mut preserved_on_behalf_of: Option<String> = None;
if should_preserve {
+17 -3
View File
@@ -306,6 +306,20 @@ pub fn check_on_behalf_of_preservation(
.map(str::to_string)
}
/// Whether a requested identity names nobody but the caller: every half given (an address, a
/// principal) is theirs. A write requesting only the caller has chosen nobody, so on create a
/// folder's `default_permissioned_as` still applies to it — the run-as pickers start on "me",
/// and a rule made to give a folder's runnables a service identity must not lose to that.
pub fn names_only_caller(
on_behalf_of_email: Option<&str>,
on_behalf_of: Option<&str>,
authed: &impl db::Authable,
) -> bool {
let own = users::username_to_permissioned_as(authed.username());
on_behalf_of.map_or(true, |p| p == own)
&& on_behalf_of_email.map_or(true, |e| e == authed.email())
}
/// Resolves the identity to store when creating/updating a flow, script or app.
///
/// The permissioned_as is the identity: it decides what the job may access, and the address is
@@ -352,9 +366,9 @@ pub async fn resolve_on_behalf_of(
// account lookups below would refuse a caller that acts without a `usr` row. Through the
// same width check as every other branch: one too wide for a job row is no more enqueueable
// for naming themselves.
let names_self = on_behalf_of.map_or(true, |p| p == own)
&& on_behalf_of_email.map_or(true, |e| e == authed.email());
if names_self || !can_preserve_on_behalf_of(authed) {
if names_only_caller(on_behalf_of_email, on_behalf_of, authed)
|| !can_preserve_on_behalf_of(authed)
{
return reject_unenqueueable(own);
}
// Reserved superadmin sentinels are rejected by name, before resolution: the lookups
+4 -1
View File
@@ -2492,7 +2492,10 @@ async fn resolve_agent_on_behalf_of(
if obj.get("run_on_behalf_of").and_then(|v| v.as_bool()) != Some(true) {
return Ok(());
}
if created && requested.is_none() && windmill_common::can_preserve_on_behalf_of(authed) {
if created
&& windmill_common::names_only_caller(None, requested.as_deref(), authed)
&& windmill_common::can_preserve_on_behalf_of(authed)
{
if let Some((_, folder_default)) =
windmill_common::folders::resolve_folder_default_on_behalf_of(db, w_id, path).await?
{
+7 -4
View File
@@ -592,10 +592,13 @@ async fn create_trigger<T: TriggerCrud>(
let new_path = new_trigger.base.path.clone();
let labels = new_trigger.base.labels.clone();
// A trigger that names no identity takes the folder's default_permissioned_as rule, for a
// caller allowed to keep one (create-time only).
if new_trigger.base.permissioned_as.is_none()
&& windmill_common::can_preserve_on_behalf_of(&authed)
// A trigger that names nobody but its creator takes the folder's default_permissioned_as
// rule, for a caller allowed to keep one (create-time only; see `names_only_caller`).
if windmill_common::names_only_caller(
None,
new_trigger.base.permissioned_as.as_deref(),
&authed,
) && windmill_common::can_preserve_on_behalf_of(&authed)
{
if let Some(default) = windmill_common::folders::resolve_folder_default_permissioned_as(
&db,
@@ -102,9 +102,9 @@
let onBehalfOfChoice = $state<OnBehalfOfChoice>(undefined)
let customOnBehalfOf = $state<OnBehalfOfDetails | undefined>(undefined)
// 'me' is sent explicitly rather than left blank. Sending nothing means "no preference", which
// lets the target folder's `default_permissioned_as` claim the item — so the option labelled
// "me" would deploy it as somebody else. No choice at all (selector hidden) still defers to it.
// 'me' is sent explicitly rather than left blank: a script or flow deployed naming no identity
// runs without one. Naming only yourself still lets a matching folder `default_permissioned_as`
// rule claim a new item, as it does from every editor (backend `names_only_caller`).
const chosenIdentity = $derived(
onBehalfOfChoice === 'custom'
? customOnBehalfOf
@@ -8932,28 +8932,6 @@ async function flushDraftOrThrow(
}
}
/**
* A run-as identity on a schedule or trigger the chat creates is kept only when the draft also
* sets `preserve_permissioned_as`: the backend keeps any identity a write names, so one the
* model copied from an item it read would make the new item run as that item's identity.
*/
function withoutUnflaggedIdentity<T>(requestBody: T): T {
const body = requestBody as { permissioned_as?: string; preserve_permissioned_as?: boolean }
if (!body.permissioned_as || body.preserve_permissioned_as) return requestBody
const { permissioned_as: _dropped, ...rest } = body
return rest as T
}
/** `withoutUnflaggedIdentity` for an agent, which names its identity in its value. */
function withoutUnflaggedAgentIdentity<T>(requestBody: T): T {
const body = requestBody as { value?: unknown; preserve_on_behalf_of?: boolean }
const value = body.value as Record<string, unknown> | undefined
if (!value || typeof value !== 'object' || !('on_behalf_of' in value)) return requestBody
if (body.preserve_on_behalf_of) return requestBody
const { on_behalf_of: _dropped, ...rest } = value
return { ...body, value: rest } as T
}
async function deployDraft(
args: {
type: WorkspaceItemType
@@ -9050,10 +9028,7 @@ async function deployDraft(
if (await ScheduleService.existsSchedule({ workspace, path })) {
await ScheduleService.updateSchedule({ workspace, path, requestBody })
} else {
await ScheduleService.createSchedule({
workspace,
requestBody: withoutUnflaggedIdentity(requestBody)
})
await ScheduleService.createSchedule({ workspace, requestBody })
}
actions = [createOpenScheduleAction(path, requestBody.is_flow ? 'flow' : 'script')]
break
@@ -9064,7 +9039,7 @@ async function deployDraft(
if (await service.exists({ workspace, path })) {
await service.update({ workspace, path, requestBody })
} else {
await service.create({ workspace, requestBody: withoutUnflaggedIdentity(requestBody) })
await service.create({ workspace, requestBody })
}
actions = [
createOpenTriggerAction(triggerKind!, path, requestBody.is_flow ? 'flow' : 'script')
@@ -9076,10 +9051,7 @@ async function deployDraft(
if (await ResourceService.existsResource({ workspace, path })) {
await ResourceService.updateResource({ workspace, path, requestBody })
} else {
await ResourceService.createResource({
workspace,
requestBody: withoutUnflaggedAgentIdentity(requestBody)
})
await ResourceService.createResource({ workspace, requestBody })
}
actions = [createOpenResourceAction(path)]
break