diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index 7b2b900324..6e00708a9c 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -748,6 +748,46 @@ async fn apply_patch_cli_reports_missing_context() -> Result<()> { Ok(()) } +#[cfg(windows)] +#[test_case("cmd.exe /c 'echo patch denied 1>&2 & exit /b 2'"; "native")] +#[test_case("end { [Console]::Error.WriteLine('patch denied'); exit 2 }"; "named block")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn powershell_hook_denies_patch_before_approval(command: &'static str) -> Result<()> { + skip_if_no_network!(Ok(())); + + let harness = apply_patch_harness_with(|builder| { + builder + .with_pre_build_hook(move |home| { + let hooks = json!({"hooks": {"PreToolUse": [{ + "matcher": "^apply_patch$", + "hooks": [{"type": "command", "command": command}] + }]}}); + fs::write(home.join("hooks.json"), hooks.to_string()).expect("write hook"); + }) + .with_config(core_test_support::hooks::trust_discovered_hooks) + }) + .await?; + let call_id = "denied-patch"; + let patch = "*** Begin Patch\n*** Add File: denied.txt\n+blocked\n*** End Patch"; + mount_apply_patch(&harness, call_id, patch, "done").await; + harness + .test() + .submit_turn_with_policies( + "apply the patch", + AskForApproval::OnRequest, + SandboxPolicy::new_read_only_policy(), + ) + .await?; + + let output = harness.apply_patch_output(call_id).await; + assert!( + output.contains("Command blocked by PreToolUse hook: patch denied"), + "{output}" + ); + assert!(!harness.path_exists("denied.txt").await?); + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn apply_patch_cli_reports_missing_target_file() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/hooks/src/engine/command_runner.rs b/codex-rs/hooks/src/engine/command_runner.rs index 6e00dd3bf4..668b19a3c3 100644 --- a/codex-rs/hooks/src/engine/command_runner.rs +++ b/codex-rs/hooks/src/engine/command_runner.rs @@ -469,6 +469,43 @@ fn build_command( #[cfg(windows)] if shell.program.is_empty() || shell.args.iter().any(|arg| arg.eq_ignore_ascii_case("/c")) { command.raw_arg(format!(r#""{command_line}""#)); + } else if shell + .args + .last() + .is_some_and(|arg| arg.eq_ignore_ascii_case("-Command")) + { + // PowerShell forbids top-level statements after named blocks. Look past + // leading comments and declarations, but not into native command arguments. + let mut script = command_line.trim_start(); + while let Some((_, rest)) = if script.starts_with('#') { + script.split_once('\n') + } else if script.starts_with("<#") { + script.split_once("#>") + } else { + None + } { + script = rest.trim_start(); + } + let mut words = script + .split(|c: char| c.is_whitespace() || matches!(c, '{' | '(' | ')' | ';' | '<' | '>')); + let first = words.next().unwrap_or_default(); + let named_block = |word: &str| { + ["begin", "process", "end", "clean", "dynamicparam"] + .iter() + .any(|name| word.eq_ignore_ascii_case(name)) + }; + let declaration = first.eq_ignore_ascii_case("param") + || first.eq_ignore_ascii_case("using") + || script.starts_with('['); + if script.contains('{') && (named_block(first) || (declaration && words.any(named_block))) { + command.arg(command_line); + } else { + // PowerShell -Command reduces native failures to 1. Check $? first so a + // successful hook doesn't inherit an earlier command's failure. + command.arg(format!( + "{command_line}\nif ($?) {{ exit 0 }}\nif ($LASTEXITCODE) {{ exit $LASTEXITCODE }}\nexit 1" + )); + } } else { command.arg(command_line); }