From 2df2c83313c871567de448e33acecffda4ad459a Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Tue, 24 Nov 2026 21:45:22 +0000 Subject: [PATCH] fix: pin definer function search_path and check sql contextual vars (#12640) Co-authored-by: Claude Opus 5.5 --- ...61124193322_pin_definer_functions.down.sql | 2 + ...0261124193322_pin_definer_functions.up.sql | 30 +++++++++ backend/windmill-common/src/workspaces.rs | 33 +++++++++- .../tests/definer_functions.rs | 39 +++++++++++ .../src/sanitized_sql_params.rs | 66 ++++++++++++++++++- 5 files changed, 167 insertions(+), 3 deletions(-) create mode 100644 backend/migrations/20261124193322_pin_definer_functions.down.sql create mode 100644 backend/migrations/20261124193322_pin_definer_functions.up.sql create mode 100644 backend/windmill-common/tests/definer_functions.rs diff --git a/backend/migrations/20261124193322_pin_definer_functions.down.sql b/backend/migrations/20261124193322_pin_definer_functions.down.sql new file mode 100644 index 0000000000..cb7bed957f --- /dev/null +++ b/backend/migrations/20261124193322_pin_definer_functions.down.sql @@ -0,0 +1,2 @@ +-- No-op: the previous grants and search_path are not restored. +SELECT 1; diff --git a/backend/migrations/20261124193322_pin_definer_functions.up.sql b/backend/migrations/20261124193322_pin_definer_functions.up.sql new file mode 100644 index 0000000000..5a1eaa0ac4 --- /dev/null +++ b/backend/migrations/20261124193322_pin_definer_functions.up.sql @@ -0,0 +1,30 @@ +-- Every definer-rights function (prosecdef) owned by the migration role gets a search_path +-- ending in pg_temp, so a session's temporary objects never resolve ahead of the schema's +-- (pg_temp is searched first unless the path names it), and loses the default PUBLIC EXECUTE +-- grant, so only Windmill's own roles use it. The schema comes from current_schema() so installs +-- with a non-public PG_SCHEMA resolve (see 20260624103600). A later CREATE OR REPLACE resets the +-- path and a new function starts with the PUBLIC grant: both need the same two statements. +DO +$do$ +DECLARE + target_schema TEXT := current_schema(); + fn regprocedure; +BEGIN + FOR fn IN + SELECT p.oid::regprocedure + FROM pg_proc p + JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = target_schema + AND p.prosecdef + AND pg_has_role(current_user, p.proowner, 'USAGE') + LOOP + EXECUTE format('ALTER FUNCTION %s SET search_path = %I, pg_temp', fn, target_schema); + EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM PUBLIC', fn); + END LOOP; +END +$do$; + +-- folder_labels() is the only one that is called rather than fired, from user_db transactions +-- (SET LOCAL ROLE windmill_user / windmill_admin) and by the owner. Trigger functions need no +-- grant: EXECUTE is checked when a trigger is created, not when it fires. +GRANT EXECUTE ON FUNCTION folder_labels(text, text) TO windmill_user, windmill_admin; diff --git a/backend/windmill-common/src/workspaces.rs b/backend/windmill-common/src/workspaces.rs index e296b59b95..907d8b5767 100644 --- a/backend/windmill-common/src/workspaces.rs +++ b/backend/windmill-common/src/workspaces.rs @@ -2146,6 +2146,18 @@ pub async fn resolve_workspace_governing_datatables( .collect()) } +/// Replication connections resolve unqualified names in `pg_catalog` only, never in the +/// database's `public` schema, whose objects the workspace manages. A startup option outranks +/// `ALTER ROLE/DATABASE ... SET`, and the last `-c` wins over one already in the options of +/// `DATABASE_URL`. +fn pin_replication_search_path(pg_creds: &mut PgDatabase) { + const PIN: &str = "-c search_path=pg_catalog"; + pg_creds.options = Some(match pg_creds.non_empty_options() { + Some(options) => format!("{options} {PIN}"), + None => PIN.to_string(), + }); +} + /// Build the `admin` connection for a governing entry: `custom_instance_user` for an instance /// database, on Windmill's cluster or the external one; the user's own resource for a BYO-postgres /// one. @@ -2160,12 +2172,15 @@ async fn resolve_datatable_connection_unchecked( .as_ref() .expect("a governing entry owns a database"); if database.resource_type == DataTableCatalogResourceType::ExternalInstance { - let pg_creds = crate::external_instance_pg::external_instance_connection_unchecked( + let mut pg_creds = crate::external_instance_pg::external_instance_connection_unchecked( db, &database.resource_path, replication, ) .await?; + if replication { + pin_replication_search_path(&mut pg_creds); + } serde_json::to_value(&pg_creds) .map_err(|e| Error::internal_err(format!("Error serializing pg creds: {}", e))) } else if database.resource_type == DataTableCatalogResourceType::Instance { @@ -2184,6 +2199,7 @@ async fn resolve_datatable_connection_unchecked( if replication { pg_creds.user = Some("custom_instance_replication_user".to_string()); pg_creds.password = Some(get_custom_pg_instance_replication_password(&db).await?); + pin_replication_search_path(&mut pg_creds); } else { pg_creds.user = Some(CUSTOM_INSTANCE_USER.to_string()); pg_creds.password = Some(get_custom_pg_instance_password(&db).await?); @@ -4017,6 +4033,21 @@ mod tests { DataTableRoleTenants { tenants: list.iter().map(|t| t.to_string()).collect() } } + #[test] + fn replication_search_path_is_pinned_after_the_url_options() { + let mut creds = PgDatabase::parse_uri("postgres://u@h/db").unwrap(); + pin_replication_search_path(&mut creds); + assert_eq!(creds.options.as_deref(), Some("-c search_path=pg_catalog")); + + let mut creds = + PgDatabase::parse_uri("postgres://u@h/db?options=-c+search_path%3Dpublic").unwrap(); + pin_replication_search_path(&mut creds); + assert_eq!( + creds.options.as_deref(), + Some("-c search_path=public -c search_path=pg_catalog") + ); + } + #[test] fn sync_script_version_is_the_second_segment_of_the_queued_path() { let meets = |p, min| sync_script_meets_min_version(&sync_callback_path(p), min); diff --git a/backend/windmill-common/tests/definer_functions.rs b/backend/windmill-common/tests/definer_functions.rs new file mode 100644 index 0000000000..491a38ee70 --- /dev/null +++ b/backend/windmill-common/tests/definer_functions.rs @@ -0,0 +1,39 @@ +use sqlx::{Pool, Postgres}; + +/// Every definer-rights function must have no PUBLIC EXECUTE grant and pin a search_path ending +/// in pg_temp. Checked over the catalog so that a new function, or one redefined with CREATE OR +/// REPLACE (which resets both), fails here. +#[sqlx::test(migrations = "../migrations")] +async fn definer_functions_are_pinned_and_closed_to_public(db: Pool) { + let exposed: Vec = sqlx::query_scalar( + "SELECT p.oid::regprocedure::text + FROM pg_proc p + JOIN pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = current_schema() + AND p.prosecdef + AND (has_function_privilege('public', p.oid, 'EXECUTE') + OR NOT EXISTS ( + SELECT 1 FROM unnest(p.proconfig) AS c + WHERE c LIKE 'search_path=%' AND c LIKE '%, pg_temp')) + ORDER BY 1", + ) + .fetch_all(&db) + .await + .unwrap(); + assert!( + exposed.is_empty(), + "executable by PUBLIC, or without a search_path ending in pg_temp: {exposed:?}" + ); + + let mut tx = db.begin().await.unwrap(); + sqlx::query("SET LOCAL ROLE windmill_user") + .execute(&mut *tx) + .await + .unwrap(); + let labels: Option> = + sqlx::query_scalar("SELECT folder_labels('admins', 'f/none/item')") + .fetch_one(&mut *tx) + .await + .unwrap(); + assert_eq!(labels, None, "windmill_user keeps EXECUTE on folder_labels"); +} diff --git a/backend/windmill-worker/src/sanitized_sql_params.rs b/backend/windmill-worker/src/sanitized_sql_params.rs index 8560f14798..28b2691bf2 100644 --- a/backend/windmill-worker/src/sanitized_sql_params.rs +++ b/backend/windmill-worker/src/sanitized_sql_params.rs @@ -33,10 +33,30 @@ fn sanitize_identifier(arg: &Arg, input: &str) -> Result<(), error::Error> { } } +/// Contextual variables are pasted as raw text, usually inside a string literal, a quoted +/// identifier or a comment, and some values come from the job's inputs (an email, the +/// `_FLOW_PATH` argument). A value must not end any of those, in any dialect. +fn sanitize_contextual_variable(name: &str, value: &str) -> Result<(), error::Error> { + if value + .chars() + .any(|c| matches!(c, '\'' | '"' | '`' | ']' | '\\' | '$') || c.is_control()) + || value.contains("/*") + || value.contains("*/") + { + Err(error::Error::BadRequest(format!( + "Contextual variable `{name}` contains characters that cannot be safely interpolated \ + in a SQL query (quotes, backticks, `]`, `\\`, `$`, comment delimiters or control \ + characters)" + ))) + } else { + Ok(()) + } +} + fn replace_contextual_variables( code: &mut String, contextual_variables: &HashMap, -) -> () { +) -> Result<(), error::Error> { let vars = RE_SQL_CONTEXTUAL_VAR .find_iter(&code) .map(|m| m.as_str().to_string()) @@ -50,9 +70,11 @@ fn replace_contextual_variables( .unwrap(); let var_value = contextual_variables.get(var_name); if let Some(var_value) = var_value { + sanitize_contextual_variable(var_name, var_value)?; *code = code.replace(&var_pattern, var_value); } } + Ok(()) } pub fn sanitize_and_interpolate_unsafe_sql_args( @@ -64,7 +86,7 @@ pub fn sanitize_and_interpolate_unsafe_sql_args( let mut ret = code.to_string(); let mut args_to_skip = vec![]; - replace_contextual_variables(&mut ret, contextual_variables); + replace_contextual_variables(&mut ret, contextual_variables)?; for arg in args { if let Some(typ) = &arg.otyp { @@ -128,3 +150,43 @@ pub fn sanitize_and_interpolate_unsafe_sql_args( Ok((ret, args_to_skip)) } + +#[cfg(test)] +mod tests { + use super::*; + + fn interpolate(code: &str, var: &str, value: &str) -> Result { + let vars = HashMap::from([(var.to_string(), value.to_string())]); + sanitize_and_interpolate_unsafe_sql_args(code, &vec![], &HashMap::new(), &vars) + .map(|(code, _)| code) + } + + #[test] + fn contextual_variables_with_quoting_characters_are_refused() { + assert_eq!( + interpolate( + "SELECT '%%WM_EMAIL%%'", + "WM_EMAIL", + "first.last+tag@windmill.dev" + ) + .unwrap(), + "SELECT 'first.last+tag@windmill.dev'" + ); + for value in [ + "o'brien@example.com", + "f/a/b', 'c", + "x\\", + "say \"hi\"", + "a`b", + "a]b", + "a$$b", + "a\nb", + "a*/b", + "a/*b", + ] { + let err = + interpolate("SELECT '%%WM_FLOW_PATH%%'", "WM_FLOW_PATH", value).expect_err(value); + assert!(matches!(err, error::Error::BadRequest(_)), "{value}"); + } + } +}