mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-30 00:07:30 +00:00
fix: resolve runnables and run-as identities consistently across tasks, deploys and triggers (#12744)
* fix: run workflow tasks at the version their parent job runs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: resolve a script path to its deployed version whoever asks Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep deploy schedule updates to schedules that run the deployed path Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: run only app script rows the deployed app version names Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: read a preprocessed flow's tag from its own workspace Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep a perpetual run on its version when a deploy drops its named identity Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: re-push resumed suspended trigger jobs as the trigger's identity Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep a schedule's or trigger's identity when the AI tools edit it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: state the authorization a script payload helper expects of its callers Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
3ee0d889ef
commit
8fac722b8e
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n WITH j AS (\n SELECT \n raw_flow->>'concurrency_key' as concurrency_key, \n raw_flow->>'concurrency_time_window_s' as concurrency_time_window_s,\n raw_flow->>'concurrency_limit' as concurrent_limit,\n runnable_path, \n runnable_id as version FROM v2_job\n WHERE id = $1\n )\n SELECT tag, j.concurrency_key, j.concurrency_time_window_s::int, j.concurrent_limit::int, j.version\n FROM flow, j\n WHERE path = j.runnable_path\n ",
|
||||
"query": "\n WITH j AS (\n SELECT \n raw_flow->>'concurrency_key' as concurrency_key, \n raw_flow->>'concurrency_time_window_s' as concurrency_time_window_s,\n raw_flow->>'concurrency_limit' as concurrent_limit,\n runnable_path, \n workspace_id,\n runnable_id as version FROM v2_job\n WHERE id = $1\n )\n SELECT tag, j.concurrency_key, j.concurrency_time_window_s::int, j.concurrent_limit::int, j.version\n FROM flow, j\n WHERE path = j.runnable_path AND flow.workspace_id = j.workspace_id\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -42,5 +42,5 @@
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "b7335ac24702c86fbb4ab95916a6aa1648082287b09122755df2462dc71ce831"
|
||||
"hash": "7af495acd76616fcb91b058b12e852363a314b39a7aa0ee2beaeab549378e7c0"
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT EXISTS(SELECT 1 FROM script WHERE hash = $1 AND workspace_id = $2)",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "exists",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Int8",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "9b35fc71fa5994aa7db3b190c7389648ca885dc87ff1b105a35ba23572598504"
|
||||
}
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT l.id IS NOT NULL as \"has_lite!\",\n CASE WHEN $3::bigint IS NULL THEN NOT EXISTS (\n SELECT 1 FROM app_script s\n WHERE s.app = a.id AND s.code_sha256 = $4::text\n AND jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)',\n jsonb_build_object('id', s.id)))\n ELSE coalesce(jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)',\n jsonb_build_object('id', $3::bigint)), false)\n END as \"may_run!\"\n FROM app a\n LEFT JOIN app_version_lite l ON l.id = a.versions[array_upper(a.versions, 1)]\n WHERE a.path = $1 AND a.workspace_id = $2",
|
||||
"query": "SELECT l.id IS NOT NULL as \"has_lite!\",\n CASE WHEN $3::bigint IS NULL THEN NOT EXISTS (\n SELECT 1 FROM app_script s\n WHERE s.app = a.id AND s.code_sha256 = $4::text\n AND jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)',\n jsonb_build_object('id', s.id)))\n ELSE coalesce(jsonb_path_exists(coalesce(l.value, v.value::jsonb),\n '$.**.inlineScript.id ? (@ == $id)',\n jsonb_build_object('id', $3::bigint)), false)\n END as \"may_run!\"\n FROM app a\n LEFT JOIN app_version_lite l ON l.id = a.versions[array_upper(a.versions, 1)]\n LEFT JOIN app_version v ON v.id = a.versions[array_upper(a.versions, 1)]\n WHERE a.path = $1 AND a.workspace_id = $2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -27,5 +27,5 @@
|
||||
null
|
||||
]
|
||||
},
|
||||
"hash": "eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814"
|
||||
"hash": "a7bd504d6e509cde3e2ab12597f7e09c9c3d3ca760fab7244510824b5c762d07"
|
||||
}
|
||||
+8
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT q.id AS \"id!\", j.created_by, j.permissioned_as, j.permissioned_as_email, j.trigger, j.trigger_kind AS \"trigger_kind: TriggerKindLabel\", j.preprocessed, j.args AS \"args: sqlx::types::Json<HashMap<String, Box<RawValue>>>\", p.job_token_scopes AS \"job_token_scopes?\" FROM v2_job_queue q JOIN v2_job j USING (id) JOIN script s ON s.workspace_id = j.workspace_id AND s.hash = j.runnable_id LEFT JOIN job_perms p ON p.job_id = q.id WHERE j.workspace_id = $1 AND j.runnable_path = $2 AND j.kind = 'script' AND j.flow_step_id IS NULL AND j.runnable_id != $3 AND q.canceled_by IS NULL AND s.restart_unless_cancelled",
|
||||
"query": "SELECT q.id AS \"id!\", j.created_by, j.permissioned_as, j.permissioned_as_email, j.trigger, j.trigger_kind AS \"trigger_kind: TriggerKindLabel\", j.preprocessed, j.args AS \"args: sqlx::types::Json<HashMap<String, Box<RawValue>>>\", p.job_token_scopes AS \"job_token_scopes?\", s.on_behalf_of AS version_on_behalf_of FROM v2_job_queue q JOIN v2_job j USING (id) JOIN script s ON s.workspace_id = j.workspace_id AND s.hash = j.runnable_id LEFT JOIN job_perms p ON p.job_id = q.id WHERE j.workspace_id = $1 AND j.runnable_path = $2 AND j.kind = 'script' AND j.flow_step_id IS NULL AND j.runnable_id != $3 AND q.canceled_by IS NULL AND s.restart_unless_cancelled",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -76,6 +76,11 @@
|
||||
"ordinal": 8,
|
||||
"name": "job_token_scopes?",
|
||||
"type_info": "TextArray"
|
||||
},
|
||||
{
|
||||
"ordinal": 9,
|
||||
"name": "version_on_behalf_of",
|
||||
"type_info": "Varchar"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
@@ -94,8 +99,9 @@
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "aed606f8c8d91a924ac457b4eabdf391947d5fc3da90ef98a7b793c2430eb7bc"
|
||||
"hash": "fd6afd1480c22e9911b50b2b74daca5c21841ea4e86243a82461e3c9e359a316"
|
||||
}
|
||||
@@ -315,8 +315,8 @@ async fn test_app_preview_authorization(db: Pool<Postgres>) -> anyhow::Result<()
|
||||
// 11. `raw_code` carrying an `app_script` `id` from another app must not run
|
||||
// against this Viewer app: the row carries its own modules and lock, which
|
||||
// would run under `vapp`'s identity. Here `999777` belongs to
|
||||
// `u/test-user/private`, not to the targeted `vapp`, so the id lookup
|
||||
// (scoped to the app) refuses it before any Viewer default applies.
|
||||
// `u/test-user/private`, not to the targeted `vapp`, whose deployed version
|
||||
// names no such row, so it is refused before any Viewer default applies.
|
||||
let resp = authed(
|
||||
client().post(format!("{base}/u/test-user/vapp")),
|
||||
"OPERATOR_TOKEN",
|
||||
@@ -340,8 +340,8 @@ async fn test_app_preview_authorization(db: Pool<Postgres>) -> anyhow::Result<()
|
||||
"run-mode raw_code with another app's app_script id must be rejected against a Viewer app (got {status}): {body}"
|
||||
);
|
||||
assert!(
|
||||
body.contains("does not belong to app u/test-user/vapp"),
|
||||
"rejection must be the app scoping of the app_script id, got: {body}"
|
||||
body.contains("not part of the deployed version of app u/test-user/vapp"),
|
||||
"rejection must be the deployed version check of the app_script id, got: {body}"
|
||||
);
|
||||
|
||||
// 12. Path confinement: the scope picker mints `apps:run:<path>` /
|
||||
|
||||
@@ -278,18 +278,43 @@ async fn test_app_script_run_derives_path(db: Pool<Postgres>) -> anyhow::Result<
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
|
||||
let resp = authed(
|
||||
client().post(format!("{ws}/apps_u/execute_component/{app_path}")),
|
||||
"SECRET_TOKEN_2",
|
||||
let run = || {
|
||||
authed(
|
||||
client().post(format!("{ws}/apps_u/execute_component/{app_path}")),
|
||||
"SECRET_TOKEN_2",
|
||||
)
|
||||
.json(&json!({
|
||||
"args": {},
|
||||
"component": "comp",
|
||||
"id": script_id,
|
||||
"raw_code": { "language": "python3", "content": "", "path": CALLER_PATH }
|
||||
}))
|
||||
.send()
|
||||
};
|
||||
|
||||
// Before its lite value exists, the deployed version's full value says which rows it runs.
|
||||
let resp = run().await?;
|
||||
let status = resp.status();
|
||||
assert_eq!(
|
||||
status,
|
||||
401,
|
||||
"a row the deployed version does not name must not run: {}",
|
||||
resp.text().await?
|
||||
);
|
||||
sqlx::query(
|
||||
"UPDATE app_version SET value = $2::jsonb::json
|
||||
WHERE id = (SELECT versions[array_upper(versions, 1)] FROM app WHERE path = $1)",
|
||||
)
|
||||
.json(&json!({
|
||||
"args": {},
|
||||
"component": "comp",
|
||||
"id": script_id,
|
||||
"raw_code": { "language": "python3", "content": "", "path": CALLER_PATH }
|
||||
}))
|
||||
.send()
|
||||
.bind(app_path)
|
||||
.bind(
|
||||
json!({ "grid": [{ "data": { "componentInput": { "runnable": {
|
||||
"inlineScript": { "id": script_id, "language": "python3" }
|
||||
} } } }] }),
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
|
||||
let resp = run().await?;
|
||||
let status = resp.status();
|
||||
let body = resp.text().await?;
|
||||
assert_eq!(
|
||||
|
||||
@@ -202,6 +202,49 @@ async fn a_replacement_runs_as_the_identity_the_deployed_version_names(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The identity an earlier version names stays with that version's code: a version deployed by
|
||||
/// someone else without one does not take it over.
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn a_run_keeps_its_version_when_the_deployed_one_drops_its_identity(
|
||||
db: Pool<Postgres>,
|
||||
) -> anyhow::Result<()> {
|
||||
let path = "u/test-user/named-identity";
|
||||
insert_version(&db, path, 801, 60.0, true).await?;
|
||||
sqlx::query(
|
||||
"UPDATE script SET on_behalf_of = 'u/test-user' WHERE hash = 801 AND workspace_id = $1",
|
||||
)
|
||||
.bind(W_ID)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
let running = start_run(&db, path, 801).await?;
|
||||
insert_version(&db, path, 802, 0.0, true).await?;
|
||||
|
||||
restart_perpetual_runs_on_new_version(&db, W_ID, path, "test-user-2").await;
|
||||
|
||||
let queued: Vec<(Uuid, Option<String>)> = sqlx::query_as(
|
||||
"SELECT q.id, q.canceled_reason FROM v2_job_queue q JOIN v2_job j USING (id) \
|
||||
WHERE j.workspace_id = $1 AND j.runnable_path = $2",
|
||||
)
|
||||
.bind(W_ID)
|
||||
.bind(path)
|
||||
.fetch_all(&db)
|
||||
.await?;
|
||||
assert_eq!(queued, vec![(running, None)]);
|
||||
|
||||
restart_perpetual_runs_on_new_version(&db, W_ID, path, "test-user").await;
|
||||
|
||||
let hash: i64 = sqlx::query_scalar(
|
||||
"SELECT j.runnable_id FROM v2_job j JOIN v2_job_queue q USING (id) \
|
||||
WHERE j.workspace_id = $1 AND j.runnable_path = $2 AND q.canceled_by IS NULL",
|
||||
)
|
||||
.bind(W_ID)
|
||||
.bind(path)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
assert_eq!(hash, 802, "a deploy by that identity itself moves the run");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn a_run_stays_on_its_version_when_it_may_not_use_the_deployed_tag(
|
||||
db: Pool<Postgres>,
|
||||
|
||||
@@ -1561,7 +1561,7 @@ async fn update_flow(
|
||||
.await.map_err(|e| error::Error::internal_err(format!("Error updating flow due to related schedules update: {e:#}")))?;
|
||||
|
||||
let schedule = sqlx::query_as::<_, Schedule>(
|
||||
"UPDATE schedule SET path = $1, script_path = $1 WHERE path = $2 AND workspace_id = $3 AND is_flow IS true RETURNING *")
|
||||
"UPDATE schedule SET path = $1, script_path = $1 WHERE path = $2 AND script_path = $2 AND workspace_id = $3 AND is_flow IS true RETURNING *")
|
||||
.bind(&nf.path)
|
||||
.bind(&flow_path)
|
||||
.bind(&w_id)
|
||||
|
||||
@@ -2674,7 +2674,7 @@ async fn create_script_internal<'c>(
|
||||
.await?;
|
||||
|
||||
let schedule = sqlx::query_as::<_, Schedule>(
|
||||
"UPDATE schedule SET path = $1, script_path = $1 WHERE path = $2 AND workspace_id = $3 AND is_flow IS false RETURNING *")
|
||||
"UPDATE schedule SET path = $1, script_path = $1 WHERE path = $2 AND script_path = $2 AND workspace_id = $3 AND is_flow IS false RETURNING *")
|
||||
.bind(&ns.path)
|
||||
.bind(&p_path)
|
||||
.bind(&w_id)
|
||||
|
||||
@@ -1152,6 +1152,7 @@ const TRIGGER_RUNTIME_KEYS: &[&str] = &[
|
||||
"last_server_ping",
|
||||
"extra_perms",
|
||||
"permissioned_as",
|
||||
"preserve_permissioned_as",
|
||||
"subscription_id",
|
||||
"push_auth_config",
|
||||
];
|
||||
|
||||
@@ -286,8 +286,15 @@ fn merge_config(base: Option<Value>, config: Value, path: &str) -> Map<String, V
|
||||
for key in ["workspace_id", "edited_by", "edited_at", "email", "error"] {
|
||||
draft.shift_remove(key);
|
||||
}
|
||||
let base_identity = non_null(draft.get("permissioned_as")).cloned();
|
||||
draft.extend(into_object(Some(config)));
|
||||
draft.insert("path".into(), json!(path));
|
||||
// As the editors do: without the flag a deploy resets the identity to the deploying user.
|
||||
if base_identity.is_some() && draft.get("permissioned_as") == base_identity.as_ref() {
|
||||
draft
|
||||
.entry("preserve_permissioned_as")
|
||||
.or_insert(json!(true));
|
||||
}
|
||||
draft
|
||||
}
|
||||
|
||||
@@ -653,6 +660,19 @@ mod tests {
|
||||
(parsed, issues)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_keeps_the_identity_the_item_runs_as() {
|
||||
let base = || Some(json!({"path": "p", "permissioned_as": "u/dev", "summary": "a"}));
|
||||
let draft = merge_config(base(), json!({"summary": "b"}), "p");
|
||||
assert_eq!(draft["preserve_permissioned_as"], json!(true));
|
||||
|
||||
let draft = merge_config(base(), json!({"permissioned_as": "u/other"}), "p");
|
||||
assert_eq!(draft.get("preserve_permissioned_as"), None);
|
||||
|
||||
let draft = merge_config(None, json!({"summary": "b"}), "p");
|
||||
assert_eq!(draft.get("preserve_permissioned_as"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trigger_config_parses_like_the_session() {
|
||||
let kafka: Value = serde_json::from_str(&SCHEMAS.trigger["kafka"]).unwrap();
|
||||
|
||||
@@ -4822,8 +4822,9 @@ async fn execute_component(
|
||||
|
||||
// The policy key covers only an inline script's own code, not the lock and modules
|
||||
// its `app_script` row runs with, so it cannot tell the deployed row from an older
|
||||
// one (or from id-less code, which runs with neither). Once the deployed version has
|
||||
// its lite value, a deployed row's code runs only through that row, and id-less code
|
||||
// one (or from id-less code, which runs with neither). A row runs only if the deployed
|
||||
// version names it, in its lite value or, until that exists, its full value. Once the
|
||||
// lite value exists, a deployed row's code runs only through that row, and id-less code
|
||||
// only as the database studio's runtime-built queries, which have no row. Those are
|
||||
// limited to the languages it emits: the pin covers content, not language, and the
|
||||
// policy also pins frontend scripts, which must never run as e.g. bash.
|
||||
@@ -4848,11 +4849,13 @@ async fn execute_component(
|
||||
WHERE s.app = a.id AND s.code_sha256 = $4::text
|
||||
AND jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)',
|
||||
jsonb_build_object('id', s.id)))
|
||||
ELSE coalesce(jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)',
|
||||
ELSE coalesce(jsonb_path_exists(coalesce(l.value, v.value::jsonb),
|
||||
'$.**.inlineScript.id ? (@ == $id)',
|
||||
jsonb_build_object('id', $3::bigint)), false)
|
||||
END as \"may_run!\"
|
||||
FROM app a
|
||||
LEFT JOIN app_version_lite l ON l.id = a.versions[array_upper(a.versions, 1)]
|
||||
LEFT JOIN app_version v ON v.id = a.versions[array_upper(a.versions, 1)]
|
||||
WHERE a.path = $1 AND a.workspace_id = $2",
|
||||
path,
|
||||
&w_id,
|
||||
@@ -4862,7 +4865,14 @@ async fn execute_component(
|
||||
.fetch_optional(&db)
|
||||
.await?;
|
||||
let may_run = payload.id.is_some() || id_less_sql;
|
||||
if deployed.is_some_and(|d| d.has_lite && !(may_run && d.may_run)) {
|
||||
let refused = deployed.is_some_and(|d| {
|
||||
if d.has_lite {
|
||||
!(may_run && d.may_run)
|
||||
} else {
|
||||
payload.id.is_some() && !d.may_run
|
||||
}
|
||||
});
|
||||
if refused {
|
||||
return Err(Error::NotAuthorized(format!(
|
||||
"This runnable is not part of the deployed version of app {path}, reload the app"
|
||||
)));
|
||||
|
||||
@@ -8714,15 +8714,20 @@ pub async fn run_workflow_as_code(
|
||||
run_query.timeout,
|
||||
None,
|
||||
),
|
||||
// The version the parent runs, not the path's latest: the parent's identity was
|
||||
// granted to that version's code.
|
||||
JobKind::Script => {
|
||||
let hash = job.script_hash.ok_or_else(|| {
|
||||
error::Error::BadRequest(format!("job {job_id} runs no script version"))
|
||||
})?;
|
||||
let userdb_authed =
|
||||
UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() };
|
||||
let script = RunnableRef::from_path(job.script_path(), false)?;
|
||||
script_path_to_payload(
|
||||
&script,
|
||||
RunOrigin::Deployed,
|
||||
Some(userdb_authed),
|
||||
db.clone(),
|
||||
let script_info =
|
||||
get_script_info_for_hash(Some(userdb_authed), &db, &w_id, hash.0).await?;
|
||||
windmill_common::jobs::script_info_to_payload(
|
||||
script_info,
|
||||
job.script_path(),
|
||||
&db,
|
||||
&w_id,
|
||||
run_query.skip_preprocessor,
|
||||
)
|
||||
|
||||
@@ -240,55 +240,8 @@ pub async fn script_path_to_payload<'e>(
|
||||
)
|
||||
} else {
|
||||
let script_info =
|
||||
get_latest_deployed_hash_for_path(db_authed, db.clone(), w_id, script_path)
|
||||
.await?
|
||||
.prefetch_cached(&db)
|
||||
.await?;
|
||||
let on_behalf_of = script_info.on_behalf_of(w_id, &db).await?;
|
||||
let ScriptHashInfo {
|
||||
hash,
|
||||
tag,
|
||||
runnable_settings:
|
||||
super::scripts::ScriptRunnableSettingsInline {
|
||||
concurrency_settings,
|
||||
debouncing_settings,
|
||||
},
|
||||
cache_ttl,
|
||||
cache_ignore_s3_path,
|
||||
language,
|
||||
dedicated_worker,
|
||||
priority,
|
||||
delete_after_use,
|
||||
delete_after_secs,
|
||||
timeout,
|
||||
has_preprocessor,
|
||||
labels,
|
||||
job_token_scopes,
|
||||
..
|
||||
} = script_info;
|
||||
|
||||
(
|
||||
JobPayload::ScriptHash {
|
||||
hash: ScriptHash(hash),
|
||||
path: script_path.to_owned(),
|
||||
cache_ttl,
|
||||
cache_ignore_s3_path,
|
||||
language,
|
||||
dedicated_worker,
|
||||
priority,
|
||||
apply_preprocessor: !skip_preprocessor.unwrap_or(false)
|
||||
&& has_preprocessor.unwrap_or(false),
|
||||
debouncing_settings,
|
||||
concurrency_settings,
|
||||
labels,
|
||||
job_token_scopes,
|
||||
},
|
||||
tag,
|
||||
delete_after_use,
|
||||
delete_after_secs,
|
||||
timeout,
|
||||
on_behalf_of,
|
||||
)
|
||||
get_latest_deployed_hash_for_path(db_authed, db.clone(), w_id, script_path).await?;
|
||||
script_info_to_payload(script_info, script_path, &db, w_id, skip_preprocessor).await?
|
||||
};
|
||||
Ok((
|
||||
job_payload,
|
||||
@@ -300,6 +253,69 @@ pub async fn script_path_to_payload<'e>(
|
||||
))
|
||||
}
|
||||
|
||||
/// The payload, tag, retention, timeout and identity a run of one script version gets.
|
||||
///
|
||||
/// Reads through `db` and authorizes nothing: callers must already have authorized the caller
|
||||
/// for `w_id` and for the version `script_info` was read from, as the run routes do.
|
||||
pub async fn script_info_to_payload(
|
||||
script_info: ScriptHashInfo<super::scripts::ScriptRunnableSettingsHandle>,
|
||||
script_path: &str,
|
||||
db: &DB,
|
||||
w_id: &str,
|
||||
skip_preprocessor: Option<bool>,
|
||||
) -> error::Result<(
|
||||
JobPayload,
|
||||
Option<Tag>,
|
||||
Option<bool>,
|
||||
Option<i32>,
|
||||
Option<i32>,
|
||||
Option<OnBehalfOf>,
|
||||
)> {
|
||||
let script_info = script_info.prefetch_cached(db).await?;
|
||||
let on_behalf_of = script_info.on_behalf_of(w_id, db).await?;
|
||||
let ScriptHashInfo {
|
||||
hash,
|
||||
tag,
|
||||
runnable_settings:
|
||||
super::scripts::ScriptRunnableSettingsInline { concurrency_settings, debouncing_settings },
|
||||
cache_ttl,
|
||||
cache_ignore_s3_path,
|
||||
language,
|
||||
dedicated_worker,
|
||||
priority,
|
||||
delete_after_use,
|
||||
delete_after_secs,
|
||||
timeout,
|
||||
has_preprocessor,
|
||||
labels,
|
||||
job_token_scopes,
|
||||
..
|
||||
} = script_info;
|
||||
|
||||
Ok((
|
||||
JobPayload::ScriptHash {
|
||||
hash: ScriptHash(hash),
|
||||
path: script_path.to_owned(),
|
||||
cache_ttl,
|
||||
cache_ignore_s3_path,
|
||||
language,
|
||||
dedicated_worker,
|
||||
priority,
|
||||
apply_preprocessor: !skip_preprocessor.unwrap_or(false)
|
||||
&& has_preprocessor.unwrap_or(false),
|
||||
debouncing_settings,
|
||||
concurrency_settings,
|
||||
labels,
|
||||
job_token_scopes,
|
||||
},
|
||||
tag,
|
||||
delete_after_use,
|
||||
delete_after_secs,
|
||||
timeout,
|
||||
on_behalf_of,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn runnable_ref_to_payload(
|
||||
runnable: &RunnableRef,
|
||||
origin: RunOrigin<'_>,
|
||||
|
||||
@@ -2736,57 +2736,25 @@ pub fn get_latest_deployed_hash_for_path<'e>(
|
||||
async move {
|
||||
let cache_key = (w_id.to_string(), script_path.to_string());
|
||||
let use_cache = !DEPLOYED_SCRIPT_CACHE_DISABLED.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let mut computed_hash = None;
|
||||
// Resolved without the caller's RLS: the cache serves every caller, with an identity or
|
||||
// none, so it must hold the path's deployed version, not the newest one a caller sees.
|
||||
let hash = match DEPLOYED_SCRIPT_HASH_CACHE
|
||||
.get(&cache_key)
|
||||
.filter(|_| use_cache)
|
||||
.filter(|cached| use_cache && cached.expires_at > std::time::Instant::now())
|
||||
{
|
||||
Some(cached_hash)
|
||||
if cached_hash.expires_at > std::time::Instant::now()
|
||||
&& db.as_ref().is_none_or(|x| {
|
||||
let r = HASH_PERMS_CACHE
|
||||
.check_perms_in_cache(x.authed, ScriptHash(cached_hash.id));
|
||||
computed_hash = Some(r.1);
|
||||
return r.0;
|
||||
}) =>
|
||||
{
|
||||
Some(cached_hash) => {
|
||||
tracing::debug!(
|
||||
"Using cached script hash {} for {script_path}",
|
||||
cached_hash.id
|
||||
);
|
||||
cached_hash.id
|
||||
}
|
||||
_ => {
|
||||
None => {
|
||||
tracing::debug!("Fetching script hash for {script_path}");
|
||||
let latest = if let Some(db) = db {
|
||||
let authed = db.authed;
|
||||
let mut conn = db.acquire().await?;
|
||||
let latest =
|
||||
get_latest_deployed_script_hash(&mut *conn, script_path, w_id).await?;
|
||||
if let Some(hash) = latest.hash {
|
||||
HASH_PERMS_CACHE.insert(
|
||||
computed_hash.unwrap_or_else(|| PermsCache::compute_hash(authed)),
|
||||
ScriptHash(hash),
|
||||
);
|
||||
} else {
|
||||
// Release the user-db connection first: holding it while taking a
|
||||
// second one from the same pool starves the pool under a burst of
|
||||
// requests for paths the caller cannot see.
|
||||
drop(conn);
|
||||
let mut conn = db2.acquire().await?;
|
||||
let exists = get_latest_script_hash(&mut *conn, script_path, w_id)
|
||||
.await?
|
||||
.is_some();
|
||||
if exists {
|
||||
return Err(Error::NotAuthorized(format!("You are not authorized to access this script: {script_path} (but it exists). Your permissions are: {:?}", authed)));
|
||||
}
|
||||
}
|
||||
latest
|
||||
} else {
|
||||
let latest = {
|
||||
let mut conn = db2.acquire().await?;
|
||||
get_latest_deployed_script_hash(&mut *conn, script_path, w_id).await?
|
||||
};
|
||||
|
||||
let hash = utils::not_found_if_none(latest.hash, "script", script_path)?;
|
||||
if use_cache {
|
||||
let ttl = if latest.pending_lock {
|
||||
@@ -2802,11 +2770,31 @@ pub fn get_latest_deployed_hash_for_path<'e>(
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
hash
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(db) = db {
|
||||
let authed = db.authed;
|
||||
let (cached, authed_hash) =
|
||||
HASH_PERMS_CACHE.check_perms_in_cache(authed, ScriptHash(hash));
|
||||
if !cached {
|
||||
let mut conn = db.acquire().await?;
|
||||
let visible = sqlx::query_scalar!(
|
||||
"SELECT EXISTS(SELECT 1 FROM script WHERE hash = $1 AND workspace_id = $2)",
|
||||
hash,
|
||||
w_id
|
||||
)
|
||||
.fetch_one(&mut *conn)
|
||||
.await?
|
||||
.unwrap_or(false);
|
||||
if !visible {
|
||||
return Err(Error::NotAuthorized(format!("You are not authorized to access this script: {script_path} (but it exists). Your permissions are: {:?}", authed)));
|
||||
}
|
||||
HASH_PERMS_CACHE.insert(authed_hash, ScriptHash(hash));
|
||||
}
|
||||
}
|
||||
|
||||
get_script_info_for_hash(None, &db2, w_id, hash).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -771,7 +771,8 @@ where
|
||||
/// Carries the authority of the deploy, which every caller has authorized: it cancels and pushes
|
||||
/// runs at `script_path` without an `Authed` of its own. A replacement runs as the deployed
|
||||
/// version's identity when it names one and otherwise as the identity of the run it replaces, and
|
||||
/// a run only moves to a tag that identity may use.
|
||||
/// a run only moves to a tag that identity may use. A run that has its identity from its own
|
||||
/// version's `on_behalf_of` only moves when the deploy names one too or comes from that identity.
|
||||
///
|
||||
/// Errors are logged, never returned: a deploy stands whatever happens to the runs of its earlier
|
||||
/// versions.
|
||||
@@ -856,7 +857,7 @@ async fn restart_perpetual_runs_at_path(
|
||||
"SELECT q.id AS \"id!\", j.created_by, j.permissioned_as, j.permissioned_as_email, \
|
||||
j.trigger, j.trigger_kind AS \"trigger_kind: TriggerKindLabel\", j.preprocessed, \
|
||||
j.args AS \"args: sqlx::types::Json<HashMap<String, Box<RawValue>>>\", \
|
||||
p.job_token_scopes AS \"job_token_scopes?\" \
|
||||
p.job_token_scopes AS \"job_token_scopes?\", s.on_behalf_of AS version_on_behalf_of \
|
||||
FROM v2_job_queue q JOIN v2_job j USING (id) \
|
||||
JOIN script s ON s.workspace_id = j.workspace_id AND s.hash = j.runnable_id \
|
||||
LEFT JOIN job_perms p ON p.job_id = q.id \
|
||||
@@ -925,6 +926,8 @@ struct PerpetualRunToRestart {
|
||||
args: Option<sqlx::types::Json<HashMap<String, Box<RawValue>>>>,
|
||||
/// Its effective token scopes: the replacement never holds a wider token.
|
||||
job_token_scopes: Option<Vec<String>>,
|
||||
/// The identity its own version runs as, if that version names one.
|
||||
version_on_behalf_of: Option<String>,
|
||||
}
|
||||
|
||||
/// What every run at the path moves to.
|
||||
@@ -947,10 +950,24 @@ async fn restart_perpetual_run(
|
||||
let RestartOnVersion { payload, tag, timeout, dedicated_worker, on_behalf_of } = version;
|
||||
let (email, permissioned_as) = match on_behalf_of {
|
||||
Some(obo) => (obo.email.clone(), obo.permissioned_as.clone()),
|
||||
None => (
|
||||
run.permissioned_as_email.clone(),
|
||||
run.permissioned_as.clone(),
|
||||
),
|
||||
None => {
|
||||
// That identity belongs to the code of the run's own version: another deployer's
|
||||
// code must not inherit it.
|
||||
if run.version_on_behalf_of.as_deref().is_some_and(|obo| {
|
||||
obo != windmill_common::users::username_to_permissioned_as(deployed_by)
|
||||
}) {
|
||||
tracing::warn!(
|
||||
"Perpetual run {} stays on its version: it runs as its version's \
|
||||
on_behalf_of and the deployed version of {script_path} names none",
|
||||
run.id
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
(
|
||||
run.permissioned_as_email.clone(),
|
||||
run.permissioned_as.clone(),
|
||||
)
|
||||
}
|
||||
};
|
||||
let args = run.args.clone().map(|args| args.0).unwrap_or_default();
|
||||
// The run's own tag was checked when the loop started; the deployed version's has not
|
||||
|
||||
@@ -173,6 +173,9 @@ pub async fn resume_suspended_trigger_jobs(
|
||||
|
||||
let l = jobs.len();
|
||||
let mut unsuspended_in_place = 0;
|
||||
// A re-pushed job runs as the trigger does, as it would have had it not been parked, not as
|
||||
// whoever resumes it.
|
||||
let mut trigger_authed: Option<ApiAuthed> = None;
|
||||
|
||||
for job in jobs {
|
||||
// If job was created after trigger was edited, simply update it to unsuspend
|
||||
@@ -214,12 +217,33 @@ pub async fn resume_suspended_trigger_jobs(
|
||||
} else {
|
||||
// Job was created before trigger edit - delete and repush with new configuration
|
||||
// Pass the transaction to trigger_runnable_inner so everything is in the same transaction
|
||||
let run_as = match &trigger_authed {
|
||||
Some(a) => a.clone(),
|
||||
None => {
|
||||
let email = windmill_common::users::get_email_from_permissioned_as(
|
||||
&trigger.permissioned_as,
|
||||
&w_id,
|
||||
&db,
|
||||
)
|
||||
.await?;
|
||||
let a = windmill_api_auth::fetch_api_authed_from_permissioned_as(
|
||||
trigger.permissioned_as.clone(),
|
||||
email,
|
||||
&w_id,
|
||||
&db,
|
||||
Some(format!("{}-{}", trigger_kind, trigger_path)),
|
||||
)
|
||||
.await?;
|
||||
trigger_authed = Some(a.clone());
|
||||
a
|
||||
}
|
||||
};
|
||||
let (_uuid, _delete_after_use, _early_return, _has_failure_module, tx_o) =
|
||||
trigger_runnable_inner(
|
||||
&db,
|
||||
Some(tx),
|
||||
Some(user_db.clone()),
|
||||
authed.clone(),
|
||||
run_as,
|
||||
ChosenBy::Deployed,
|
||||
&w_id,
|
||||
&windmill_common::runnable_ref::RunnableRef::from_path(
|
||||
|
||||
@@ -498,12 +498,13 @@ pub async fn get_tag_and_concurrency(job_id: &Uuid, db: &DB) -> Option<TagAndCon
|
||||
raw_flow->>'concurrency_time_window_s' as concurrency_time_window_s,
|
||||
raw_flow->>'concurrency_limit' as concurrent_limit,
|
||||
runnable_path,
|
||||
workspace_id,
|
||||
runnable_id as version FROM v2_job
|
||||
WHERE id = $1
|
||||
)
|
||||
SELECT tag, j.concurrency_key, j.concurrency_time_window_s::int, j.concurrent_limit::int, j.version
|
||||
FROM flow, j
|
||||
WHERE path = j.runnable_path
|
||||
WHERE path = j.runnable_path AND flow.workspace_id = j.workspace_id
|
||||
",
|
||||
job_id
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user