diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs index 8e2757259f..c3abb7273f 100644 --- a/codex-rs/core/src/exec_policy.rs +++ b/codex-rs/core/src/exec_policy.rs @@ -258,80 +258,88 @@ impl ExecPolicyManager { .filter(|commands| !commands.is_empty()); #[cfg(not(windows))] let powershell_commands: Option>> = None; - let (commands, used_complex_parsing) = if let Some(commands) = powershell_commands.clone() { - (commands, false) - } else { - commands_for_exec_policy(original_command) - }; - // Keep heredoc prefix parsing for rule evaluation so existing - // allow/prompt/forbidden rules still apply, but avoid auto-derived - // amendments when only the heredoc fallback parser matched. - let auto_amendment_allowed = !used_complex_parsing; - let exec_policy_fallback = |parsed_command: &[String]| { - #[cfg(windows)] - let command_for_heuristics = if powershell_commands.is_some() { - original_command - } else { - parsed_command - }; - #[cfg(not(windows))] - let command_for_heuristics = parsed_command; - render_decision_for_unmatched_command( - approval_policy, - &permission_profile, - file_system_sandbox_policy, - sandbox_cwd, - command_for_heuristics, - sandbox_permissions, - used_complex_parsing, - ) - }; let match_options = MatchOptions { resolve_host_executables: true, }; - let mut evaluation = exec_policy.check_multiple_with_options( - commands.iter(), - &exec_policy_fallback, - &match_options, - ); - - #[cfg(windows)] - if powershell_commands.is_some() { - let outer_policy_matches = exec_policy.matches_for_command_with_options( - original_command, - /*heuristics_fallback*/ None, - &match_options, - ); - if outer_policy_matches.is_empty() { - for rule_match in &mut evaluation.matched_rules { - if let RuleMatch::HeuristicsRuleMatch { - command: matched_command, - .. - } = rule_match - { - *matched_command = original_command.to_vec(); - } - } - } else { - evaluation.matched_rules.retain(is_policy_match); - evaluation.matched_rules.extend(outer_policy_matches); + let (evaluation, requested_amendment, used_complex_parsing) = + if let Some(powershell_commands) = powershell_commands.as_ref() { + // PowerShell wrappers have two useful views: the outer argv for + // heuristics and wrapper-targeted rules, and the recovered + // inner commands for explicit prefix matching. + let exec_policy_fallback = |_: &[String]| { + render_decision_for_unmatched_command( + approval_policy, + &permission_profile, + file_system_sandbox_policy, + sandbox_cwd, + original_command, + sandbox_permissions, + /*used_complex_parsing*/ false, + ) + }; + let mut evaluation = exec_policy.check_multiple_with_options( + powershell_commands.iter(), + &exec_policy_fallback, + &match_options, + ); + evaluation + .matched_rules + .extend(exec_policy.matches_for_command_with_options( + original_command, + /*heuristics_fallback*/ None, + &match_options, + )); evaluation.decision = evaluation .matched_rules .iter() .map(RuleMatch::decision) .max() .expect("invariant failed: matched_rules must be non-empty"); - } - } - let requested_amendment = derive_requested_execpolicy_amendment_from_prefix_rule( - prefix_rule.as_ref(), - &evaluation.matched_rules, - exec_policy.as_ref(), - &commands, - &exec_policy_fallback, - &match_options, - ); + let requested_amendment = + derive_requested_execpolicy_amendment_from_prefix_rule_for_powershell( + prefix_rule.as_ref(), + &evaluation.matched_rules, + exec_policy.as_ref(), + powershell_commands, + &match_options, + ); + (evaluation, requested_amendment, false) + } else { + let (commands, used_complex_parsing) = commands_for_exec_policy(original_command); + let exec_policy_fallback = |parsed_command: &[String]| { + render_decision_for_unmatched_command( + approval_policy, + &permission_profile, + file_system_sandbox_policy, + sandbox_cwd, + parsed_command, + sandbox_permissions, + used_complex_parsing, + ) + }; + let evaluation = exec_policy.check_multiple_with_options( + commands.iter(), + &exec_policy_fallback, + &match_options, + ); + let requested_amendment = derive_requested_execpolicy_amendment_from_prefix_rule( + prefix_rule.as_ref(), + &evaluation.matched_rules, + exec_policy.as_ref(), + &commands, + &exec_policy_fallback, + &match_options, + ); + (evaluation, requested_amendment, used_complex_parsing) + }; + // Keep heredoc prefix parsing for rule evaluation so existing + // allow/prompt/forbidden rules still apply, but avoid auto-derived + // amendments when only the heredoc fallback parser matched. + let auto_amendment_allowed = !used_complex_parsing; + let auto_prompt_amendment_allowed = auto_amendment_allowed + && !(powershell_commands.is_some() + && evaluation.matched_rules.iter().any(is_policy_match)); match evaluation.decision { Decision::Forbidden => ExecApprovalRequirement::Forbidden { @@ -348,7 +356,7 @@ impl ExecPolicyManager { None => ExecApprovalRequirement::NeedsApproval { reason: derive_prompt_reason(original_command, &evaluation), proposed_execpolicy_amendment: requested_amendment.or_else(|| { - if auto_amendment_allowed { + if auto_prompt_amendment_allowed { try_derive_execpolicy_amendment_for_prompt_rules( &evaluation.matched_rules, ) @@ -808,6 +816,16 @@ fn try_derive_execpolicy_amendment_for_allow_rules( }) } +fn prefix_rule_is_banned(prefix_rule: &[String]) -> bool { + BANNED_PREFIX_SUGGESTIONS.iter().any(|banned| { + prefix_rule.len() == banned.len() + && prefix_rule + .iter() + .map(String::as_str) + .eq(banned.iter().copied()) + }) +} + fn derive_requested_execpolicy_amendment_from_prefix_rule( prefix_rule: Option<&Vec>, matched_rules: &[RuleMatch], @@ -820,13 +838,7 @@ fn derive_requested_execpolicy_amendment_from_prefix_rule( if prefix_rule.is_empty() { return None; } - if BANNED_PREFIX_SUGGESTIONS.iter().any(|banned| { - prefix_rule.len() == banned.len() - && prefix_rule - .iter() - .map(String::as_str) - .eq(banned.iter().copied()) - }) { + if prefix_rule_is_banned(prefix_rule) { return None; } @@ -849,6 +861,48 @@ fn derive_requested_execpolicy_amendment_from_prefix_rule( } } +fn derive_requested_execpolicy_amendment_from_prefix_rule_for_powershell( + prefix_rule: Option<&Vec>, + matched_rules: &[RuleMatch], + exec_policy: &Policy, + powershell_commands: &[Vec], + match_options: &MatchOptions, +) -> Option { + let prefix_rule = prefix_rule?; + if prefix_rule.is_empty() { + return None; + } + if prefix_rule_is_banned(prefix_rule) { + return None; + } + + if matched_rules.iter().any(is_policy_match) { + return None; + } + + let amendment = ExecPolicyAmendment::new(prefix_rule.clone()); + let mut policy_with_prefix_rule = exec_policy.clone(); + if policy_with_prefix_rule + .add_prefix_rule(&amendment.command, Decision::Allow) + .is_err() + { + return None; + } + + powershell_commands + .iter() + .all(|command| { + let matched_rules = policy_with_prefix_rule.matches_for_command_with_options( + command, + /*heuristics_fallback*/ None, + match_options, + ); + !matched_rules.is_empty() + && matched_rules.iter().map(RuleMatch::decision).max() == Some(Decision::Allow) + }) + .then_some(amendment) +} + fn prefix_rule_would_approve_all_commands( exec_policy: &Policy, prefix_rule: &[String], diff --git a/codex-rs/core/src/exec_policy_tests.rs b/codex-rs/core/src/exec_policy_tests.rs index 990e729b4a..214d132356 100644 --- a/codex-rs/core/src/exec_policy_tests.rs +++ b/codex-rs/core/src/exec_policy_tests.rs @@ -837,6 +837,35 @@ async fn allow_rule_matches_powershell_wrapped_inner_commands() { .await; } +#[cfg(windows)] +#[tokio::test] +async fn powershell_outer_allow_does_not_override_unmatched_wrapper_prompt() { + assert_exec_approval_requirement_for_command( + ExecApprovalRequirementScenario { + policy_src: Some( + r#"prefix_rule(pattern=["powershell.exe"], decision="allow")"#.to_string(), + ), + command: vec_str(&[ + "powershell.exe", + "-WindowStyle", + "Hidden", + "-Command", + "Get-Content Cargo.toml", + ]), + approval_policy: AskForApproval::OnRequest, + sandbox_policy: SandboxPolicy::new_read_only_policy(), + file_system_sandbox_policy: read_only_file_system_sandbox_policy(), + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }, + ExecApprovalRequirement::NeedsApproval { + reason: None, + proposed_execpolicy_amendment: None, + }, + ) + .await; +} + #[test] fn commands_for_exec_policy_falls_back_for_empty_shell_script() { let command = vec!["bash".to_string(), "-lc".to_string(), "".to_string()]; @@ -1920,6 +1949,53 @@ fn derive_requested_execpolicy_amendment_allows_non_exact_banned_prefix_rule_mat ); } +#[test] +fn derive_requested_execpolicy_amendment_for_powershell_uses_inner_commands() { + let prefix_rule = vec!["git".to_string(), "push".to_string()]; + let powershell_commands = vec![vec![ + "git".to_string(), + "push".to_string(), + "origin".to_string(), + "main".to_string(), + ]]; + + assert_eq!( + Some(ExecPolicyAmendment::new(prefix_rule.clone())), + derive_requested_execpolicy_amendment_from_prefix_rule_for_powershell( + Some(&prefix_rule), + &[], + &Policy::empty(), + &powershell_commands, + &MatchOptions::default(), + ) + ); +} + +#[test] +fn derive_requested_execpolicy_amendment_for_powershell_requires_all_inner_commands_to_match() { + let prefix_rule = vec!["git".to_string(), "push".to_string()]; + let powershell_commands = vec![ + vec![ + "git".to_string(), + "push".to_string(), + "origin".to_string(), + "main".to_string(), + ], + vec!["whoami".to_string()], + ]; + + assert_eq!( + None, + derive_requested_execpolicy_amendment_from_prefix_rule_for_powershell( + Some(&prefix_rule), + &[], + &Policy::empty(), + &powershell_commands, + &MatchOptions::default(), + ) + ); +} + #[test] fn derive_requested_execpolicy_amendment_returns_none_when_policy_matches() { let prefix_rule = vec!["cargo".to_string(), "build".to_string()]; diff --git a/codex-rs/shell-command/src/powershell.rs b/codex-rs/shell-command/src/powershell.rs index acbddb8279..7941aab79e 100644 --- a/codex-rs/shell-command/src/powershell.rs +++ b/codex-rs/shell-command/src/powershell.rs @@ -91,8 +91,7 @@ pub fn try_parse_powershell_command_sequence( ) -> Option>> { let (executable, args) = command.split_first()?; if is_powershell_executable(executable) { - let parser_executable = trusted_powershell_parser_executable(executable)?; - parse_powershell_invocation(&parser_executable, args, mode) + parse_powershell_invocation(executable, args, mode) } else { None } @@ -179,22 +178,6 @@ pub(crate) fn parse_powershell_script_to_commands( try_parse_powershell_ast_commands(executable, script) } -fn trusted_powershell_parser_executable(exe: &str) -> Option { - let executable_name = std::path::Path::new(exe) - .file_name() - .and_then(|osstr| osstr.to_str()) - .unwrap_or(exe) - .to_ascii_lowercase(); - - let parser_executable = match executable_name.as_str() { - "powershell" | "powershell.exe" => try_find_powershell_executable_blocking()?, - "pwsh" | "pwsh.exe" => try_find_pwsh_executable_blocking()?, - _ => return None, - }; - - Some(parser_executable.as_path().to_string_lossy().into_owned()) -} - pub(crate) fn is_powershell_executable(exe: &str) -> bool { let executable_name = std::path::Path::new(exe) .file_name() @@ -433,26 +416,4 @@ mod tests { ]), ); } - - #[cfg(windows)] - #[test] - fn uses_trusted_system_powershell_for_ast_parsing() { - let command = vec![ - r"C:\repo\powershell.exe".to_string(), - "-NoExit".to_string(), - "-Command".to_string(), - "Get-Content Cargo.toml".to_string(), - ]; - - assert_eq!( - try_parse_powershell_command_sequence( - &command, - PowershellCommandSequenceParseMode::ExecPolicy, - ), - Some(vec![vec![ - "Get-Content".to_string(), - "Cargo.toml".to_string(), - ]]), - ); - } }