From 8fac722b8edfce2ae29fc9a8723d8d0e4faf9ff5 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sun, 29 Nov 2026 12:43:49 +0000 Subject: [PATCH] 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 * fix: resolve a script path to its deployed version whoever asks Co-Authored-By: Claude Opus 5.5 * fix: keep deploy schedule updates to schedules that run the deployed path Co-Authored-By: Claude Opus 5.5 * fix: run only app script rows the deployed app version names Co-Authored-By: Claude Opus 5.5 * fix: read a preprocessed flow's tag from its own workspace Co-Authored-By: Claude Opus 5.5 * fix: keep a perpetual run on its version when a deploy drops its named identity Co-Authored-By: Claude Opus 5.5 * fix: re-push resumed suspended trigger jobs as the trigger's identity Co-Authored-By: Claude Opus 5.5 * fix: keep a schedule's or trigger's identity when the AI tools edit it Co-Authored-By: Claude Opus 5.5 * docs: state the authorization a script payload helper expects of its callers Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- ...52363a314b39a7aa0ee2beaeab549378e7c0.json} | 4 +- ...89648ca885dc87ff1b105a35ba23572598504.json | 23 ++++ ...e09c9c3d3ca760fab7244510824b5c762d07.json} | 4 +- ...ca5c21841ea4e86243a82461e3c9e359a316.json} | 10 +- backend/tests/app_preview_auth.rs | 8 +- backend/tests/app_run_mode_lock_strip.rs | 45 +++++-- backend/tests/perpetual_deploy_restart.rs | 43 +++++++ backend/windmill-api-flows/src/flows.rs | 2 +- backend/windmill-api-scripts/src/scripts.rs | 2 +- .../src/ai_session_tools/deploy.rs | 1 + .../src/ai_session_tools/items.rs | 20 +++ backend/windmill-api/src/apps.rs | 18 ++- backend/windmill-api/src/jobs.rs | 17 ++- backend/windmill-common/src/jobs.rs | 114 ++++++++++-------- backend/windmill-common/src/lib.rs | 66 +++++----- backend/windmill-queue/src/jobs.rs | 29 ++++- .../windmill-trigger/src/global_handler.rs | 26 +++- backend/windmill-worker/src/worker_utils.rs | 3 +- 18 files changed, 307 insertions(+), 128 deletions(-) rename backend/.sqlx/{query-b7335ac24702c86fbb4ab95916a6aa1648082287b09122755df2462dc71ce831.json => query-7af495acd76616fcb91b058b12e852363a314b39a7aa0ee2beaeab549378e7c0.json} (71%) create mode 100644 backend/.sqlx/query-9b35fc71fa5994aa7db3b190c7389648ca885dc87ff1b105a35ba23572598504.json rename backend/.sqlx/{query-eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814.json => query-a7bd504d6e509cde3e2ab12597f7e09c9c3d3ca760fab7244510824b5c762d07.json} (58%) rename backend/.sqlx/{query-aed606f8c8d91a924ac457b4eabdf391947d5fc3da90ef98a7b793c2430eb7bc.json => query-fd6afd1480c22e9911b50b2b74daca5c21841ea4e86243a82461e3c9e359a316.json} (78%) diff --git a/backend/.sqlx/query-b7335ac24702c86fbb4ab95916a6aa1648082287b09122755df2462dc71ce831.json b/backend/.sqlx/query-7af495acd76616fcb91b058b12e852363a314b39a7aa0ee2beaeab549378e7c0.json similarity index 71% rename from backend/.sqlx/query-b7335ac24702c86fbb4ab95916a6aa1648082287b09122755df2462dc71ce831.json rename to backend/.sqlx/query-7af495acd76616fcb91b058b12e852363a314b39a7aa0ee2beaeab549378e7c0.json index 7f90d5ac1f..e1b3a45b58 100644 --- a/backend/.sqlx/query-b7335ac24702c86fbb4ab95916a6aa1648082287b09122755df2462dc71ce831.json +++ b/backend/.sqlx/query-7af495acd76616fcb91b058b12e852363a314b39a7aa0ee2beaeab549378e7c0.json @@ -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" } diff --git a/backend/.sqlx/query-9b35fc71fa5994aa7db3b190c7389648ca885dc87ff1b105a35ba23572598504.json b/backend/.sqlx/query-9b35fc71fa5994aa7db3b190c7389648ca885dc87ff1b105a35ba23572598504.json new file mode 100644 index 0000000000..16ff07308d --- /dev/null +++ b/backend/.sqlx/query-9b35fc71fa5994aa7db3b190c7389648ca885dc87ff1b105a35ba23572598504.json @@ -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" +} diff --git a/backend/.sqlx/query-eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814.json b/backend/.sqlx/query-a7bd504d6e509cde3e2ab12597f7e09c9c3d3ca760fab7244510824b5c762d07.json similarity index 58% rename from backend/.sqlx/query-eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814.json rename to backend/.sqlx/query-a7bd504d6e509cde3e2ab12597f7e09c9c3d3ca760fab7244510824b5c762d07.json index b7cfa590d5..2836c7ff27 100644 --- a/backend/.sqlx/query-eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814.json +++ b/backend/.sqlx/query-a7bd504d6e509cde3e2ab12597f7e09c9c3d3ca760fab7244510824b5c762d07.json @@ -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" } diff --git a/backend/.sqlx/query-aed606f8c8d91a924ac457b4eabdf391947d5fc3da90ef98a7b793c2430eb7bc.json b/backend/.sqlx/query-fd6afd1480c22e9911b50b2b74daca5c21841ea4e86243a82461e3c9e359a316.json similarity index 78% rename from backend/.sqlx/query-aed606f8c8d91a924ac457b4eabdf391947d5fc3da90ef98a7b793c2430eb7bc.json rename to backend/.sqlx/query-fd6afd1480c22e9911b50b2b74daca5c21841ea4e86243a82461e3c9e359a316.json index 0bd5d0eca5..b00f6cb0a4 100644 --- a/backend/.sqlx/query-aed606f8c8d91a924ac457b4eabdf391947d5fc3da90ef98a7b793c2430eb7bc.json +++ b/backend/.sqlx/query-fd6afd1480c22e9911b50b2b74daca5c21841ea4e86243a82461e3c9e359a316.json @@ -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>>\", 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>>\", 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" } diff --git a/backend/tests/app_preview_auth.rs b/backend/tests/app_preview_auth.rs index 9f6e77f61c..3306e266f0 100644 --- a/backend/tests/app_preview_auth.rs +++ b/backend/tests/app_preview_auth.rs @@ -315,8 +315,8 @@ async fn test_app_preview_authorization(db: Pool) -> 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) -> 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:` / diff --git a/backend/tests/app_run_mode_lock_strip.rs b/backend/tests/app_run_mode_lock_strip.rs index 77265f2bcd..186227c836 100644 --- a/backend/tests/app_run_mode_lock_strip.rs +++ b/backend/tests/app_run_mode_lock_strip.rs @@ -278,18 +278,43 @@ async fn test_app_script_run_derives_path(db: Pool) -> 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!( diff --git a/backend/tests/perpetual_deploy_restart.rs b/backend/tests/perpetual_deploy_restart.rs index 6f9e82e5c6..1dc7fbb4f4 100644 --- a/backend/tests/perpetual_deploy_restart.rs +++ b/backend/tests/perpetual_deploy_restart.rs @@ -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, +) -> 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)> = 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, diff --git a/backend/windmill-api-flows/src/flows.rs b/backend/windmill-api-flows/src/flows.rs index 3699f2b37f..01cdfd155d 100644 --- a/backend/windmill-api-flows/src/flows.rs +++ b/backend/windmill-api-flows/src/flows.rs @@ -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) diff --git a/backend/windmill-api-scripts/src/scripts.rs b/backend/windmill-api-scripts/src/scripts.rs index 72a1e2837d..6e0cb1487a 100644 --- a/backend/windmill-api-scripts/src/scripts.rs +++ b/backend/windmill-api-scripts/src/scripts.rs @@ -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) diff --git a/backend/windmill-api/src/ai_session_tools/deploy.rs b/backend/windmill-api/src/ai_session_tools/deploy.rs index 1bd8090574..0cab057627 100644 --- a/backend/windmill-api/src/ai_session_tools/deploy.rs +++ b/backend/windmill-api/src/ai_session_tools/deploy.rs @@ -1152,6 +1152,7 @@ const TRIGGER_RUNTIME_KEYS: &[&str] = &[ "last_server_ping", "extra_perms", "permissioned_as", + "preserve_permissioned_as", "subscription_id", "push_auth_config", ]; diff --git a/backend/windmill-api/src/ai_session_tools/items.rs b/backend/windmill-api/src/ai_session_tools/items.rs index 7cd0c3831b..1ac49ee406 100644 --- a/backend/windmill-api/src/ai_session_tools/items.rs +++ b/backend/windmill-api/src/ai_session_tools/items.rs @@ -286,8 +286,15 @@ fn merge_config(base: Option, config: Value, path: &str) -> Map { + 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, ) diff --git a/backend/windmill-common/src/jobs.rs b/backend/windmill-common/src/jobs.rs index ecc2143c1c..1d6ace9ed5 100644 --- a/backend/windmill-common/src/jobs.rs +++ b/backend/windmill-common/src/jobs.rs @@ -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, + script_path: &str, + db: &DB, + w_id: &str, + skip_preprocessor: Option, +) -> error::Result<( + JobPayload, + Option, + Option, + Option, + Option, + Option, +)> { + 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<'_>, diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 84a509a5df..b462b9987d 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -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 } } diff --git a/backend/windmill-queue/src/jobs.rs b/backend/windmill-queue/src/jobs.rs index ba03f2b18f..f143dfe7dd 100644 --- a/backend/windmill-queue/src/jobs.rs +++ b/backend/windmill-queue/src/jobs.rs @@ -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>>\", \ - 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>>>, /// Its effective token scopes: the replacement never holds a wider token. job_token_scopes: Option>, + /// The identity its own version runs as, if that version names one. + version_on_behalf_of: Option, } /// 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 diff --git a/backend/windmill-trigger/src/global_handler.rs b/backend/windmill-trigger/src/global_handler.rs index cae38d935d..056a65966a 100644 --- a/backend/windmill-trigger/src/global_handler.rs +++ b/backend/windmill-trigger/src/global_handler.rs @@ -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 = 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( diff --git a/backend/windmill-worker/src/worker_utils.rs b/backend/windmill-worker/src/worker_utils.rs index acfd6992d8..2f96e0054b 100644 --- a/backend/windmill-worker/src/worker_utils.rs +++ b/backend/windmill-worker/src/worker_utils.rs @@ -498,12 +498,13 @@ pub async fn get_tag_and_concurrency(job_id: &Uuid, db: &DB) -> Option>'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 )