Compare commits

...

3 Commits

Author SHA1 Message Date
David Wiesen
3e671ee6e0 Reuse PowerShell parsing for execpolicy matching 2026-03-22 21:50:43 -07:00
David Wiesen
9152876b6b Normalize intercepted PowerShell execpolicy commands 2026-03-22 21:46:22 -07:00
David Wiesen
9f076192d8 Normalize simple PowerShell execpolicy commands 2026-03-22 21:46:22 -07:00
5 changed files with 197 additions and 11 deletions

View File

@@ -33,9 +33,12 @@ use tracing::instrument;
use crate::bash::parse_shell_lc_plain_commands;
use crate::bash::parse_shell_lc_single_command_prefix;
use crate::config::Config;
use crate::powershell::extract_powershell_command;
use crate::sandboxing::SandboxPermissions;
use crate::tools::sandboxing::ExecApprovalRequirement;
use codex_shell_command::command_safety::windows_safe_commands::parse_powershell_command_sequence;
use codex_utils_absolute_path::AbsolutePathBuf;
use shlex::split as shlex_split;
use shlex::try_join as shlex_try_join;
const PROMPT_CONFLICT_REASON: &str =
@@ -627,13 +630,45 @@ fn commands_for_exec_policy(command: &[String]) -> (Vec<Vec<String>>, bool) {
return (commands, false);
}
if let Some(commands) = parse_powershell_command_sequence(command)
&& !commands.is_empty()
{
return (commands, false);
}
if let Some(single_command) = parse_shell_lc_single_command_prefix(command) {
return (vec![single_command], true);
}
if let Some(single_command) = parse_powershell_plain_command(command) {
return (vec![single_command], false);
}
(vec![command.to_vec()], false)
}
fn parse_powershell_plain_command(command: &[String]) -> Option<Vec<String>> {
let (_, script) = extract_powershell_command(command)?;
let script = script.trim();
if script.is_empty() {
return None;
}
// Only normalize simple wrapper cases where the PowerShell script is
// effectively a plain external command invocation. Anything that looks like
// real PowerShell syntax should continue to use the opaque argv form.
if script.chars().any(|c| {
matches!(
c,
'\n' | '\r' | ';' | '|' | '&' | '(' | ')' | '{' | '}' | '$' | '@' | '`' | '<' | '>'
)
}) {
return None;
}
shlex_split(script).filter(|tokens| !tokens.is_empty())
}
/// Derive a proposed execpolicy amendment when a command requires user approval
/// - If any execpolicy rule prompts, return None, because an amendment would not skip that policy requirement.
/// - Otherwise return the first heuristics Prompt.

View File

@@ -590,6 +590,73 @@ async fn evaluates_heredoc_script_against_prefix_rules() {
);
}
#[tokio::test]
async fn powershell_wrapped_plain_command_matches_prefix_rules() {
let policy_src = r#"prefix_rule(pattern=["git", "add"], decision="allow")"#;
let mut parser = PolicyParser::new();
parser
.parse("test.rules", policy_src)
.expect("parse policy");
let policy = Arc::new(parser.build());
let command = vec![
"pwsh".to_string(),
"-NoProfile".to_string(),
"-Command".to_string(),
"git add -A".to_string(),
];
let requirement = ExecPolicyManager::new(policy)
.create_exec_approval_requirement_for_command(ExecApprovalRequest {
command: &command,
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,
})
.await;
assert_eq!(
requirement,
ExecApprovalRequirement::Skip {
bypass_sandbox: true,
proposed_execpolicy_amendment: None,
}
);
}
#[tokio::test]
async fn requested_prefix_rule_can_approve_powershell_wrapped_plain_commands() {
let command = vec![
"pwsh".to_string(),
"-NoProfile".to_string(),
"-Command".to_string(),
"git add -A".to_string(),
];
let requirement = ExecPolicyManager::default()
.create_exec_approval_requirement_for_command(ExecApprovalRequest {
command: &command,
approval_policy: AskForApproval::UnlessTrusted,
sandbox_policy: &SandboxPolicy::new_read_only_policy(),
file_system_sandbox_policy: &read_only_file_system_sandbox_policy(),
sandbox_permissions: SandboxPermissions::UseDefault,
prefix_rule: Some(vec!["git".to_string(), "add".to_string()]),
})
.await;
assert_eq!(
requirement,
ExecApprovalRequirement::NeedsApproval {
reason: None,
proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![
"git".to_string(),
"add".to_string(),
])),
}
);
}
#[tokio::test]
async fn omits_auto_amendment_for_heredoc_fallback_prompts() {
let command = vec![

View File

@@ -19,6 +19,7 @@ use crate::tools::sandboxing::SandboxAttempt;
use crate::tools::sandboxing::SandboxablePreference;
use crate::tools::sandboxing::ToolCtx;
use crate::tools::sandboxing::ToolError;
use crate::powershell::extract_powershell_command;
use codex_execpolicy::Decision;
use codex_execpolicy::Evaluation;
use codex_execpolicy::MatchOptions;
@@ -53,6 +54,7 @@ use codex_utils_absolute_path::AbsolutePathBuf;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use shlex::split as shlex_split;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio_util::sync::CancellationToken;
@@ -766,10 +768,16 @@ fn evaluate_intercepted_exec_policy(
sandbox_permissions,
enable_shell_wrapper_parsing,
} = context;
let wrapper_command = join_program_and_argv(program, argv);
let CandidateCommands {
commands,
used_complex_parsing,
} = if enable_shell_wrapper_parsing {
} = if let Some(command) = parse_powershell_plain_command(&wrapper_command) {
CandidateCommands {
commands: vec![command],
used_complex_parsing: false,
}
} else if enable_shell_wrapper_parsing {
// In this codepath, the first argument in `commands` could be a bare
// name like `find` instead of an absolute path like `/usr/bin/find`.
// It could also be a shell built-in like `echo`.
@@ -778,7 +786,7 @@ fn evaluate_intercepted_exec_policy(
// In this codepath, `commands` has a single entry where the program
// is always an absolute path.
CandidateCommands {
commands: vec![join_program_and_argv(program, argv)],
commands: vec![wrapper_command],
used_complex_parsing: false,
}
};
@@ -821,19 +829,22 @@ fn commands_for_intercepted_exec_policy(
program: &AbsolutePathBuf,
argv: &[String],
) -> CandidateCommands {
if let [_, flag, script] = argv {
let shell_command = [
program.to_string_lossy().to_string(),
flag.clone(),
script.clone(),
];
if let Some(commands) = parse_shell_lc_plain_commands(&shell_command) {
let wrapper_command = join_program_and_argv(program, argv);
if let Some(command) = parse_powershell_plain_command(&wrapper_command) {
return CandidateCommands {
commands: vec![command],
used_complex_parsing: false,
};
}
if argv.len() == 3 {
if let Some(commands) = parse_shell_lc_plain_commands(&wrapper_command) {
return CandidateCommands {
commands,
used_complex_parsing: false,
};
}
if let Some(single_command) = parse_shell_lc_single_command_prefix(&shell_command) {
if let Some(single_command) = parse_shell_lc_single_command_prefix(&wrapper_command) {
return CandidateCommands {
commands: vec![single_command],
used_complex_parsing: true,
@@ -842,11 +853,33 @@ fn commands_for_intercepted_exec_policy(
}
CandidateCommands {
commands: vec![join_program_and_argv(program, argv)],
commands: vec![wrapper_command],
used_complex_parsing: false,
}
}
fn parse_powershell_plain_command(command: &[String]) -> Option<Vec<String>> {
let (_, script) = extract_powershell_command(command)?;
let script = script.trim();
if script.is_empty() {
return None;
}
// Only normalize simple external-command wrappers. Anything that looks like
// actual PowerShell syntax should remain opaque and rely on the exact
// wrapper argv.
if script.chars().any(|c| {
matches!(
c,
'\n' | '\r' | ';' | '|' | '&' | '(' | ')' | '{' | '}' | '$' | '@' | '`' | '<' | '>'
)
}) {
return None;
}
shlex_split(script).filter(|tokens| !tokens.is_empty())
}
struct CoreShellCommandExecutor {
command: Vec<String>,
cwd: PathBuf,

View File

@@ -519,6 +519,51 @@ fn evaluate_intercepted_exec_policy_matches_inner_shell_commands_when_enabled()
);
}
#[test]
fn evaluate_intercepted_exec_policy_matches_simple_powershell_wrapped_commands() {
let policy_src = r#"prefix_rule(pattern = ["git", "add"], decision = "allow")"#;
let mut parser = PolicyParser::new();
parser.parse("test.rules", policy_src).unwrap();
let policy = parser.build();
let program = AbsolutePathBuf::try_from(if cfg!(windows) {
r"C:\Program Files\PowerShell\7\pwsh.exe".to_string()
} else {
"/usr/local/bin/pwsh".to_string()
})
.unwrap();
let evaluation = evaluate_intercepted_exec_policy(
&policy,
&program,
&[
"pwsh".to_string(),
"-NoProfile".to_string(),
"-Command".to_string(),
"git add -A".to_string(),
],
InterceptedExecPolicyContext {
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,
enable_shell_wrapper_parsing: false,
},
);
assert_eq!(
evaluation,
Evaluation {
decision: Decision::Allow,
matched_rules: vec![RuleMatch::PrefixRuleMatch {
matched_prefix: vec!["git".to_string(), "add".to_string()],
decision: Decision::Allow,
resolved_program: None,
justification: None,
}],
}
);
}
#[test]
fn intercepted_exec_policy_uses_host_executable_mappings() {
let git_path = host_absolute_path(&["usr", "bin", "git"]);

View File

@@ -31,6 +31,12 @@ fn try_parse_powershell_command_sequence(command: &[String]) -> Option<Vec<Vec<S
}
}
/// Parse a PowerShell wrapper into the underlying command sequence when the
/// script is simple enough to recover stable argv tokens.
pub fn parse_powershell_command_sequence(command: &[String]) -> Option<Vec<Vec<String>>> {
try_parse_powershell_command_sequence(command)
}
/// Parses a PowerShell invocation into discrete command vectors, rejecting unsafe patterns.
fn parse_powershell_invocation(executable: &str, args: &[String]) -> Option<Vec<Vec<String>>> {
if args.is_empty() {