Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: harden hook filtering, approvals store, and template expansion (#2841)
Maximilian Roos04a8f5c0c245
diff --git a/.typos.toml b/.typos.tomlindex 66c2d3be3..d03285d17 100644--- a/.typos.toml+++ b/.typos.toml@@ -13,5 +13,7 @@ PNGs = "PNGs"deplyo = "deplyo"comit = "comit"siwtch = "siwtch"+# Intentional typo in expansion.rs exercising conditional undefined-var validation+targte = "targte"# Intentional typo in CHANGELOG.md illustrating the unreferenced-var warningbrnach = "brnach"diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex 222420643..a705a8b50 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -241,20 +241,13 @@ pub fn approve_hooks_filtered(let mut commands = collect_commands_for_hooks(&project_config, hook_types);- // Apply name filters before approval to only prompt for targeted commands- // Collect non-empty name parts from filters- // Empty names (e.g., "project:") mean match all project commands - no filtering- let filter_names: Vec<&str> = parsed_filters- .iter()- .map(|f| f.name)- .filter(|n| !n.is_empty())- .collect();- if !filter_names.is_empty() {+ // Apply source-aware filters before approval to only prompt for targeted+ // project commands. User-scoped filters never match project commands.+ if !parsed_filters.is_empty() {commands.retain(|cmd| {- cmd.command- .name- .as_deref()- .is_some_and(|n| filter_names.contains(&n))+ parsed_filters+ .iter()+ .any(|f| f.matches_command(HookSource::Project, cmd.command.name.as_deref()))});}diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 19daebfc8..a2f77b5ea 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -902,6 +902,25 @@ mod tests {assert!(result.is_ok());}+ #[test]+ fn test_handle_command_error_warn_signal_aborts() {+ let err: anyhow::Error = WorktrunkError::ChildProcessExited {+ code: 143,+ message: "terminated".into(),+ signal: Some(15),+ }+ .into();+ let cmd = make_cmd(Some("cleanup"));+ let wrapper = hook_error_wrapper(HookType::PostStart);+ let result = handle_command_error(err, &cmd, &wrapper, FailureStrategy::Warn);+ let err = result.unwrap_err();+ let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();+ assert!(matches!(+ wt_err,+ WorktrunkError::AlreadyDisplayed { exit_code: 143 }+ ));+ }+#[test]fn test_handle_command_error_warn_unnamed() {// Covers the `cmd.name = None` branch of the Warn arm.diff --git a/src/commands/hook_filter.rs b/src/commands/hook_filter.rsindex ae4399744..b81cded34 100644--- a/src/commands/hook_filter.rs+++ b/src/commands/hook_filter.rs@@ -69,4 +69,10 @@ impl<'a> ParsedFilter<'a> {pub(crate) fn matches_source(&self, source: HookSource) -> bool {self.source.is_none() || self.source == Some(source)}++ /// Check if this filter matches a command from the given source.+ pub(crate) fn matches_command(&self, source: HookSource, name: Option<&str>) -> bool {+ self.matches_source(source)+ && (self.name.is_empty() || name.is_some_and(|n| n == self.name))+ }}diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 7d3a67378..0702de687 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -133,7 +133,7 @@ fn prepare_sourced_steps(let is_pipeline = config.is_pipeline();let steps = prepare_steps(config, ctx, extra_vars, hook_type, source)?;for step in steps {- if let Some(filtered) = filter_step_by_name(step, &parsed_filters) {+ if let Some(filtered) = filter_step_by_name(step, source, &parsed_filters) {result.push(SourcedStep {step: filtered,source,@@ -150,24 +150,17 @@ fn prepare_sourced_steps(/// filtered out. A `Concurrent` group reduced to one command collapses to `Single`.fn filter_step_by_name(step: PreparedStep,+ source: HookSource,parsed_filters: &[ParsedFilter<'_>],) -> Option<PreparedStep> {if parsed_filters.is_empty() {return Some(step);}- let filter_names: Vec<&str> = parsed_filters- .iter()- .map(|f| f.name)- .filter(|n| !n.is_empty())- .collect();- if filter_names.is_empty() {- return Some(step);- }let matches = |cmd: &PreparedCommand| {- cmd.name- .as_deref()- .is_some_and(|n| filter_names.contains(&n))+ parsed_filters+ .iter()+ .any(|f| f.matches_command(source, cmd.name.as_deref()))};match step {diff --git a/src/config/approvals.rs b/src/config/approvals.rsindex b9d2bccd4..0a90bd6d6 100644--- a/src/config/approvals.rs+++ b/src/config/approvals.rs@@ -20,6 +20,7 @@//! convenience.use std::collections::BTreeMap;+use std::io::Write;use std::path::{Path, PathBuf};use serde::{Deserialize, Serialize};@@ -31,6 +32,7 @@ use crate::path::format_path_for_display;/// Approved commands, stored in `approvals.toml`.#[derive(Debug, Default, Serialize, Deserialize)]+#[serde(deny_unknown_fields)]pub struct Approvals {#[serde(default)]projects: BTreeMap<String, ApprovedProject>,@@ -38,6 +40,7 @@ pub struct Approvals {/// Per-project approved commands.#[derive(Debug, Default, Serialize, Deserialize, Clone)]+#[serde(deny_unknown_fields)]struct ApprovedProject {#[serde(default,@@ -146,10 +149,9 @@ impl Approvals {impl Approvals {/// Save approvals to a specific file path.pub fn save_to(&self, path: &Path) -> Result<(), ConfigError> {- if let Some(parent) = path.parent() {- std::fs::create_dir_all(parent)- .map_err(|e| ConfigError(format!("Failed to create approvals directory: {e}")))?;- }+ let parent = save_parent(path);+ std::fs::create_dir_all(parent)+ .map_err(|e| ConfigError(format!("Failed to create approvals directory: {e}")))?;let mut doc = toml_edit::DocumentMut::new();@@ -178,13 +180,40 @@ impl Approvals {output};- std::fs::write(path, output)- .map_err(|e| ConfigError(format!("Failed to write approvals file: {e}")))?;+ write_approvals_file(path, &output)?;Ok(())}}+fn save_parent(path: &Path) -> &Path {+ path.parent()+ .filter(|parent| !parent.as_os_str().is_empty())+ .unwrap_or_else(|| Path::new("."))+}++fn write_approvals_file(path: &Path, output: &str) -> Result<(), ConfigError> {+ let parent = save_parent(path);+ let mut temp = tempfile::Builder::new()+ .prefix(".approvals.")+ .suffix(".tmp")+ .tempfile_in(parent)+ .map_err(|e| ConfigError(format!("Failed to create temporary approvals file: {e}")))?;++ temp.write_all(output.as_bytes())+ .map_err(|e| ConfigError(format!("Failed to write temporary approvals file: {e}")))?;+ temp.flush()+ .map_err(|e| ConfigError(format!("Failed to flush temporary approvals file: {e}")))?;+ temp.as_file()+ .sync_all()+ .map_err(|e| ConfigError(format!("Failed to sync temporary approvals file: {e}")))?;++ temp.persist(path)+ .map_err(|e| ConfigError(format!("Failed to replace approvals file: {}", e.error)))?;++ Ok(())+}+// =========================================================================// Queries// =========================================================================@@ -402,6 +431,18 @@ mod tests {Approvals::load_from_file(path)}+ #[cfg(unix)]+ struct WritableOnDrop(PathBuf);++ #[cfg(unix)]+ impl Drop for WritableOnDrop {+ fn drop(&mut self) {+ use std::os::unix::fs::PermissionsExt;++ let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755));+ }+ }+#[test]fn test_empty_approvals() {let approvals = Approvals::default();@@ -542,6 +583,55 @@ mod tests {assert!(loaded.is_command_approved("github.com/user/repo", "npm test"));}+ #[cfg(unix)]+ #[test]+ fn test_save_failure_preserves_existing_file() {+ use std::os::unix::fs::PermissionsExt;++ let temp_dir = TempDir::new().unwrap();+ let approvals_dir = temp_dir.path().join("readonly");+ std::fs::create_dir(&approvals_dir).unwrap();+ let path = approvals_dir.join("approvals.toml");++ let mut original = Approvals::default();+ original.projects.insert(+ "github.com/user/repo".to_string(),+ super::ApprovedProject {+ approved_commands: vec!["npm install".to_string()],+ },+ );+ original.save_to(&path).unwrap();+ let original_content = std::fs::read_to_string(&path).unwrap();++ std::fs::set_permissions(&approvals_dir, std::fs::Permissions::from_mode(0o555)).unwrap();+ let _restore = WritableOnDrop(approvals_dir.clone());+ let test_file = approvals_dir.join("test_write");+ if std::fs::write(&test_file, "test").is_ok() {+ let _ = std::fs::remove_file(test_file);+ return;+ }++ let mut replacement = Approvals::default();+ replacement.projects.insert(+ "github.com/user/repo".to_string(),+ super::ApprovedProject {+ approved_commands: vec!["npm test".to_string()],+ },+ );+ let err = replacement.save_to(&path).unwrap_err();+ assert!(+ err.to_string()+ .contains("Failed to create temporary approvals file"),+ "Expected temporary file creation error, got: {}",+ err+ );++ assert_eq!(std::fs::read_to_string(&path).unwrap(), original_content);+ let loaded = Approvals::load_from_file(&path).unwrap();+ assert!(loaded.is_command_approved("github.com/user/repo", "npm install"));+ assert!(!loaded.is_command_approved("github.com/user/repo", "npm test"));+ }+#[test]fn test_save_format() {let (_temp_dir, path) = test_dir();@@ -709,6 +799,46 @@ approved-commands = ["npm install"]);}+ #[test]+ fn test_load_from_file_rejects_unknown_top_level_key() {+ let temp_dir = TempDir::new().unwrap();+ let path = temp_dir.path().join("approvals.toml");+ std::fs::write(+ &path,+ r#"+[project."github.com/user/repo"]+approved-commands = ["npm test"]+"#,+ )+ .unwrap();+ let err = Approvals::load_from_file(&path).unwrap_err();+ assert!(+ err.to_string().contains("Failed to parse approvals file"),+ "Expected parse error, got: {}",+ err+ );+ }++ #[test]+ fn test_load_from_file_rejects_unknown_project_key() {+ let temp_dir = TempDir::new().unwrap();+ let path = temp_dir.path().join("approvals.toml");+ std::fs::write(+ &path,+ r#"+[projects."github.com/user/repo"]+approved-command = ["npm test"]+"#,+ )+ .unwrap();+ let err = Approvals::load_from_file(&path).unwrap_err();+ assert!(+ err.to_string().contains("Failed to parse approvals file"),+ "Expected parse error, got: {}",+ err+ );+ }+#[test]fn test_load_from_config_file_invalid_toml() {let temp_dir = TempDir::new().unwrap();diff --git a/src/config/deprecation.rs b/src/config/deprecation.rsindex c5cfd89a0..d2a599aae 100644--- a/src/config/deprecation.rs+++ b/src/config/deprecation.rs@@ -1122,15 +1122,18 @@ pub fn migrate_content(content: &str) -> String {////// Called by `wt config update` before overwriting the config with migrated/// content, so the approvals data survives the rewrite. `Ok(None)` for the-/// benign no-op cases (`approvals.toml` already exists, or the config has no-/// approved-commands entries). Returns `Err` when a copy was attempted but-/// failed — the caller must abort before rewriting config.toml, otherwise the-/// legacy approvals are silently lost.+/// benign no-op cases (a valid `approvals.toml` already exists, or the config+/// has no approved-commands entries). Returns `Err` when the existing+/// approvals file cannot be validated or a copy was attempted but failed — the+/// caller must abort before rewriting config.toml, otherwise the legacy+/// approvals are silently lost.pub fn copy_approved_commands_to_approvals_file(config_path: &Path,) -> anyhow::Result<Option<PathBuf>> {let approvals_path = config_path.with_file_name("approvals.toml");+ let _lock = super::user::mutation::acquire_config_lock(&approvals_path)?;if approvals_path.exists() {+ validate_existing_approvals_file(&approvals_path)?;return Ok(None); // Already authoritative, don't overwrite}@@ -1154,6 +1157,22 @@ pub fn copy_approved_commands_to_approvals_file(Ok(Some(approvals_path))}+fn validate_existing_approvals_file(approvals_path: &Path) -> anyhow::Result<()> {+ let content = std::fs::read_to_string(approvals_path).with_context(|| {+ format!(+ "Failed to read existing approvals file {}",+ crate::path::format_path_for_display(approvals_path)+ )+ })?;+ toml::from_str::<super::approvals::Approvals>(&content).with_context(|| {+ format!(+ "Failed to parse existing approvals file {}",+ crate::path::format_path_for_display(approvals_path)+ )+ })?;+ Ok(())+}+/// Merge args array into command string////// Converts: command = "llm", args = ["-m", "haiku"]@@ -3175,6 +3194,32 @@ approved-commands = ["npm install"]assert_eq!(existing, "# existing approvals\n");}+ #[test]+ fn test_copy_approved_commands_errors_when_existing_approvals_invalid() {+ let temp_dir = tempfile::TempDir::new().unwrap();+ let config_path = temp_dir.path().join("config.toml");+ let approvals_path = temp_dir.path().join("approvals.toml");+ let content = r#"+[projects."github.com/user/repo"]+approved-commands = ["npm install"]+"#;+ std::fs::write(&config_path, content).unwrap();+ std::fs::write(&approvals_path, "this is = = not valid toml\n").unwrap();++ let result = copy_approved_commands_to_approvals_file(&config_path);+ assert!(+ result.is_err(),+ "Invalid existing approvals.toml must surface as Err; got {result:?}"+ );+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("Failed to parse existing approvals file"),+ "Error should identify the invalid approvals file"+ );+ }+#[test]fn test_copy_approved_commands_skips_when_empty() {let temp_dir = tempfile::TempDir::new().unwrap();diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 4533febc7..d2867bf0f 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -674,6 +674,36 @@ fn build_template_error(}}+fn sorted_available_vars(vars: &[&str]) -> Vec<String> {+ let mut keys: Vec<String> = vars.iter().map(|k| k.to_string()).collect();+ keys.sort();+ keys.dedup();+ keys+}++fn build_undefined_vars_error(+ name: &str,+ undefined_vars: &[String],+ available_vars: Vec<String>,+) -> TemplateExpandError {+ let names = undefined_vars+ .iter()+ .map(|var| format!("`{var}`"))+ .collect::<Vec<_>>()+ .join(", ");+ let noun = if undefined_vars.len() == 1 {+ "value"+ } else {+ "values"+ };++ TemplateExpandError {+ message: format!("Failed to expand {name}: undefined {noun}: {names}"),+ source_line: None,+ available_vars,+ }+}+/// Set up a minijinja environment with worktrunk's custom filters and functions.////// Shared by [`expand_template`] and [`validate_template`] to ensure both use@@ -824,12 +854,24 @@ pub fn validate_template(.template_from_named_str(name, template).map_err(|e| build_template_error(&e, template, name, Vec::new()))?;+ let mut allowed: BTreeSet<String> = available.iter().map(|k| k.to_string()).collect();+ allowed.insert("vars".to_string());+ let mut undefined: Vec<String> = tmpl+ .undeclared_variables(false)+ .into_iter()+ .filter(|var| !allowed.contains(var))+ .collect();+ undefined.sort();+ if !undefined.is_empty() {+ return Err(build_undefined_vars_error(+ name,+ &undefined,+ sorted_available_vars(&available),+ ));+ }+tmpl.render(minijinja::Value::from_object(context))- .map_err(|e| {- let mut keys: Vec<String> = available.iter().map(|k| k.to_string()).collect();- keys.sort();- build_template_error(&e, template, name, keys)- })?;+ .map_err(|e| build_template_error(&e, template, name, sorted_available_vars(&available)))?;Ok(())}@@ -881,32 +923,6 @@ pub fn expand_template(}}- // Inject vars data as a nested object: {{ vars.env }}, {{ vars.config.port }}- // When branch is present, always inject (even if empty map) so {{ vars.key | default(...) }}- // works in SemiStrict mode. Only look up vars data if the template references it (avoids a- // git process spawn per expansion). JSON objects/arrays are parsed so dot access works- // ({{ vars.config.port }}); plain strings and numbers stay as-is.- //- // Use "vars." to avoid false positives from branch names or URLs containing "vars"- // (e.g., "envvars.internal"). Template access is always `vars.<key>`.- if template.contains("vars.")- && let Some(branch) = vars.get("branch")- {- let entries = repo.vars_entries(branch);- let vars_map: std::collections::BTreeMap<String, Value> = entries- .into_iter()- .map(|(k, v)| {- let value = serde_json::from_str::<serde_json::Value>(&v)- .ok()- .filter(|j| j.is_object() || j.is_array())- .map(|j| Value::from_serialize(&j))- .unwrap_or_else(|| Value::from(v));- (k, value)- })- .collect();- context.insert("vars".to_string(), Value::from_serialize(&vars_map));- }-let mut env = setup_template_env(repo);if shell_escape {// Preserve trailing newlines in templates (important for multiline shell commands)@@ -961,6 +977,32 @@ pub fn expand_template(.template_from_named_str(name, template).map_err(|e| build_template_error(&e, template, name, Vec::new()))?;+ // Inject vars data as a nested object: {{ vars.env }}, {{ vars["env"] }},+ // {{ vars.config.port }}. When branch is present, always inject (even if+ // empty map) so {{ vars.key | default(...) }} works in SemiStrict mode.+ // Only look up vars data if the parsed template references the top-level+ // `vars` object (avoids a git process spawn per expansion while supporting+ // every MiniJinja access form without false positives from literal text).+ // JSON objects/arrays are parsed so nested access works; plain strings and+ // numbers stay as-is.+ if tmpl.undeclared_variables(false).contains("vars")+ && let Some(branch) = vars.get("branch")+ {+ let entries = repo.vars_entries(branch);+ let vars_map: std::collections::BTreeMap<String, Value> = entries+ .into_iter()+ .map(|(k, v)| {+ let value = serde_json::from_str::<serde_json::Value>(&v)+ .ok()+ .filter(|j| j.is_object() || j.is_array())+ .map(|j| Value::from_serialize(&j))+ .unwrap_or_else(|| Value::from(v));+ (k, value)+ })+ .collect();+ context.insert("vars".to_string(), Value::from_serialize(&vars_map));+ }+let result = tmpl.render(minijinja::Value::from_object(context)).map_err(|e| {@@ -1952,6 +1994,21 @@ mod tests {expand_template("{{ vars.env }}", &vars, false, &test.repo, "test").unwrap(),"staging");+ assert_eq!(+ expand_template(r#"{{ vars["env"] }}"#, &vars, false, &test.repo, "test").unwrap(),+ "staging"+ );+ assert_eq!(+ expand_template(+ "{% if vars %}vars loaded{% endif %}",+ &vars,+ false,+ &test.repo,+ "test"+ )+ .unwrap(),+ "vars loaded"+ );assert_eq!(expand_template("{{ vars.port }}", &vars, false, &test.repo, "test").unwrap(),"3000"@@ -2305,6 +2362,21 @@ mod tests {.is_ok());+ // Typos in conditional predicates must not be hidden by SemiStrict truthiness.+ let err = validate_template(+ "{% if targte %}echo {{ target }}{% endif %}",+ ValidationScope::Hook(HookType::PreMerge),+ &test.repo,+ "test",+ )+ .unwrap_err();+ assert!(+ err.message.contains("undefined value"),+ "got: {}",+ err.message+ );+ assert!(err.message.contains("targte"), "got: {}", err.message);+// `pr_number`/`pr_url` are available in pre-start (populated when// creating via `pr:N` / `mr:N`).for var in ["pr_number", "pr_url"] {diff --git a/tests/integration_tests/approval_ui.rs b/tests/integration_tests/approval_ui.rsindex 2c494aef7..39d3d4fa9 100644--- a/tests/integration_tests/approval_ui.rs+++ b/tests/integration_tests/approval_ui.rs@@ -545,6 +545,53 @@ test = "echo 'user test'");}+#[rstest]+fn test_mixed_source_name_filters_do_not_cross_match(repo: TestRepo) {+ repo.write_test_config(+ r#"[pre-merge]+lint = "echo 'user lint' > user_lint.txt"+deploy = "echo 'user deploy' > user_deploy.txt"+"#,+ );+ repo.write_project_config(+ r#"[pre-merge]+lint = "echo 'project lint' > project_lint.txt"+deploy = "echo 'project deploy' > project_deploy.txt"+"#,+ );+ repo.commit("Add pre-merge hooks");++ let output = repo+ .wt_command()+ .args(["--yes", "hook", "pre-merge", "project:deploy", "user:lint"])+ .env("NO_COLOR", "1")+ .output()+ .expect("Failed to run wt hook pre-merge");++ assert!(+ output.status.success(),+ "wt hook pre-merge failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ assert_eq!(+ fs::read_to_string(repo.root_path().join("project_deploy.txt")).unwrap(),+ "project deploy\n"+ );+ assert_eq!(+ fs::read_to_string(repo.root_path().join("user_lint.txt")).unwrap(),+ "user lint\n"+ );+ assert!(+ !repo.root_path().join("project_lint.txt").exists(),+ "project lint should not run for a user-scoped lint filter"+ );+ assert!(+ !repo.root_path().join("user_deploy.txt").exists(),+ "user deploy should not run for a project-scoped deploy filter"+ );+}+#[rstest]fn test_step_hook_run_all_commands(repo: TestRepo) {// Config with multiple named commands