From 09202d40948d59fc3e519a103c55ce8a7b04669b Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sun, 29 Nov 2026 13:06:26 +0000 Subject: [PATCH] fix: consistent writes for linked resource/variable pairs and instance database resolution (#12746) * fix: serialize resource writes on a path and require write access to both halves of a linked pair Co-Authored-By: Claude Opus 5.5 * fix: resolve the instance database resource only on routes that name it, within token scopes Co-Authored-By: Claude Opus 5.5 * fix: keep the resource-then-variable lock order in variable rename Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- ...4c7377ed7c40b81182f0b0ea95381b0f7b2e.json} | 4 +- backend/tests/wm_token_confinement.rs | 39 ++++++++ backend/tests/ws_specific.rs | 99 +++++++++++++++++++ .../windmill-api-workspaces/src/workspaces.rs | 47 +++++---- backend/windmill-store/src/resources.rs | 81 ++++++++------- backend/windmill-store/src/variables.rs | 63 +++++++----- 6 files changed, 251 insertions(+), 82 deletions(-) rename backend/.sqlx/{query-be1de9116b18a40681cb8c5ec7578fd7c5f7ce77f7af63f766c2899d85fe0bef.json => query-dcf0071eb7adb1382ea183e0d92b4c7377ed7c40b81182f0b0ea95381b0f7b2e.json} (63%) diff --git a/backend/.sqlx/query-be1de9116b18a40681cb8c5ec7578fd7c5f7ce77f7af63f766c2899d85fe0bef.json b/backend/.sqlx/query-dcf0071eb7adb1382ea183e0d92b4c7377ed7c40b81182f0b0ea95381b0f7b2e.json similarity index 63% rename from backend/.sqlx/query-be1de9116b18a40681cb8c5ec7578fd7c5f7ce77f7af63f766c2899d85fe0bef.json rename to backend/.sqlx/query-dcf0071eb7adb1382ea183e0d92b4c7377ed7c40b81182f0b0ea95381b0f7b2e.json index a03162fcb9..f4f212856b 100644 --- a/backend/.sqlx/query-be1de9116b18a40681cb8c5ec7578fd7c5f7ce77f7af63f766c2899d85fe0bef.json +++ b/backend/.sqlx/query-dcf0071eb7adb1382ea183e0d92b4c7377ed7c40b81182f0b0ea95381b0f7b2e.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT value FROM resource WHERE path = $1 AND workspace_id = $2", + "query": "SELECT value FROM resource WHERE path = $1 AND workspace_id = $2 FOR UPDATE", "describe": { "columns": [ { @@ -19,5 +19,5 @@ true ] }, - "hash": "be1de9116b18a40681cb8c5ec7578fd7c5f7ce77f7af63f766c2899d85fe0bef" + "hash": "dcf0071eb7adb1382ea183e0d92b4c7377ed7c40b81182f0b0ea95381b0f7b2e" } diff --git a/backend/tests/wm_token_confinement.rs b/backend/tests/wm_token_confinement.rs index a57bab5332..dd70ac8e13 100644 --- a/backend/tests/wm_token_confinement.rs +++ b/backend/tests/wm_token_confinement.rs @@ -1232,3 +1232,42 @@ async fn test_privilege_gates_reject_a_job_token_directly( Ok(()) } + +/// A database source named by a `$res:` path is held to the token's resource scopes like any +/// other read of that resource, the instance database included, even for a token carrying its +/// owner's superadmin rights. +#[sqlx::test(fixtures("preserve_on_behalf_of"))] +async fn test_pg_source_is_held_to_resource_scopes(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let base = format!("http://localhost:{port}/api"); + + let resp = authed( + client().post(format!("{base}/users/tokens/create")), + "SECRET_TOKEN", + ) + .json(&json!({ + "label": "scoped", + "scopes": ["workspaces:write"], + "workspace_id": "test-workspace", + "super_admin": true, + })) + .send() + .await?; + assert_eq!(resp.status(), 201); + let scoped = resp.text().await?; + + let resp = authed( + client().post(format!( + "{base}/w/test-workspace/workspaces/get_datatable_full_schema" + )), + &scoped, + ) + .json(&json!({ "source": "$res:CUSTOM_INSTANCE_DB/windmill" })) + .send() + .await?; + assert_eq!(resp.status(), 403, "{}", resp.text().await?); + + Ok(()) +} diff --git a/backend/tests/ws_specific.rs b/backend/tests/ws_specific.rs index 322de598b7..98a42d29b0 100644 --- a/backend/tests/ws_specific.rs +++ b/backend/tests/ws_specific.rs @@ -647,3 +647,102 @@ async fn test_bulk_delete_follows_what_rls_deleted(db: Pool) -> anyhow Ok(()) } + +/// A variable and a resource at the same path are deleted and renamed together, so a token +/// scoped to one kind must not move or delete the other through that pair. +#[sqlx::test(fixtures("ws_specific"))] +async fn test_scoped_token_needs_both_halves_of_a_linked_pair( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let base = format!("http://localhost:{port}/api/w/test-workspace"); + let path = "u/test-user/pair"; + + for (kind, body) in [ + ( + "variables", + json!({ "path": path, "value": "v", "is_secret": false, "description": "" }), + ), + ( + "resources", + json!({ "path": path, "value": { "a": 1 }, "resource_type": "object" }), + ), + ] { + let resp = authed( + client().post(format!("{base}/{kind}/create")), + "SECRET_TOKEN", + ) + .json(&body) + .send() + .await?; + assert_eq!(resp.status(), 201, "create {kind}: {}", resp.text().await?); + } + + let var_only = mint_scoped_token(port, vec!["variables:write:u/test-user/*"]).await?; + let res_only = mint_scoped_token(port, vec!["resources:write:u/test-user/*"]).await?; + let attempts = [ + ( + &var_only, + client().delete(format!("{base}/variables/delete/{path}")), + json!(null), + ), + ( + &var_only, + client().delete(format!("{base}/variables/delete_bulk")), + json!({ "paths": [path] }), + ), + ( + &var_only, + client().post(format!("{base}/variables/update/{path}")), + json!({ "path": "u/test-user/pair2" }), + ), + ( + &res_only, + client().post(format!("{base}/resources/update/{path}")), + json!({ "path": "u/test-user/pair2" }), + ), + ]; + for (token, req, body) in attempts { + let req = if body.is_null() { req } else { req.json(&body) }; + let resp = authed(req, token).send().await?; + assert_eq!(resp.status(), 403, "{}", resp.text().await?); + } + + for table in ["variable", "resource"] { + let n: i64 = sqlx::query_scalar(&format!( + "SELECT COUNT(*) FROM {table} WHERE workspace_id = 'test-workspace' AND path = $1" + )) + .bind(path) + .fetch_one(&db) + .await?; + assert_eq!(n, 1, "the {table} must stay where it was"); + } + + // A token holding both scopes still renames the pair. + let both = mint_scoped_token( + port, + vec![ + "variables:write:u/test-user/*", + "resources:write:u/test-user/*", + ], + ) + .await?; + let resp = authed( + client().post(format!("{base}/variables/update/{path}")), + &both, + ) + .json(&json!({ "path": "u/test-user/pair2" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let moved: i64 = sqlx::query_scalar( + "SELECT COUNT(*) FROM resource WHERE workspace_id = 'test-workspace' AND path = 'u/test-user/pair2'", + ) + .fetch_one(&db) + .await?; + assert_eq!(moved, 1); + + Ok(()) +} diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index f753bb069e..265d5a11ab 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -3377,28 +3377,33 @@ pub(crate) async fn resolve_pg_source_checked_with_kind( managed_kind = kind; connection } else if let Some(path) = source.strip_prefix("$res:") { - let db_with_authed = windmill_common::db::DbWithOptAuthed::from_authed( - authed, - db.clone(), - Some(user_db.clone()), - ); - let value = windmill_store::resources::get_resource_value_interpolated_internal( - &db_with_authed, - w_id, - path, - None, - None, - false, - ) - .await?; + check_scopes(authed, || format!("resources:read:{}", path))?; + if let Some(dbname) = path.strip_prefix("CUSTOM_INSTANCE_DB/") { + windmill_store::resources::custom_instance_db_value(authed, db, dbname).await? + } else { + let db_with_authed = windmill_common::db::DbWithOptAuthed::from_authed( + authed, + db.clone(), + Some(user_db.clone()), + ); + let value = windmill_store::resources::get_resource_value_interpolated_internal( + &db_with_authed, + w_id, + path, + None, + None, + false, + ) + .await?; - match value { - Some(v) => v, - None => { - return Err(Error::NotAuthorized(format!( - "Resource '{}' not found or you do not have access to it", - path - ))); + match value { + Some(v) => v, + None => { + return Err(Error::NotAuthorized(format!( + "Resource '{}' not found or you do not have access to it", + path + ))); + } } } } else { diff --git a/backend/windmill-store/src/resources.rs b/backend/windmill-store/src/resources.rs index fd5ae7958c..3822503de9 100644 --- a/backend/windmill-store/src/resources.rs +++ b/backend/windmill-store/src/resources.rs @@ -803,6 +803,11 @@ async fn get_resource_value_interpolated( let path = path.to_path(); check_scopes(&authed, || format!("resources:read:{}", path))?; + if let Some(dbname) = path.strip_prefix("CUSTOM_INSTANCE_DB/") { + return custom_instance_db_value(&authed, &db, dbname) + .await + .map(|v| Json(Some(v))); + } let db_with_opt_authed = DbWithOptAuthed::from_authed(&authed, db.clone(), Some(user_db.clone())); get_resource_value_interpolated_internal( @@ -817,6 +822,35 @@ async fn get_resource_value_interpolated( .map(|success| Json(success)) } +/// The instance database's own credentials for `CUSTOM_INSTANCE_DB/`. Only reachable from +/// a route where the caller names that path in their own request: a lookup made on someone's +/// behalf (an app's inputs resolved as its viewer, a resource value's references) must never +/// reach it, so `get_resource_value_interpolated_internal` does not serve it. +pub async fn custom_instance_db_value( + authed: &ApiAuthed, + db: &DB, + dbname: &str, +) -> Result { + // A job's WM_TOKEN must never reach this superadmin-only path even if it runs on behalf of a + // superadmin. Read the job provenance from the *authenticated* identity, never a + // caller-supplied `job_id` param. + if authed.job_id.is_some() { + return Err(Error::NotAuthorized( + "CUSTOM_INSTANCE_DB cannot be resolved from a job token ($WM_TOKEN)".to_string(), + )); + } + if authed.super_admin_withheld { + return Err(Error::NotAuthorized( + "CUSTOM_INSTANCE_DB requires a token carrying superadmin rights".to_string(), + )); + } + require_super_admin_email(db, &authed.email).await?; + let mut pg_creds = PgDatabase::parse_uri(&get_database_url().await?.as_str().await)?; + pg_creds.dbname = dbname.to_string(); + serde_json::to_value(&pg_creds) + .map_err(|e| Error::internal_err(format!("Error serializing pg creds: {}", e))) +} + pub async fn get_resource_value_interpolated_internal<'a>( db_with_opt_authed: &'a DbWithOptAuthed<'a, ApiAuthed>, workspace: &str, @@ -825,33 +859,6 @@ pub async fn get_resource_value_interpolated_internal<'a>( token_for_context: Option<&str>, allow_cache: bool, ) -> Result> { - // This is a special syntax to help debugging custom instance databases - if let Some(dbname) = path.strip_prefix("CUSTOM_INSTANCE_DB/") { - // A job's WM_TOKEN must never reach this superadmin-only path even if it - // runs on behalf of a superadmin (GHSA-hfh4-cx4h-3fcr). Read the job - // provenance from the *authenticated* identity, never the caller-supplied - // `job_id` param (which comes from an untrusted query string). - if db_with_opt_authed.authed().and_then(|a| a.job_id).is_some() { - return Err(Error::NotAuthorized( - "CUSTOM_INSTANCE_DB cannot be resolved from a job token ($WM_TOKEN)".to_string(), - )); - } - if db_with_opt_authed - .authed() - .is_some_and(|a| a.super_admin_withheld) - { - return Err(Error::NotAuthorized( - "CUSTOM_INSTANCE_DB requires a token carrying superadmin rights".to_string(), - )); - } - require_super_admin_email(db_with_opt_authed.db(), &db_with_opt_authed.email()).await?; - let mut pg_creds = PgDatabase::parse_uri(&get_database_url().await?.as_str().await)?; - pg_creds.dbname = dbname.to_string(); - let pg_creds = serde_json::to_value(&pg_creds) - .map_err(|e| Error::internal_err(format!("Error serializing pg creds: {}", e)))?; - return Ok(Some(pg_creds)); - } - // Scope the cache to the caller's full authorization identity (not just email): the // cached value is already decrypted/interpolated under this caller's RLS context, so it // must never be served to a context that resolves to different permissions. Only @@ -2244,6 +2251,10 @@ async fn update_resource( .await?; if let Some(var) = linked_var { + // The variable moves with the resource, so a scoped token needs write access to it + // at both paths. + check_scopes(&authed, || format!("variables:write:{}", path))?; + check_scopes(&authed, || format!("variables:write:{}", npath))?; if var.is_secret { // Check if this is a Vault-stored secret and rename it if let Some(new_value) = @@ -2614,17 +2625,21 @@ async fn resolve_agent_on_behalf_of( } /// Held until the write commits: whether a value is resolved as an agent's depends on the type -/// read after this, and a concurrent retype into an agent must not land between the two. +/// read after this, and a concurrent retype into an agent must not land between the two. A +/// missing row is refused rather than passed over: nothing would be locked, and a resource +/// created meanwhile would take a write judged against no type at all. async fn lock_resource_row( tx: &mut Transaction<'_, Postgres>, w_id: &str, path: &str, ) -> Result<()> { - sqlx::query("SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2 FOR UPDATE") - .bind(w_id) - .bind(path) - .execute(&mut **tx) - .await?; + let locked = + sqlx::query("SELECT 1 FROM resource WHERE workspace_id = $1 AND path = $2 FOR UPDATE") + .bind(w_id) + .bind(path) + .fetch_optional(&mut **tx) + .await?; + not_found_if_none(locked, "Resource", path)?; Ok(()) } diff --git a/backend/windmill-store/src/variables.rs b/backend/windmill-store/src/variables.rs index dafef639a7..e193d966b1 100644 --- a/backend/windmill-store/src/variables.rs +++ b/backend/windmill-store/src/variables.rs @@ -1107,6 +1107,11 @@ async fn delete_variable( ) .fetch_optional(&mut *tx) .await?; + // The resource at the same path goes with the variable, so a scoped token needs write access + // to it too. Erroring rolls the whole delete back. + if deleted_linked_resource.is_some() { + check_scopes(&authed, || format!("resources:write:{}", path))?; + } if let Some(var_data) = trash_var { let mut trash_data = serde_json::json!({"row": var_data}); @@ -1297,6 +1302,9 @@ async fn delete_variables_bulk( ) .fetch_all(&mut *tx) .await?; + for rpath in &deleted_resource_paths { + check_scopes(&authed, || format!("resources:write:{}", rpath))?; + } sqlx::query!( "DELETE FROM ws_specific WHERE workspace_id = $1 AND item_kind = 'variable' AND path = ANY($2)", @@ -1521,7 +1529,6 @@ async fn update_variable( check_path_conflict(&db, &w_id, &npath).await?; require_owner_of_path(&authed, path)?; - // Handle Vault secret rename if the variable is a secret stored in Vault let current_var = sqlx::query!( "SELECT value::text AS \"value!\", is_secret FROM variable WHERE path = $1 AND workspace_id = $2", path, @@ -1530,6 +1537,22 @@ async fn update_variable( .fetch_optional(&mut *tx) .await?; + // Locked so the value written back below is the one stored now, not one a concurrent + // resource write has since replaced. + let linked_resource = sqlx::query_scalar!( + "SELECT value FROM resource WHERE path = $1 AND workspace_id = $2 FOR UPDATE", + path, + w_id + ) + .fetch_optional(&mut *tx) + .await?; + // The resource at the same path moves with the variable. + if linked_resource.is_some() { + check_scopes(&authed, || format!("resources:write:{}", path))?; + check_scopes(&authed, || format!("resources:write:{}", npath))?; + } + + // Handle Vault secret rename if the variable is a secret stored in Vault if let Some(var) = current_var { if var.is_secret && is_http_store_stored_value(&var.value) { return Err(http_store_rename_error(path)); @@ -1552,33 +1575,21 @@ async fn update_variable( } } - let mut v = sqlx::query_scalar!( - "SELECT value FROM resource WHERE path = $1 AND workspace_id = $2", - path, - w_id - ) - .fetch_optional(&mut *tx) - .await? - .flatten(); - - if let Some(old_v) = v { - v = Some(replace_path( - old_v, - &format!("$var:{path}"), - &format!("$var:{npath}"), - )) + if let Some(v) = linked_resource { + let v = v.map(|old_v| { + replace_path(old_v, &format!("$var:{path}"), &format!("$var:{npath}")) + }); + sqlx::query!( + "UPDATE resource SET path = $1, value = $2, edited_at = now() WHERE path = $3 AND workspace_id = $4", + npath, + v, + path, + w_id + ) + .execute(&mut *tx) + .await?; } - sqlx::query!( - "UPDATE resource SET path = $1, value = $2, edited_at = now() WHERE path = $3 AND workspace_id = $4", - npath, - v, - path, - w_id - ) - .execute(&mut *tx) - .await?; - sqlx::query!( "UPDATE native_trigger SET connection_path = $1 WHERE workspace_id = $2 AND connection_path = $3", npath,