first pass at integrating execpolicy2 into codex

This commit is contained in:
kevin zhao
2025-11-13 22:14:13 -05:00
parent bdb5210721
commit 24a9b7ba28
15 changed files with 537 additions and 52 deletions
@@ -300,6 +300,11 @@ impl ShellHandler {
env: exec_params.env.clone(),
with_escalated_permissions: exec_params.with_escalated_permissions,
justification: exec_params.justification.clone(),
exec_policy: if is_user_shell_command {
None
} else {
turn.exec_policy_v2.clone()
},
};
let mut orchestrator = ToolOrchestrator::new();
let mut runtime = ShellRuntime::new();
+38 -28
View File
@@ -11,6 +11,7 @@ use crate::error::get_error_message_ui;
use crate::exec::ExecToolCallOutput;
use crate::sandboxing::SandboxManager;
use crate::tools::sandboxing::ApprovalCtx;
use crate::tools::sandboxing::ApprovalRequirement;
use crate::tools::sandboxing::ProvidesSandboxRetryData;
use crate::tools::sandboxing::SandboxAttempt;
use crate::tools::sandboxing::ToolCtx;
@@ -49,40 +50,49 @@ impl ToolOrchestrator {
let otel_cfg = codex_otel::otel_event_manager::ToolDecisionSource::Config;
// 1) Approval
let needs_initial_approval =
tool.wants_initial_approval(req, approval_policy, &turn_ctx.sandbox_policy);
let mut already_approved = false;
if needs_initial_approval {
let mut risk = None;
if let Some(metadata) = req.sandbox_retry_data() {
risk = tool_ctx
.session
.assess_sandbox_command(turn_ctx, &tool_ctx.call_id, &metadata.command, None)
.await;
match tool.approval_requirement(req, approval_policy, &turn_ctx.sandbox_policy) {
ApprovalRequirement::Skip => {
otel.tool_decision(otel_tn, otel_ci, ReviewDecision::Approved, otel_cfg);
}
ApprovalRequirement::Forbidden { reason } => {
return Err(ToolError::Rejected(reason));
}
ApprovalRequirement::NeedsApproval { reason } => {
let mut risk = None;
let approval_ctx = ApprovalCtx {
session: tool_ctx.session,
turn: turn_ctx,
call_id: &tool_ctx.call_id,
retry_reason: None,
risk,
};
let decision = tool.start_approval_async(req, approval_ctx).await;
otel.tool_decision(otel_tn, otel_ci, decision, otel_user.clone());
match decision {
ReviewDecision::Denied | ReviewDecision::Abort => {
return Err(ToolError::Rejected("rejected by user".to_string()));
if let Some(metadata) = req.sandbox_retry_data() {
risk = tool_ctx
.session
.assess_sandbox_command(
turn_ctx,
&tool_ctx.call_id,
&metadata.command,
None,
)
.await;
}
ReviewDecision::Approved | ReviewDecision::ApprovedForSession => {}
let approval_ctx = ApprovalCtx {
session: tool_ctx.session,
turn: turn_ctx,
call_id: &tool_ctx.call_id,
retry_reason: reason,
risk,
};
let decision = tool.start_approval_async(req, approval_ctx).await;
otel.tool_decision(otel_tn, otel_ci, decision, otel_user.clone());
match decision {
ReviewDecision::Denied | ReviewDecision::Abort => {
return Err(ToolError::Rejected("rejected by user".to_string()));
}
ReviewDecision::Approved | ReviewDecision::ApprovedForSession => {}
}
already_approved = true;
}
already_approved = true;
} else {
otel.tool_decision(otel_tn, otel_ci, ReviewDecision::Approved, otel_cfg);
}
// 2) First attempt under the selected sandbox.
+114 -8
View File
@@ -6,11 +6,13 @@ builds a CommandSpec, and runs it under the current SandboxAttempt.
*/
use crate::command_safety::is_dangerous_command::requires_initial_appoval;
use crate::exec::ExecToolCallOutput;
use crate::exec_policy::evaluate_with_policy;
use crate::protocol::SandboxPolicy;
use crate::sandboxing::execute_env;
use crate::tools::runtimes::build_command_spec;
use crate::tools::sandboxing::Approvable;
use crate::tools::sandboxing::ApprovalCtx;
use crate::tools::sandboxing::ApprovalRequirement;
use crate::tools::sandboxing::ProvidesSandboxRetryData;
use crate::tools::sandboxing::SandboxAttempt;
use crate::tools::sandboxing::SandboxRetryData;
@@ -20,10 +22,12 @@ use crate::tools::sandboxing::ToolCtx;
use crate::tools::sandboxing::ToolError;
use crate::tools::sandboxing::ToolRuntime;
use crate::tools::sandboxing::with_cached_approval;
use codex_execpolicy2::Policy as ExecPolicyV2;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::ReviewDecision;
use futures::future::BoxFuture;
use std::path::PathBuf;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct ShellRequest {
@@ -33,6 +37,7 @@ pub struct ShellRequest {
pub env: std::collections::HashMap<String, String>,
pub with_escalated_permissions: Option<bool>,
pub justification: Option<String>,
pub exec_policy: Option<Arc<ExecPolicyV2>>,
}
impl ProvidesSandboxRetryData for ShellRequest {
@@ -66,6 +71,24 @@ impl ShellRuntime {
tx_event: ctx.session.get_tx_event(),
})
}
fn base_approval_requirement(
&self,
req: &ShellRequest,
policy: AskForApproval,
sandbox_policy: &SandboxPolicy,
) -> ApprovalRequirement {
if requires_initial_appoval(
policy,
sandbox_policy,
&req.command,
req.with_escalated_permissions.unwrap_or(false),
) {
ApprovalRequirement::NeedsApproval { reason: None }
} else {
ApprovalRequirement::Skip
}
}
}
impl Sandboxable for ShellRuntime {
@@ -114,18 +137,19 @@ impl Approvable<ShellRequest> for ShellRuntime {
})
}
fn wants_initial_approval(
fn approval_requirement(
&self,
req: &ShellRequest,
policy: AskForApproval,
sandbox_policy: &SandboxPolicy,
) -> bool {
requires_initial_appoval(
policy,
sandbox_policy,
&req.command,
req.with_escalated_permissions.unwrap_or(false),
)
) -> ApprovalRequirement {
if let Some(exec_policy) = &req.exec_policy
&& let Some(requirement) = evaluate_with_policy(exec_policy, &req.command, policy)
{
return requirement;
}
self.base_approval_requirement(req, policy, sandbox_policy)
}
fn wants_escalated_first_attempt(&self, req: &ShellRequest) -> bool {
@@ -157,3 +181,85 @@ impl ToolRuntime<ShellRequest, ExecToolCallOutput> for ShellRuntime {
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
use codex_execpolicy2::PolicyParser;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
fn parse_policy(src: &str) -> Arc<ExecPolicyV2> {
let mut parser = PolicyParser::new();
parser
.parse("test.codexpolicy", src)
.expect("parse execpolicy2 file");
Arc::new(parser.build())
}
fn shell_request(command: &[&str], exec_policy: Option<Arc<ExecPolicyV2>>) -> ShellRequest {
ShellRequest {
command: command.iter().map(ToString::to_string).collect(),
cwd: PathBuf::from("."),
timeout_ms: None,
env: HashMap::new(),
with_escalated_permissions: None,
justification: None,
exec_policy,
}
}
#[test]
fn prompt_decision_requires_approval() {
let policy = parse_policy(r#"prefix_rule(pattern=["echo"], decision="prompt")"#);
let req = shell_request(&["echo", "hi"], Some(policy));
let runtime = ShellRuntime::new();
let requirement = runtime.approval_requirement(
&req,
AskForApproval::OnRequest,
&SandboxPolicy::DangerFullAccess,
);
assert_eq!(
requirement,
ApprovalRequirement::NeedsApproval {
reason: Some("execpolicy requires approval for this command".to_string())
}
);
}
#[test]
fn prompt_blocked_when_approval_disabled() {
let policy = parse_policy(r#"prefix_rule(pattern=["echo"], decision="prompt")"#);
let req = shell_request(&["echo", "hi"], Some(policy));
let runtime = ShellRuntime::new();
let requirement = runtime.approval_requirement(
&req,
AskForApproval::Never,
&SandboxPolicy::DangerFullAccess,
);
assert_eq!(
requirement,
ApprovalRequirement::Forbidden {
reason: "execpolicy requires approval for this command".to_string()
}
);
}
#[test]
fn user_shell_commands_skip_execpolicy() {
let req = shell_request(&["echo", "hi"], None);
let runtime = ShellRuntime::new();
let requirement = runtime.approval_requirement(
&req,
AskForApproval::OnRequest,
&SandboxPolicy::DangerFullAccess,
);
assert_eq!(requirement, ApprovalRequirement::Skip);
}
}
@@ -1,4 +1,5 @@
use crate::command_safety::is_dangerous_command::requires_initial_appoval;
use crate::exec_policy::evaluate_with_policy;
/*
Runtime: unified exec
@@ -10,6 +11,7 @@ use crate::error::SandboxErr;
use crate::tools::runtimes::build_command_spec;
use crate::tools::sandboxing::Approvable;
use crate::tools::sandboxing::ApprovalCtx;
use crate::tools::sandboxing::ApprovalRequirement;
use crate::tools::sandboxing::ProvidesSandboxRetryData;
use crate::tools::sandboxing::SandboxAttempt;
use crate::tools::sandboxing::SandboxRetryData;
@@ -22,18 +24,21 @@ use crate::tools::sandboxing::with_cached_approval;
use crate::unified_exec::UnifiedExecError;
use crate::unified_exec::UnifiedExecSession;
use crate::unified_exec::UnifiedExecSessionManager;
use codex_execpolicy2::Policy as ExecPolicyV2;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::ReviewDecision;
use codex_protocol::protocol::SandboxPolicy;
use futures::future::BoxFuture;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct UnifiedExecRequest {
pub command: Vec<String>,
pub cwd: PathBuf,
pub env: HashMap<String, String>,
pub exec_policy: Option<Arc<ExecPolicyV2>>,
pub with_escalated_permissions: Option<bool>,
pub justification: Option<String>,
}
@@ -63,6 +68,7 @@ impl UnifiedExecRequest {
command: Vec<String>,
cwd: PathBuf,
env: HashMap<String, String>,
exec_policy: Option<Arc<ExecPolicyV2>>,
with_escalated_permissions: Option<bool>,
justification: Option<String>,
) -> Self {
@@ -70,6 +76,7 @@ impl UnifiedExecRequest {
command,
cwd,
env,
exec_policy,
with_escalated_permissions,
justification,
}
@@ -80,6 +87,19 @@ impl<'a> UnifiedExecRuntime<'a> {
pub fn new(manager: &'a UnifiedExecSessionManager) -> Self {
Self { manager }
}
fn base_approval_requirement(
&self,
req: &UnifiedExecRequest,
policy: AskForApproval,
sandbox_policy: &SandboxPolicy,
) -> ApprovalRequirement {
if requires_initial_appoval(policy, sandbox_policy, &req.command, false) {
ApprovalRequirement::NeedsApproval { reason: None }
} else {
ApprovalRequirement::Skip
}
}
}
impl Sandboxable for UnifiedExecRuntime<'_> {
@@ -129,18 +149,19 @@ impl Approvable<UnifiedExecRequest> for UnifiedExecRuntime<'_> {
})
}
fn wants_initial_approval(
fn approval_requirement(
&self,
req: &UnifiedExecRequest,
policy: AskForApproval,
sandbox_policy: &SandboxPolicy,
) -> bool {
requires_initial_appoval(
policy,
sandbox_policy,
&req.command,
req.with_escalated_permissions.unwrap_or(false),
)
) -> ApprovalRequirement {
if let Some(exec_policy) = &req.exec_policy
&& let Some(requirement) = evaluate_with_policy(exec_policy, &req.command, policy)
{
return requirement;
}
self.base_approval_requirement(req, policy, sandbox_policy)
}
fn wants_escalated_first_attempt(&self, req: &UnifiedExecRequest) -> bool {
+16 -8
View File
@@ -86,6 +86,13 @@ pub(crate) struct ApprovalCtx<'a> {
pub risk: Option<SandboxCommandAssessment>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ApprovalRequirement {
Skip,
NeedsApproval { reason: Option<String> },
Forbidden { reason: String },
}
pub(crate) trait Approvable<Req> {
type ApprovalKey: Hash + Eq + Clone + Debug + Serialize;
@@ -106,21 +113,22 @@ pub(crate) trait Approvable<Req> {
matches!(policy, AskForApproval::Never)
}
/// Decide whether an initial user approval should be requested before the
/// first attempt. Defaults to the orchestrator's behavior (pre‑refactor):
/// - Never, OnFailure: do not ask
/// - OnRequest: ask unless sandbox policy is DangerFullAccess
/// - UnlessTrusted: always ask
fn wants_initial_approval(
fn approval_requirement(
&self,
_req: &Req,
policy: AskForApproval,
sandbox_policy: &SandboxPolicy,
) -> bool {
match policy {
) -> ApprovalRequirement {
let needs_approval = match policy {
AskForApproval::Never | AskForApproval::OnFailure => false,
AskForApproval::OnRequest => !matches!(sandbox_policy, SandboxPolicy::DangerFullAccess),
AskForApproval::UnlessTrusted => true,
};
if needs_approval {
ApprovalRequirement::NeedsApproval { reason: None }
} else {
ApprovalRequirement::Skip
}
}