diff --git a/backend/windmill-api-integration-tests/tests/offboarding.rs b/backend/windmill-api-integration-tests/tests/offboarding.rs index 8dc8079096..ce5d0578ca 100644 --- a/backend/windmill-api-integration-tests/tests/offboarding.rs +++ b/backend/windmill-api-integration-tests/tests/offboarding.rs @@ -321,6 +321,86 @@ async fn test_offboard_to_folder(db: Pool) -> anyhow::Result<()> { Ok(()) } +/// Offboarding moves the user's runnables to the target, so handlers naming them must follow. +#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))] +async fn test_offboard_moves_handler_paths(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::raw_sql( + r#"UPDATE schedule SET on_failure = 'script/u/test-user-2/script_a', on_success = 'flow/u/test-user-2/flow_a' + WHERE workspace_id = 'test-workspace' AND path = 'f/test-folder/sched_shared'; + UPDATE http_trigger SET error_handler_path = 'u/test-user-2/script_b' + WHERE workspace_id = 'test-workspace' AND path = 'f/test-folder/webhook_shared'; + UPDATE workspace_settings SET error_handler = '{"path": "script/u/test-user-2/script_b", "muted_on_cancel": true}', + slack_command_script = 'u/test-user-2/script_a', teams_command_script = 'flow/u/test-user-2/flow_a', + default_app = 'u/test-user-2/app_a' + WHERE workspace_id = 'test-workspace';"#, + ) + .execute(&db) + .await?; + + let resp = authed(client().post(ws_url(port, "offboard/test-user-2"))) + .json(&json!({ + "reassign_to": "f/test-folder", + "new_on_behalf_of_user": "test-user", + "delete_user": true + })) + .send() + .await?; + assert_eq!(resp.status(), 200, "offboard: {}", resp.text().await?); + + let schedule: (String, String) = sqlx::query_as( + "SELECT on_failure, on_success FROM schedule + WHERE workspace_id = 'test-workspace' AND path = 'f/test-folder/sched_shared'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + schedule, + ( + "script/f/test-folder/script_a".into(), + "flow/f/test-folder/flow_a".into() + ) + ); + + let trigger: String = sqlx::query_scalar( + "SELECT error_handler_path FROM http_trigger + WHERE workspace_id = 'test-workspace' AND path = 'f/test-folder/webhook_shared'", + ) + .fetch_one(&db) + .await?; + assert_eq!(trigger, "f/test-folder/script_b"); + + let error_handler: serde_json::Value = sqlx::query_scalar( + "SELECT error_handler FROM workspace_settings WHERE workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + error_handler, + json!({ "path": "script/f/test-folder/script_b", "muted_on_cancel": true }) + ); + + let commands: (String, String, String) = sqlx::query_as( + "SELECT slack_command_script, teams_command_script, default_app FROM workspace_settings + WHERE workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + commands, + ( + "f/test-folder/script_a".into(), + "flow/f/test-folder/flow_a".into(), + "f/test-folder/app_a".into() + ) + ); + + Ok(()) +} + #[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))] async fn test_offboard_reassign_only(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; diff --git a/backend/windmill-api-integration-tests/tests/users.rs b/backend/windmill-api-integration-tests/tests/users.rs index b46d196d68..ad6706a470 100644 --- a/backend/windmill-api-integration-tests/tests/users.rs +++ b/backend/windmill-api-integration-tests/tests/users.rs @@ -1362,6 +1362,117 @@ async fn test_rename_moves_run_as_of_schedules_and_triggers( Ok(()) } +/// The rename moves the user's runnables, so every handler naming one must follow in the form its +/// column stores, or it fails exactly when it fires. A handler under another user's path stays. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_rename_moves_handler_paths(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::raw_sql( + r#"INSERT INTO schedule (workspace_id, path, edited_by, edited_at, schedule, timezone, enabled, script_path, is_flow, email, permissioned_as, extra_perms, on_failure, on_recovery, on_success, dynamic_skip) + VALUES ('test-workspace', 'f/ops/nightly', 'test-user', NOW(), '0 * * * *', 'UTC', true, 'f/ops/job', false, 'test@windmill.dev', 'u/test-user', '{}', + 'script/u/test-user-2/on_fail', 'flow/u/test-user-2/on_recover', 'script/u/test-user/on_success', 'u/test-user-2/skip'); + INSERT INTO http_trigger (workspace_id, path, route_path, route_path_key, script_path, is_flow, edited_by, permissioned_as, edited_at, extra_perms, http_method, authentication_method, mode, error_handler_path) + VALUES ('test-workspace', 'f/ops/hook', '/hook', 'hook', 'f/ops/job', false, 'test-user', 'u/test-user', NOW(), '{}', 'post', 'none', 'enabled', 'u/test-user-2/trigger_err'); + INSERT INTO kafka_trigger (workspace_id, path, kafka_resource_path, topics, group_id, script_path, is_flow, edited_by, permissioned_as, error_handler_path, server_id) + VALUES ('test-workspace', 'f/ops/k', 'f/ops/kafka', '{t}', 'g', 'f/ops/job', false, 'test-user', 'u/test-user', 'u/test-user/trigger_err', 'srv'), + ('test-workspace', 'f/ops/k2', 'f/ops/kafka', '{t}', 'g', 'f/ops/job', false, 'test-user', 'u/test-user', 'u/test-user-2/trigger_err', 'srv'); + UPDATE workspace_settings SET + error_handler = '{"path": "script/u/test-user-2/ws_err", "extra_args": {"channel": "ops"}, "muted_on_cancel": true}', + success_handler = '{"path": "flow/u/test-user-2/ws_ok"}', + variable_expiration_handler = '{"path": "script/u/test-user/expiry", "notify_before_secs": 60}', + slack_command_script = 'script/u/test-user-2/slack_cmd', + teams_command_script = 'u/test-user/teams_cmd', + default_app = 'u/test-user-2/home' + WHERE workspace_id = 'test-workspace';"#, + ) + .execute(&db) + .await?; + + let resp = authed(client().post(format!( + "http://localhost:{port}/api/users/rename/test2@windmill.dev" + ))) + .json(&json!({ "new_username": "alice" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "rename: {}", resp.text().await?); + + let schedule: (String, String, String, String) = sqlx::query_as( + "SELECT on_failure, on_recovery, on_success, dynamic_skip FROM schedule + WHERE workspace_id = 'test-workspace' AND path = 'f/ops/nightly'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + schedule, + ( + "script/u/alice/on_fail".into(), + "flow/u/alice/on_recover".into(), + "script/u/test-user/on_success".into(), + "u/alice/skip".into() + ) + ); + + let http: String = sqlx::query_scalar( + "SELECT error_handler_path FROM http_trigger WHERE workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!(http, "u/alice/trigger_err"); + // A listener whose handler moved must restart to load it; one whose handler stayed is left be. + let kafka: Vec<(String, String, Option)> = sqlx::query_as( + "SELECT path, error_handler_path, server_id FROM kafka_trigger + WHERE workspace_id = 'test-workspace' ORDER BY path", + ) + .fetch_all(&db) + .await?; + assert_eq!( + kafka, + vec![ + ( + "f/ops/k".into(), + "u/test-user/trigger_err".into(), + Some("srv".into()) + ), + ("f/ops/k2".into(), "u/alice/trigger_err".into(), None), + ] + ); + + let settings: (serde_json::Value, serde_json::Value, serde_json::Value) = sqlx::query_as( + "SELECT error_handler, success_handler, variable_expiration_handler FROM workspace_settings + WHERE workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + settings, + ( + json!({ "path": "script/u/alice/ws_err", "extra_args": { "channel": "ops" }, "muted_on_cancel": true }), + json!({ "path": "flow/u/alice/ws_ok" }), + json!({ "path": "script/u/test-user/expiry", "notify_before_secs": 60 }) + ) + ); + + let commands: (String, String, String) = sqlx::query_as( + "SELECT slack_command_script, teams_command_script, default_app FROM workspace_settings + WHERE workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!( + commands, + ( + "script/u/alice/slack_cmd".into(), + "u/test-user/teams_cmd".into(), + "u/alice/home".into() + ) + ); + + Ok(()) +} + /// Outside a superadmin's workspaces `u/{password.username}` resolves to them, so their rows there /// follow the rename — but not in a workspace where a member holds that name, where it was theirs. #[sqlx::test(migrations = "../migrations", fixtures("base"))] diff --git a/backend/windmill-api/src/offboarding.rs b/backend/windmill-api/src/offboarding.rs index 3fe9750d2b..7ae0b19ecf 100644 --- a/backend/windmill-api/src/offboarding.rs +++ b/backend/windmill-api/src/offboarding.rs @@ -1184,6 +1184,14 @@ async fn offboard_user_from_workspace<'c>( .await?; } + crate::users::move_handler_paths( + tx, + w_id, + &format!("u/{username}/"), + &format!("{new_prefix}/"), + ) + .await?; + // NOTE: extra_perms cleanup, folder owners, favorites, inputs, captures, // and token deletion are handled by delete_workspace_user_internal when delete_user=true. // They are NOT done here for reassign-only (delete_user=false) since the user stays. diff --git a/backend/windmill-api/src/users.rs b/backend/windmill-api/src/users.rs index 9153454dfe..80ff96faf3 100644 --- a/backend/windmill-api/src/users.rs +++ b/backend/windmill-api/src/users.rs @@ -466,6 +466,121 @@ async fn move_run_as_principal( Ok(()) } +/// Moves the handlers that name a runnable under `old_prefix` (e.g. `u/alice/`) to the same path +/// under `new_prefix`, in the form each column stores: schedule handlers and the workspace +/// handlers' `path` carry a `script/` or `flow/` kind, a schedule's skip handler and a trigger's +/// error handler are bare script paths. A handler left on the old path fails exactly when it fires. +/// The Slack and Teams command scripts and the workspace's default app move the same way. +pub(crate) async fn move_handler_paths( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + w_id: &str, + old_prefix: &str, + new_prefix: &str, +) -> error::Result<()> { + // `starts_with` rather than `LIKE`/regex: a legacy email-shaped username carries `.` and `_`, + // which those would treat as wildcards and so rewrite another user's paths. + let moved = |col: &str| { + format!( + "CASE WHEN starts_with({col}, $1) THEN $2 || substr({col}, char_length($1) + 1) ELSE {col} END" + ) + }; + let moved_kind = |col: &str| { + format!( + "CASE WHEN starts_with({col}, 'script/' || $1) THEN 'script/' || $2 || substr({col}, char_length($1) + 8) + WHEN starts_with({col}, 'flow/' || $1) THEN 'flow/' || $2 || substr({col}, char_length($1) + 6) + ELSE {col} END" + ) + }; + let names_old = |col: &str| { + format!("(starts_with({col}, 'script/' || $1) OR starts_with({col}, 'flow/' || $1))") + }; + + // SAFETY: the interpolated column names are literals from this function. + sqlx::query(&format!( + "UPDATE schedule SET on_failure = {}, on_recovery = {}, on_success = {}, dynamic_skip = {} + WHERE workspace_id = $3 AND ({} OR {} OR {} OR starts_with(dynamic_skip, $1))", + moved_kind("on_failure"), + moved_kind("on_recovery"), + moved_kind("on_success"), + moved("dynamic_skip"), + names_old("on_failure"), + names_old("on_recovery"), + names_old("on_success"), + )) + .bind(old_prefix) + .bind(new_prefix) + .bind(w_id) + .execute(&mut **tx) + .await?; + + // SAFETY: `table` comes from the hardcoded `TRIGGER_TABLES`, not user input. + for table in TRIGGER_TABLES { + // A listener keeps the config it started with and its ping does not compare the handler, + // so clearing `server_id` is what makes it restart on the rewritten path. + let restart = match table { + "http_trigger" | "email_trigger" => "", + _ => ", server_id = NULL", + }; + sqlx::query(&format!( + "UPDATE {table} SET error_handler_path = {}{restart} + WHERE workspace_id = $3 AND starts_with(error_handler_path, $1)", + moved("error_handler_path"), + )) + .bind(old_prefix) + .bind(new_prefix) + .bind(w_id) + .execute(&mut **tx) + .await?; + } + + for setting in [ + "error_handler", + "success_handler", + "variable_expiration_handler", + ] { + let path = format!("({setting}->>'path')"); + sqlx::query(&format!( + "UPDATE workspace_settings SET {setting} = jsonb_set({setting}, '{{path}}', to_jsonb({})) + WHERE workspace_id = $3 AND {}", + moved_kind(&path), + names_old(&path), + )) + .bind(old_prefix) + .bind(new_prefix) + .bind(w_id) + .execute(&mut **tx) + .await?; + } + + // The command scripts are read with `RunnableRef::from_setting`, which takes a bare script + // path as well as a prefixed one, so both forms are moved. + let moved_command = |col: &str| { + format!( + "CASE WHEN {} THEN {} ELSE {} END", + names_old(col), + moved_kind(col), + moved(col) + ) + }; + let names_command = |col: &str| format!("({} OR starts_with({col}, $1))", names_old(col)); + sqlx::query(&format!( + "UPDATE workspace_settings + SET slack_command_script = {}, teams_command_script = {}, default_app = {} + WHERE workspace_id = $3 AND ({} OR {} OR starts_with(default_app, $1))", + moved_command("slack_command_script"), + moved_command("teams_command_script"), + moved("default_app"), + names_command("slack_command_script"), + names_command("teams_command_script"), + )) + .bind(old_prefix) + .bind(new_prefix) + .bind(w_id) + .execute(&mut **tx) + .await?; + Ok(()) +} + async fn update_username_in_workpsace<'c>( tx: &mut sqlx::Transaction<'c, sqlx::Postgres>, db: &DB, @@ -1057,6 +1172,8 @@ async fn update_username_in_workpsace<'c>( ) .await?; + move_handler_paths(tx, w_id, &old_prefix, &new_prefix).await?; + // ---- group_ ---- sqlx::query!(