From 1940a36879ead0b5caf62204a7ca309ee4e18899 Mon Sep 17 00:00:00 2001 From: Sama Setty Date: Fri, 3 Jul 2026 21:59:49 +0000 Subject: [PATCH] support reviewer overrides in execpolicy rules --- codex-rs/config/src/config_requirements.rs | 1 + .../config/src/requirements_exec_policy.rs | 22 +++ .../src/requirements_exec_policy_tests.rs | 62 ++++++++ codex-rs/core/src/apply_patch.rs | 1 + codex-rs/core/src/codex_delegate.rs | 18 ++- codex-rs/core/src/codex_delegate_tests.rs | 110 ++++++++++++- .../core/src/config/config_loader_tests.rs | 9 ++ codex-rs/core/src/exec_policy.rs | 28 +++- codex-rs/core/src/exec_policy_tests.rs | 73 +++++++++ .../core/src/exec_policy_windows_tests.rs | 1 + codex-rs/core/src/guardian/mod.rs | 2 + codex-rs/core/src/guardian/review.rs | 48 ++++++ codex-rs/core/src/guardian/tests.rs | 33 ++++ codex-rs/core/src/session/mod.rs | 2 + .../core/src/session/tests/guardian_tests.rs | 1 + codex-rs/core/src/tools/network_approval.rs | 1 + codex-rs/core/src/tools/orchestrator.rs | 32 +++- .../src/tools/runtimes/apply_patch_tests.rs | 2 + codex-rs/core/src/tools/runtimes/shell.rs | 1 + .../tools/runtimes/shell/unix_escalation.rs | 40 ++++- .../runtimes/shell/unix_escalation_tests.rs | 2 + .../core/src/tools/runtimes/unified_exec.rs | 3 + codex-rs/core/src/tools/sandboxing.rs | 15 ++ codex-rs/core/src/tools/sandboxing_tests.rs | 2 + codex-rs/execpolicy/README.md | 10 +- codex-rs/execpolicy/src/lib.rs | 1 + codex-rs/execpolicy/src/parser.rs | 20 +++ codex-rs/execpolicy/src/policy.rs | 34 ++++ codex-rs/execpolicy/src/rule.rs | 17 ++ codex-rs/execpolicy/tests/basic.rs | 147 +++++++++++++++++- codex-rs/mcp-server/src/codex_tool_runner.rs | 1 + codex-rs/protocol/src/approvals.rs | 7 + 32 files changed, 724 insertions(+), 22 deletions(-) create mode 100644 codex-rs/config/src/requirements_exec_policy_tests.rs diff --git a/codex-rs/config/src/config_requirements.rs b/codex-rs/config/src/config_requirements.rs index 00af972336..4345722ee9 100644 --- a/codex-rs/config/src/config_requirements.rs +++ b/codex-rs/config/src/config_requirements.rs @@ -3804,6 +3804,7 @@ command = "python3 /enterprise/hooks/pre.py" decision: Decision::Forbidden, resolved_program: None, justification: None, + reviewer: None, }], } ); diff --git a/codex-rs/config/src/requirements_exec_policy.rs b/codex-rs/config/src/requirements_exec_policy.rs index 95f02b249f..728cf10fbd 100644 --- a/codex-rs/config/src/requirements_exec_policy.rs +++ b/codex-rs/config/src/requirements_exec_policy.rs @@ -1,6 +1,7 @@ use codex_execpolicy::Decision; use codex_execpolicy::Policy; use codex_execpolicy::RuleRef; +use codex_execpolicy::RuleReviewer; use codex_execpolicy::rule::PatternToken; use codex_execpolicy::rule::PrefixPattern; use codex_execpolicy::rule::PrefixRule; @@ -58,6 +59,12 @@ pub struct RequirementsExecPolicyToml { pub struct RequirementsExecPolicyPrefixRuleToml { pub pattern: Vec, pub decision: Option, + /// Optional reviewer override for prompt rules. + /// + /// This mirrors reviewer on the Starlark prefix_rule(...) builtin. + /// A reviewer only has meaning for rules that request approval, so it is + /// rejected for non-prompt decisions during conversion. + pub reviewer: Option, pub justification: Option, } @@ -117,6 +124,11 @@ pub enum RequirementsExecPolicyParseError { "rules prefix_rule at index {rule_index} has decision 'allow', which is not permitted in requirements.toml: Codex merges these rules with other config and uses the most restrictive result (use 'prompt' or 'forbidden')" )] AllowDecisionNotAllowed { rule_index: usize }, + + #[error( + "rules prefix_rule at index {rule_index} has a reviewer, but reviewer is only valid with decision 'prompt'" + )] + ReviewerRequiresPromptDecision { rule_index: usize }, } impl RequirementsExecPolicyToml { @@ -158,6 +170,11 @@ impl RequirementsExecPolicyToml { return Err(RequirementsExecPolicyParseError::MissingDecision { rule_index }); } }; + if rule.reviewer.is_some() && decision != Decision::Prompt { + return Err( + RequirementsExecPolicyParseError::ReviewerRequiresPromptDecision { rule_index }, + ); + } let justification = rule.justification.clone(); let (first_token, remaining_tokens) = pattern_tokens @@ -173,6 +190,7 @@ impl RequirementsExecPolicyToml { rest: rest.clone(), }, decision, + reviewer: rule.reviewer, justification: justification.clone(), }); rules_by_program.insert(head.clone(), rule); @@ -234,3 +252,7 @@ fn parse_pattern_token( }), } } + +#[cfg(test)] +#[path = "requirements_exec_policy_tests.rs"] +mod tests; diff --git a/codex-rs/config/src/requirements_exec_policy_tests.rs b/codex-rs/config/src/requirements_exec_policy_tests.rs new file mode 100644 index 0000000000..c63241bc6b --- /dev/null +++ b/codex-rs/config/src/requirements_exec_policy_tests.rs @@ -0,0 +1,62 @@ +use super::*; +use codex_execpolicy::rule::PrefixRule; + +#[test] +fn prompt_reviewer_is_deserialized_and_propagated_to_prefix_rule() { + let parsed: RequirementsExecPolicyToml = toml::from_str( + r#" +prefix_rules = [ + { pattern = [{ token = "git" }, { token = "push" }], decision = "prompt", reviewer = "auto_review" }, +] +"#, + ) + .expect("requirements rules should deserialize"); + + assert_eq!( + parsed.prefix_rules[0].reviewer, + Some(RuleReviewer::AutoReview) + ); + + let policy = parsed.to_policy().expect("prompt reviewer should be valid"); + let rules = policy + .rules() + .get_vec("git") + .expect("git prefix rule should exist"); + let rule = rules[0] + .as_any() + .downcast_ref::() + .expect("rule should be a prefix rule"); + + assert_eq!(rule.reviewer, Some(RuleReviewer::AutoReview)); +} + +#[test] +fn user_reviewer_deserializes_from_requirements_toml() { + let parsed: RequirementsExecPolicyToml = toml::from_str( + r#" +prefix_rules = [ + { pattern = [{ token = "git" }], decision = "prompt", reviewer = "user" }, +] +"#, + ) + .expect("requirements rules should deserialize"); + + assert_eq!(parsed.prefix_rules[0].reviewer, Some(RuleReviewer::User)); +} + +#[test] +fn reviewer_is_rejected_for_non_prompt_decisions() { + let parsed: RequirementsExecPolicyToml = toml::from_str( + r#" +prefix_rules = [ + { pattern = [{ token = "rm" }], decision = "forbidden", reviewer = "user" }, +] +"#, + ) + .expect("requirements rules should deserialize"); + + assert!(matches!( + parsed.to_policy(), + Err(RequirementsExecPolicyParseError::ReviewerRequiresPromptDecision { rule_index: 0 }) + )); +} diff --git a/codex-rs/core/src/apply_patch.rs b/codex-rs/core/src/apply_patch.rs index 5e9a3f6e5a..9296bee3ea 100644 --- a/codex-rs/core/src/apply_patch.rs +++ b/codex-rs/core/src/apply_patch.rs @@ -64,6 +64,7 @@ pub(crate) async fn apply_patch( auto_approved: false, exec_approval_requirement: ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: None, }, }) diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index a671f0dd74..b872080112 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -33,7 +33,9 @@ use tokio_util::sync::CancellationToken; use crate::config::Config; use crate::guardian::GuardianApprovalRequest; +use crate::guardian::allowed_approval_reviewer_override; use crate::guardian::new_guardian_review_id; +use crate::guardian::reason_for_allowed_approval_reviewer_override; use crate::guardian::routes_approval_to_guardian; use crate::guardian::routes_approval_to_guardian_with_reviewer; use crate::guardian::spawn_approval_request_review; @@ -504,13 +506,26 @@ async fn handle_exec_approval( command, cwd, reason, + approvals_reviewer, network_approval_context, proposed_execpolicy_amendment, additional_permissions, available_decisions, .. } = event; - let decision = if routes_approval_to_guardian(parent_ctx) { + let requested_approvals_reviewer = approvals_reviewer; + let approvals_reviewer = + allowed_approval_reviewer_override(parent_ctx, requested_approvals_reviewer); + let reason = reason_for_allowed_approval_reviewer_override( + reason, + requested_approvals_reviewer, + approvals_reviewer, + ); + let use_guardian = approvals_reviewer.map_or_else( + || routes_approval_to_guardian(parent_ctx), + |reviewer| routes_approval_to_guardian_with_reviewer(parent_ctx, reviewer), + ); + let decision = if use_guardian { let review_cancel = cancel_token.child_token(); let review_rx = spawn_approval_request_review( Arc::clone(parent_session), @@ -550,6 +565,7 @@ async fn handle_exec_approval( command, cwd, reason, + approvals_reviewer, network_approval_context, proposed_execpolicy_amendment, additional_permissions, diff --git a/codex-rs/core/src/codex_delegate_tests.rs b/codex-rs/core/src/codex_delegate_tests.rs index 9513dcc56c..78072a75e9 100644 --- a/codex-rs/core/src/codex_delegate_tests.rs +++ b/codex-rs/core/src/codex_delegate_tests.rs @@ -283,12 +283,12 @@ async fn handle_request_permissions_uses_tool_call_id_for_round_trip() { } #[tokio::test] -async fn handle_exec_approval_uses_call_id_for_guardian_review_and_approval_id_for_reply() { +async fn handle_exec_approval_routes_explicit_auto_review_to_guardian() { let (parent_session, parent_ctx, rx_events) = crate::session::tests::make_session_and_context_with_rx().await; let mut parent_ctx = Arc::try_unwrap(parent_ctx).expect("single turn context ref"); let mut config = (*parent_ctx.config).clone(); - config.approvals_reviewer = ApprovalsReviewer::AutoReview; + config.approvals_reviewer = ApprovalsReviewer::User; parent_ctx.config = Arc::new(config); parent_ctx .approval_policy @@ -328,6 +328,7 @@ async fn handle_exec_approval_uses_call_id_for_guardian_review_and_approval_id_f command: vec!["rm".to_string(), "-rf".to_string(), "tmp".to_string()], cwd: test_path_buf("/tmp").abs(), reason: Some("unsafe subcommand".to_string()), + approvals_reviewer: Some(ApprovalsReviewer::AutoReview), network_approval_context: None, proposed_execpolicy_amendment: None, proposed_network_policy_amendments: None, @@ -396,6 +397,111 @@ async fn handle_exec_approval_uses_call_id_for_guardian_review_and_approval_id_f ); } +#[tokio::test] +async fn handle_exec_approval_routes_explicit_user_reviewer_to_parent_prompt() { + let (parent_session, parent_ctx, rx_events) = + crate::session::tests::make_session_and_context_with_rx().await; + *parent_session.active_turn.lock().await = Some(crate::state::ActiveTurn::default()); + let mut parent_ctx = Arc::try_unwrap(parent_ctx).expect("single turn context ref"); + let mut config = (*parent_ctx.config).clone(); + config.approvals_reviewer = ApprovalsReviewer::AutoReview; + parent_ctx.config = Arc::new(config); + parent_ctx + .approval_policy + .set(AskForApproval::OnRequest) + .expect("set on-request policy"); + let parent_ctx = Arc::new(parent_ctx); + + let (tx_sub, rx_sub) = bounded(SUBMISSION_CHANNEL_CAPACITY); + let (_tx_events, rx_events_child) = bounded(SUBMISSION_CHANNEL_CAPACITY); + let (_agent_status_tx, agent_status) = watch::channel(AgentStatus::PendingInit); + let codex = Arc::new(Codex { + tx_sub, + rx_event: rx_events_child, + agent_status, + session: Arc::clone(&parent_session), + session_loop_termination: completed_session_loop_termination(), + }); + + let cancel_token = CancellationToken::new(); + let handle = tokio::spawn({ + let codex = Arc::clone(&codex); + let parent_session = Arc::clone(&parent_session); + let parent_ctx = Arc::clone(&parent_ctx); + async move { + handle_exec_approval( + codex.as_ref(), + "child-turn-user".to_string(), + &parent_session, + &parent_ctx, + ExecApprovalRequestEvent { + call_id: "command-item-user".to_string(), + approval_id: Some("callback-approval-user".to_string()), + turn_id: "child-turn-user".to_string(), + environment_id: Some("remote".to_string()), + started_at_ms: 0, + command: vec!["git".to_string(), "push".to_string()], + cwd: test_path_buf("/tmp").abs(), + reason: Some("requires human approval by policy".to_string()), + approvals_reviewer: Some(ApprovalsReviewer::User), + network_approval_context: None, + proposed_execpolicy_amendment: None, + proposed_network_policy_amendments: None, + additional_permissions: None, + available_decisions: Some(vec![ + ReviewDecision::Approved, + ReviewDecision::Abort, + ]), + parsed_cmd: Vec::new(), + }, + &cancel_token, + ) + .await; + } + }); + + let request = timeout(Duration::from_secs(2), async { + loop { + let event = rx_events.recv().await.expect("approval request event"); + match event.msg { + EventMsg::ExecApprovalRequest(request) => return request, + EventMsg::GuardianAssessment(_) => { + panic!("user reviewer override should not route to guardian") + } + _ => {} + } + } + }) + .await + .expect("timed out waiting for parent approval prompt"); + assert_eq!(request.approvals_reviewer, Some(ApprovalsReviewer::User)); + assert_eq!( + request.reason.as_deref(), + Some("requires human approval by policy") + ); + + parent_session + .notify_approval("callback-approval-user", ReviewDecision::Approved) + .await; + timeout(Duration::from_secs(2), handle) + .await + .expect("handle_exec_approval hung") + .expect("handle_exec_approval join error"); + + let submission = timeout(Duration::from_secs(2), rx_sub.recv()) + .await + .expect("exec approval response timed out") + .expect("exec approval response missing"); + assert_eq!( + submission.op, + Op::ExecApproval { + id: "callback-approval-user".to_string(), + turn_id: Some("child-turn-user".to_string()), + decision: ReviewDecision::Approved, + } + ); +} + #[tokio::test] async fn delegated_mcp_guardian_abort_returns_synthetic_decline_answer() { let (parent_session, parent_ctx, _rx_events) = diff --git a/codex-rs/core/src/config/config_loader_tests.rs b/codex-rs/core/src/config/config_loader_tests.rs index 9857e08f16..9266458137 100644 --- a/codex-rs/core/src/config/config_loader_tests.rs +++ b/codex-rs/core/src/config/config_loader_tests.rs @@ -3571,6 +3571,7 @@ prefix_rules = [ any_of: None, }], decision: Some(RequirementsExecPolicyDecisionToml::Forbidden), + reviewer: None, justification: None, }], } @@ -3600,6 +3601,7 @@ prefix_rules = [ any_of: None, }], decision: Some(RequirementsExecPolicyDecisionToml::Forbidden), + reviewer: None, justification: None, }, RequirementsExecPolicyPrefixRuleToml { @@ -3614,6 +3616,7 @@ prefix_rules = [ }, ], decision: Some(RequirementsExecPolicyDecisionToml::Prompt), + reviewer: None, justification: Some("review changes before push or commit".to_string()), }, ], @@ -3643,6 +3646,7 @@ prefix_rules = [ decision: Decision::Forbidden, resolved_program: None, justification: None, + reviewer: None, }], } ); @@ -3669,6 +3673,7 @@ prefix_rules = [ decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: None, }], } ); @@ -3681,6 +3686,7 @@ prefix_rules = [ decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: None, }], } ); @@ -3765,6 +3771,7 @@ prefix_rules = [] decision: Decision::Forbidden, resolved_program: None, justification: None, + reviewer: None, }], } ); @@ -3804,6 +3811,7 @@ prefix_rules = [] decision: Decision::Forbidden, resolved_program: None, justification: None, + reviewer: None, }], } ); @@ -3819,6 +3827,7 @@ prefix_rules = [] decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: None, }], } ); diff --git a/codex-rs/core/src/exec_policy.rs b/codex-rs/core/src/exec_policy.rs index cbffcd7e43..5ffdf4a350 100644 --- a/codex-rs/core/src/exec_policy.rs +++ b/codex-rs/core/src/exec_policy.rs @@ -17,9 +17,11 @@ use codex_execpolicy::NetworkRuleProtocol; use codex_execpolicy::Policy; use codex_execpolicy::PolicyParser; use codex_execpolicy::RuleMatch; +use codex_execpolicy::RuleReviewer; use codex_execpolicy::blocking_append_allow_prefix_rule; use codex_execpolicy::blocking_append_network_rule; use codex_protocol::approvals::ExecPolicyAmendment; +use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::PermissionProfile; use codex_protocol::permissions::FileSystemSandboxKind; @@ -331,12 +333,17 @@ impl ExecPolicyManager { let prompt_is_rule = evaluation.matched_rules.iter().any(|rule_match| { is_policy_match(rule_match) && rule_match.decision() == Decision::Prompt }); + let reviewer = evaluation.prompt_reviewer().map(|reviewer| match reviewer { + RuleReviewer::User => ApprovalsReviewer::User, + RuleReviewer::AutoReview => ApprovalsReviewer::AutoReview, + }); match prompt_is_rejected_by_policy(approval_policy, prompt_is_rule) { Some(reason) => ExecApprovalRequirement::Forbidden { reason: reason.to_string(), }, None => ExecApprovalRequirement::NeedsApproval { - reason: derive_prompt_reason(command, &evaluation), + reason: derive_prompt_reason(command, &evaluation, reviewer), + reviewer, proposed_execpolicy_amendment: requested_amendment.or_else(|| { if auto_amendment_allowed { try_derive_execpolicy_amendment_for_prompt_rules( @@ -913,8 +920,17 @@ fn prefix_rule_would_approve_all_commands( } /// Only return a reason when a policy rule drove the prompt decision. -fn derive_prompt_reason(command_args: &[String], evaluation: &Evaluation) -> Option { +fn derive_prompt_reason( + command_args: &[String], + evaluation: &Evaluation, + reviewer: Option, +) -> Option { let command = render_shlex_command(command_args); + let approval_description = match reviewer { + Some(ApprovalsReviewer::User) => "requires human approval", + Some(ApprovalsReviewer::AutoReview) => "requires automatic approval review", + None => "requires approval", + }; let most_specific_prompt = evaluation .matched_rules @@ -931,11 +947,11 @@ fn derive_prompt_reason(command_args: &[String], evaluation: &Evaluation) -> Opt .max_by_key(|(matched_prefix_len, _)| *matched_prefix_len); match most_specific_prompt { - Some((_matched_prefix_len, Some(justification))) => { - Some(format!("`{command}` requires approval: {justification}")) - } + Some((_matched_prefix_len, Some(justification))) => Some(format!( + "`{command}` {approval_description}: {justification}" + )), Some((_matched_prefix_len, None)) => { - Some(format!("`{command}` requires approval by policy")) + Some(format!("`{command}` {approval_description} by policy")) } None => None, } diff --git a/codex-rs/core/src/exec_policy_tests.rs b/codex-rs/core/src/exec_policy_tests.rs index cf17387ef5..dc3c566bbf 100644 --- a/codex-rs/core/src/exec_policy_tests.rs +++ b/codex-rs/core/src/exec_policy_tests.rs @@ -333,6 +333,7 @@ async fn loads_policies_from_policy_subdirectory() { decision: Decision::Forbidden, resolved_program: None, justification: None, + reviewer: None, }], }, policy.check_multiple(command.iter(), &|_| Decision::Allow) @@ -611,6 +612,7 @@ async fn loads_policies_from_multiple_config_layers() -> anyhow::Result<()> { decision: Decision::Forbidden, resolved_program: None, justification: None, + reviewer: None, }], }, policy.check_multiple([vec!["rm".to_string()]].iter(), &|_| Decision::Allow) @@ -623,6 +625,7 @@ async fn loads_policies_from_multiple_config_layers() -> anyhow::Result<()> { decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: None, }], }, policy.check_multiple([vec!["ls".to_string()]].iter(), &|_| Decision::Allow) @@ -765,6 +768,7 @@ async fn omits_auto_amendment_for_heredoc_fallback_prompts() { }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: None, }, ) @@ -792,6 +796,7 @@ async fn drops_requested_amendment_for_heredoc_fallback_prompts_when_it_wont_mat }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: None, }, ) @@ -815,6 +820,7 @@ async fn drops_requested_amendment_for_heredoc_fallback_prompts_when_it_matches( }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: None, }, ) @@ -902,6 +908,7 @@ EOF"# }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ "zsh".to_string(), "-lc".to_string(), @@ -959,6 +966,53 @@ async fn exec_approval_requirement_prefers_execpolicy_match() { }, ExecApprovalRequirement::NeedsApproval { reason: Some("`rm` requires approval by policy".to_string()), + reviewer: None, + proposed_execpolicy_amendment: None, + }, + ) + .await; +} + +#[tokio::test] +async fn exec_approval_requirement_carries_user_reviewer_from_prompt_rule() { + assert_exec_approval_requirement_for_command( + ExecApprovalRequirementScenario { + policy_src: Some( + r#"prefix_rule(pattern=["rm"], decision="prompt", reviewer="user", justification="human checkpoint")"# + .to_string(), + ), + command: vec!["rm".to_string()], + approval_policy: AskForApproval::OnRequest, + permission_profile: PermissionProfile::Disabled, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }, + ExecApprovalRequirement::NeedsApproval { + reason: Some("`rm` requires human approval: human checkpoint".to_string()), + reviewer: Some(ApprovalsReviewer::User), + proposed_execpolicy_amendment: None, + }, + ) + .await; +} + +#[tokio::test] +async fn exec_approval_requirement_carries_auto_review_reviewer_from_prompt_rule() { + assert_exec_approval_requirement_for_command( + ExecApprovalRequirementScenario { + policy_src: Some( + r#"prefix_rule(pattern=["rm"], decision="prompt", reviewer="auto_review")"# + .to_string(), + ), + command: vec!["rm".to_string()], + approval_policy: AskForApproval::OnRequest, + permission_profile: PermissionProfile::Disabled, + sandbox_permissions: SandboxPermissions::UseDefault, + prefix_rule: None, + }, + ExecApprovalRequirement::NeedsApproval { + reason: Some("`rm` requires automatic approval review by policy".to_string()), + reviewer: Some(ApprovalsReviewer::AutoReview), proposed_execpolicy_amendment: None, }, ) @@ -1045,6 +1099,7 @@ async fn requested_prefix_rule_can_approve_absolute_path_commands() { }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ "cargo".to_string(), "install".to_string(), @@ -1229,6 +1284,7 @@ async fn exec_approval_requirement_prompts_for_inline_additional_permissions_und }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ "touch".to_string(), "requested-dir/requested-but-unused.txt".to_string(), @@ -1251,6 +1307,7 @@ async fn exec_approval_requirement_prompts_for_known_safe_escalation_under_on_re }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ "echo".to_string(), "hello".to_string(), @@ -1406,6 +1463,7 @@ async fn exec_approval_requirement_falls_back_to_heuristics() { requirement, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(command)) } ); @@ -1431,6 +1489,7 @@ async fn empty_bash_lc_script_falls_back_to_original_command() { requirement, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(command)), } ); @@ -1460,6 +1519,7 @@ async fn whitespace_bash_lc_script_falls_back_to_original_command() { requirement, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(command)), } ); @@ -1489,6 +1549,7 @@ async fn request_rule_uses_prefix_rule() { requirement, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ "cargo".to_string(), "install".to_string(), @@ -1521,6 +1582,7 @@ async fn request_rule_falls_back_when_prefix_rule_does_not_approve_all_commands( requirement, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ "rm".to_string(), "-rf".to_string(), @@ -1557,6 +1619,7 @@ async fn heuristics_apply_when_other_commands_match_policy() { .await, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ "orange".to_string() ])) @@ -1630,6 +1693,7 @@ async fn proposed_execpolicy_amendment_is_present_for_single_command_without_pol }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(command)), }, ) @@ -1649,6 +1713,7 @@ async fn proposed_execpolicy_amendment_is_omitted_when_policy_prompts() { }, ExecApprovalRequirement::NeedsApproval { reason: Some("`rm` requires approval by policy".to_string()), + reviewer: None, proposed_execpolicy_amendment: None, }, ) @@ -1672,6 +1737,7 @@ async fn proposed_execpolicy_amendment_is_present_for_multi_command_scripts() { }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ "cargo".to_string(), "build".to_string(), @@ -1701,6 +1767,7 @@ async fn proposed_execpolicy_amendment_uses_first_no_match_in_multi_command_scri }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![ "apple".to_string(), ])), @@ -1925,6 +1992,7 @@ fn derive_requested_execpolicy_amendment_returns_none_when_policy_matches() { decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: None, }]; assert_eq!( None, @@ -1936,6 +2004,7 @@ fn derive_requested_execpolicy_amendment_returns_none_when_policy_matches() { decision: Decision::Allow, resolved_program: None, justification: None, + reviewer: None, }]; assert_eq!( None, @@ -1947,6 +2016,7 @@ fn derive_requested_execpolicy_amendment_returns_none_when_policy_matches() { decision: Decision::Forbidden, resolved_program: None, justification: None, + reviewer: None, }]; assert_eq!( None, @@ -1973,6 +2043,7 @@ async fn dangerous_rm_rf_requires_approval_in_danger_full_access() { }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(command)), }, ) @@ -2012,6 +2083,7 @@ async fn verify_approval_requirement_for_unsafe_powershell_command() { safe" should require approval."#, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: expected_amendment.clone(), }, ) @@ -2044,6 +2116,7 @@ async fn verify_approval_requirement_for_unsafe_powershell_command() { assert_eq!( ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec_str(&[ "rm", "-rf", diff --git a/codex-rs/core/src/exec_policy_windows_tests.rs b/codex-rs/core/src/exec_policy_windows_tests.rs index 735cdd4ddc..e1b01dcad2 100644 --- a/codex-rs/core/src/exec_policy_windows_tests.rs +++ b/codex-rs/core/src/exec_policy_windows_tests.rs @@ -195,6 +195,7 @@ async fn unmatched_dangerous_powershell_inner_commands_require_approval() { }, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(inner_command)), }, ) diff --git a/codex-rs/core/src/guardian/mod.rs b/codex-rs/core/src/guardian/mod.rs index b06a2daad3..4f01b0fefe 100644 --- a/codex-rs/core/src/guardian/mod.rs +++ b/codex-rs/core/src/guardian/mod.rs @@ -29,10 +29,12 @@ pub(crate) use approval_request::GuardianMcpAnnotations; pub(crate) use approval_request::GuardianNetworkAccessTrigger; #[cfg(test)] pub(crate) use approval_request::guardian_approval_request_to_json; +pub(crate) use review::allowed_approval_reviewer_override; pub(crate) use review::guardian_rejection_message; pub(crate) use review::guardian_timeout_message; pub(crate) use review::is_guardian_reviewer_source; pub(crate) use review::new_guardian_review_id; +pub(crate) use review::reason_for_allowed_approval_reviewer_override; #[cfg(test)] pub(crate) use review::record_guardian_denial_for_test; pub(crate) use review::review_approval_request; diff --git a/codex-rs/core/src/guardian/review.rs b/codex-rs/core/src/guardian/review.rs index 4756cc1fc4..356891f786 100644 --- a/codex-rs/core/src/guardian/review.rs +++ b/codex-rs/core/src/guardian/review.rs @@ -169,6 +169,54 @@ pub(crate) fn routes_approval_to_guardian(turn: &TurnContext) -> bool { routes_approval_to_guardian_with_reviewer(turn, turn.config.approvals_reviewer) } +/// Returns a per-request reviewer override when managed requirements permit it. +/// +/// A disallowed override must not bypass allowed_approvals_reviewers; in that +/// case the request inherits the already-constrained turn-level reviewer. +pub(crate) fn allowed_approval_reviewer_override( + turn: &TurnContext, + approvals_reviewer: Option, +) -> Option { + let reviewer = approvals_reviewer?; + if let Err(err) = turn + .config + .config_layer_stack + .requirements() + .approvals_reviewer + .can_set(&reviewer) + { + tracing::warn!( + error = %err, + ?reviewer, + "exec-policy reviewer override is disallowed by requirements; using the configured reviewer" + ); + return None; + } + Some(reviewer) +} + +/// Removes reviewer-specific wording when requirements reject a rule override. +/// +/// Approval reasons generated for exec-policy prompt rules use one of these +/// controlled phrases. If the override cannot be honored, the inherited +/// reviewer is intentionally left implicit rather than claiming the wrong +/// route in the UI or history. +pub(crate) fn reason_for_allowed_approval_reviewer_override( + reason: Option, + requested_reviewer: Option, + allowed_reviewer: Option, +) -> Option { + if requested_reviewer == allowed_reviewer { + return reason; + } + + reason.map(|reason| { + reason + .replacen("requires human approval", "requires approval", 1) + .replacen("requires automatic approval review", "requires approval", 1) + }) +} + /// Whether an approval with its own reviewer selection should be routed through guardian. pub(crate) fn routes_approval_to_guardian_with_reviewer( turn: &TurnContext, diff --git a/codex-rs/core/src/guardian/tests.rs b/codex-rs/core/src/guardian/tests.rs index 7dc4d8544e..ed2130ab01 100644 --- a/codex-rs/core/src/guardian/tests.rs +++ b/codex-rs/core/src/guardian/tests.rs @@ -1224,6 +1224,39 @@ async fn routes_approval_to_guardian_can_use_app_reviewer_override() { )); } +#[tokio::test] +async fn exec_policy_reviewer_override_respects_managed_reviewer_requirements() { + let (_session, mut turn) = crate::session::tests::make_session_and_context().await; + let mut config = (*turn.config).clone(); + let requirements = codex_config::ConfigRequirements { + approvals_reviewer: codex_config::ConstrainedWithSource::new( + Constrained::allow_only(ApprovalsReviewer::User), + /*source*/ None, + ), + ..Default::default() + }; + config.config_layer_stack = ConfigLayerStack::new(Vec::new(), requirements, Default::default()) + .expect("config layer stack"); + turn.config = Arc::new(config); + + assert_eq!( + allowed_approval_reviewer_override(&turn, Some(ApprovalsReviewer::AutoReview)), + None + ); + assert_eq!( + allowed_approval_reviewer_override(&turn, Some(ApprovalsReviewer::User)), + Some(ApprovalsReviewer::User) + ); + assert_eq!( + reason_for_allowed_approval_reviewer_override( + Some("`rm` requires human approval by policy".to_string()), + Some(ApprovalsReviewer::User), + None, + ), + Some("`rm` requires approval by policy".to_string()) + ); +} + #[tokio::test] async fn routes_approval_to_guardian_allows_granular_review_policy() { let (_session, mut turn) = crate::session::tests::make_session_and_context().await; diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 978768ba00..7c3f52ee25 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -2129,6 +2129,7 @@ impl Session { command: Vec, cwd: AbsolutePathBuf, reason: Option, + approvals_reviewer: Option, network_approval_context: Option, proposed_execpolicy_amendment: Option, additional_permissions: Option, @@ -2183,6 +2184,7 @@ impl Session { command, cwd, reason, + approvals_reviewer, network_approval_context, proposed_execpolicy_amendment, proposed_network_policy_amendments, diff --git a/codex-rs/core/src/session/tests/guardian_tests.rs b/codex-rs/core/src/session/tests/guardian_tests.rs index d13239d810..8326f7fd78 100644 --- a/codex-rs/core/src/session/tests/guardian_tests.rs +++ b/codex-rs/core/src/session/tests/guardian_tests.rs @@ -695,6 +695,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() { decision: Decision::Forbidden, resolved_program: None, justification: None, + reviewer: None, }], } ); diff --git a/codex-rs/core/src/tools/network_approval.rs b/codex-rs/core/src/tools/network_approval.rs index 2b63164b4d..fbbe2afd1a 100644 --- a/codex-rs/core/src/tools/network_approval.rs +++ b/codex-rs/core/src/tools/network_approval.rs @@ -612,6 +612,7 @@ impl NetworkApprovalService { prompt_command, cwd, Some(prompt_reason), + /*approvals_reviewer*/ None, Some(network_approval_context.clone()), /*proposed_execpolicy_amendment*/ None, /*additional_permissions*/ None, diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index aaa0dfe9d1..c189873234 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -6,10 +6,13 @@ simple sequence for any ToolRuntime: approval → select sandbox → attempt → retry with an escalated sandbox strategy on denial (no re‑approval thanks to caching). */ +use crate::guardian::allowed_approval_reviewer_override; use crate::guardian::guardian_rejection_message; use crate::guardian::guardian_timeout_message; use crate::guardian::new_guardian_review_id; +use crate::guardian::reason_for_allowed_approval_reviewer_override; use crate::guardian::routes_approval_to_guardian; +use crate::guardian::routes_approval_to_guardian_with_reviewer; use crate::hook_runtime::run_permission_request_hooks; use crate::network_policy_decision::network_approval_context_from_payload; use crate::tools::flat_tool_name; @@ -31,6 +34,7 @@ use crate::tools::sandboxing::sandbox_override_for_first_attempt; use crate::tools::sandboxing::unsandboxed_execution_allowed; use codex_hooks::PermissionRequestDecision; use codex_otel::ToolDecisionSource; +use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::error::CodexErr; use codex_protocol::error::SandboxErr; use codex_protocol::exec_output::ExecToolCallOutput; @@ -146,7 +150,6 @@ impl ToolOrchestrator { let otel_tn = flat_tool_name(&tool_ctx.tool_name).into_owned(); let otel_ci = &tool_ctx.call_id; let strict_auto_review = tool_ctx.session.strict_auto_review_enabled_for_turn().await; - let use_guardian = routes_approval_to_guardian(turn_ctx) || strict_auto_review; // 1) Approval let mut already_approved = false; @@ -156,9 +159,17 @@ impl ToolOrchestrator { let requirement = tool.exec_approval_requirement(req).unwrap_or_else(|| { default_exec_approval_requirement(approval_policy, &file_system_sandbox_policy) }); + let requested_reviewer = requirement.reviewer(); + let reviewer = allowed_approval_reviewer_override(turn_ctx, requested_reviewer); + let strict_auto_review_for_request = + strict_auto_review && reviewer != Some(ApprovalsReviewer::User); + let use_guardian = reviewer.map_or_else( + || routes_approval_to_guardian(turn_ctx) || strict_auto_review_for_request, + |reviewer| routes_approval_to_guardian_with_reviewer(turn_ctx, reviewer), + ); match &requirement { ExecApprovalRequirement::Skip { .. } => { - if strict_auto_review { + if strict_auto_review_for_request { let guardian_review_id = Some(new_guardian_review_id()); let approval_ctx = ApprovalCtx { session: &tool_ctx.session, @@ -166,6 +177,7 @@ impl ToolOrchestrator { call_id: &tool_ctx.call_id, guardian_review_id: guardian_review_id.clone(), retry_reason: None, + approvals_reviewer: reviewer, network_approval_context: None, }; let decision = Self::request_approval( @@ -194,13 +206,19 @@ impl ToolOrchestrator { return Err(ToolError::Rejected(reason.clone())); } ExecApprovalRequirement::NeedsApproval { reason, .. } => { + let reason = reason_for_allowed_approval_reviewer_override( + reason.clone(), + requested_reviewer, + reviewer, + ); let guardian_review_id = use_guardian.then(new_guardian_review_id); let approval_ctx = ApprovalCtx { session: &tool_ctx.session, turn: &tool_ctx.turn, call_id: &tool_ctx.call_id, guardian_review_id: guardian_review_id.clone(), - retry_reason: reason.clone(), + retry_reason: reason, + approvals_reviewer: reviewer, network_approval_context: None, }; let decision = Self::request_approval( @@ -209,7 +227,7 @@ impl ToolOrchestrator { tool_ctx.call_id.as_str(), approval_ctx, tool_ctx, - /*evaluate_permission_request_hooks*/ !strict_auto_review, + /*evaluate_permission_request_hooks*/ !strict_auto_review_for_request, &otel, ) .await?; @@ -386,7 +404,7 @@ impl ToolOrchestrator { // Strict auto-review approval covers the sandboxed attempt only; // retrying without the sandbox requires a fresh guardian review. - let bypass_retry_approval = !strict_auto_review + let bypass_retry_approval = !strict_auto_review_for_request && tool.should_bypass_approval(approval_policy, already_approved) && network_approval_context.is_none(); if !bypass_retry_approval { @@ -397,6 +415,7 @@ impl ToolOrchestrator { call_id: &tool_ctx.call_id, guardian_review_id: guardian_review_id.clone(), retry_reason: Some(retry_reason), + approvals_reviewer: reviewer, network_approval_context: network_approval_context.clone(), }; @@ -407,7 +426,8 @@ impl ToolOrchestrator { &permission_request_run_id, approval_ctx, tool_ctx, - /*evaluate_permission_request_hooks*/ !strict_auto_review, + /*evaluate_permission_request_hooks*/ + !strict_auto_review_for_request, &otel, ) .await?; diff --git a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs index f1c6f43aa3..bb82c10082 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs @@ -69,6 +69,7 @@ async fn guardian_review_request_includes_patch_context() { )]), exec_approval_requirement: ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: None, }, additional_permissions: None, @@ -105,6 +106,7 @@ async fn permission_request_payload_uses_apply_patch_hook_name_and_aliases() { changes: HashMap::new(), exec_approval_requirement: ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: None, }, additional_permissions: None, diff --git a/codex-rs/core/src/tools/runtimes/shell.rs b/codex-rs/core/src/tools/runtimes/shell.rs index 0d386103db..78fe2460b6 100644 --- a/codex-rs/core/src/tools/runtimes/shell.rs +++ b/codex-rs/core/src/tools/runtimes/shell.rs @@ -180,6 +180,7 @@ impl Approvable for ShellRuntime { command, cwd, reason, + ctx.approvals_reviewer, ctx.network_approval_context.clone(), req.exec_approval_requirement .proposed_execpolicy_amendment() diff --git a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs index 10cb460205..b5ff89f6e9 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -4,11 +4,13 @@ use crate::exec::ExecExpiration; use crate::exec::cancel_when_either; use crate::exec::is_likely_sandbox_denied; use crate::guardian::GuardianApprovalRequest; +use crate::guardian::allowed_approval_reviewer_override; use crate::guardian::guardian_rejection_message; use crate::guardian::guardian_timeout_message; use crate::guardian::new_guardian_review_id; use crate::guardian::review_approval_request; use crate::guardian::routes_approval_to_guardian; +use crate::guardian::routes_approval_to_guardian_with_reviewer; use crate::hook_runtime::run_permission_request_hooks; use crate::sandboxing::ExecOptions; use crate::sandboxing::ExecRequest; @@ -29,8 +31,10 @@ use codex_execpolicy::Evaluation; use codex_execpolicy::MatchOptions; use codex_execpolicy::Policy; use codex_execpolicy::RuleMatch; +use codex_execpolicy::RuleReviewer; use codex_features::Feature; use codex_hooks::PermissionRequestDecision; +use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::error::CodexErr; use codex_protocol::error::SandboxErr; @@ -445,6 +449,7 @@ impl CoreShellActionProvider { argv: &[String], workdir: &AbsolutePathBuf, stopwatch: &Stopwatch, + reviewer: Option, additional_permissions: Option, ) -> anyhow::Result { let command = join_program_and_argv(program, argv); @@ -455,7 +460,20 @@ impl CoreShellActionProvider { let approval_id = Some(Uuid::new_v4().to_string()); let environment_id = Some(self.environment_id.clone()); let source = self.tool_name; - let guardian_review_id = routes_approval_to_guardian(&turn).then(new_guardian_review_id); + let reviewer = allowed_approval_reviewer_override(&turn, reviewer); + let use_guardian = reviewer.map_or_else( + || routes_approval_to_guardian(&turn), + |reviewer| routes_approval_to_guardian_with_reviewer(&turn, reviewer), + ); + let guardian_review_id = use_guardian.then(new_guardian_review_id); + let approval_reason = reviewer.map(|reviewer| { + let approval_description = match reviewer { + ApprovalsReviewer::User => "requires human approval", + ApprovalsReviewer::AutoReview => "requires automatic approval review", + }; + let command = codex_shell_command::parse_command::shlex_join(&command); + format!("`{command}` {approval_description} by policy") + }); Ok(stopwatch .pause_for(async move { // 1) Run PermissionRequest hooks @@ -503,7 +521,7 @@ impl CoreShellActionProvider { cwd: workdir.clone(), additional_permissions, }, - /*retry_reason*/ None, + approval_reason.clone(), ) .await; return PromptDecision { @@ -522,7 +540,8 @@ impl CoreShellActionProvider { environment_id, command, workdir.clone(), - /*reason*/ None, + approval_reason, + reviewer, /*network_approval_context*/ None, /*proposed_execpolicy_amendment*/ None, additional_permissions, @@ -546,6 +565,7 @@ impl CoreShellActionProvider { program: &AbsolutePathBuf, argv: &[String], workdir: &AbsolutePathBuf, + reviewer: Option, prompt_permissions: Option, escalation_execution: EscalationExecution, decision_source: DecisionSource, @@ -561,7 +581,14 @@ impl CoreShellActionProvider { EscalationDecision::deny(Some("Execution forbidden by policy".to_string())) } else { let prompt_decision = self - .prompt(program, argv, workdir, &self.stopwatch, prompt_permissions) + .prompt( + program, + argv, + workdir, + &self.stopwatch, + reviewer, + prompt_permissions, + ) .await?; match prompt_decision.decision { ReviewDecision::Approved @@ -674,6 +701,10 @@ impl CoreShellActionProvider { } else { DecisionSource::UnmatchedCommandFallback }; + let reviewer = evaluation.prompt_reviewer().map(|reviewer| match reviewer { + RuleReviewer::User => ApprovalsReviewer::User, + RuleReviewer::AutoReview => ApprovalsReviewer::AutoReview, + }); let escalation_execution = match decision_source { DecisionSource::PrefixRule if unsandboxed_allowed => EscalationExecution::Unsandboxed, DecisionSource::PrefixRule => EscalationExecution::TurnDefault, @@ -690,6 +721,7 @@ impl CoreShellActionProvider { program, argv, workdir, + reviewer, self.prompt_permissions.clone(), escalation_execution, decision_source, diff --git a/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs b/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs index 5478c1d946..8561d4eca6 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs @@ -697,6 +697,7 @@ fn evaluate_intercepted_exec_policy_matches_inner_shell_commands_when_enabled() decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: None, }], } ); @@ -739,6 +740,7 @@ host_executable(name = "git", paths = ["{git_path_literal}"]) decision: Decision::Prompt, resolved_program: Some(program), justification: None, + reviewer: None, }], } ); diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index 5df42cc979..50f66dbd3e 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -221,6 +221,7 @@ impl Approvable for UnifiedExecRuntime<'_> { command, native_cwd, reason, + ctx.approvals_reviewer, ctx.network_approval_context.clone(), req.exec_approval_requirement .proposed_execpolicy_amendment() @@ -598,6 +599,7 @@ mod tests { SandboxPermissions::RequireEscalated, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: None, }, ); @@ -623,6 +625,7 @@ mod tests { SandboxPermissions::WithAdditionalPermissions, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: None, }, ); diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index 8e9e274f24..5b72426d1a 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -15,6 +15,7 @@ use codex_file_system::FileSystemSandboxContext; use codex_network_proxy::NetworkProxy; use codex_protocol::approvals::ExecPolicyAmendment; use codex_protocol::approvals::NetworkApprovalContext; +use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::error::CodexErr; use codex_protocol::permissions::FileSystemSandboxKind; use codex_protocol::permissions::FileSystemSandboxPolicy; @@ -130,6 +131,8 @@ pub(crate) struct ApprovalCtx<'a> { /// review without overloading the tool call ID as a review ID. pub guardian_review_id: Option, pub retry_reason: Option, + /// Optional per-request reviewer selected by a matching exec-policy rule. + pub approvals_reviewer: Option, pub network_approval_context: Option, } @@ -172,6 +175,10 @@ pub(crate) enum ExecApprovalRequirement { /// Approval required for this tool call. NeedsApproval { reason: Option, + /// Optional per-request reviewer selected by a matching exec-policy rule. + /// + /// When omitted, approval routing falls back to the turn-level reviewer. + reviewer: Option, /// Proposed execpolicy amendment to skip future approvals for similar commands /// See core/src/exec_policy.rs for more details on how proposed_execpolicy_amendment is determined. proposed_execpolicy_amendment: Option, @@ -194,6 +201,13 @@ impl ExecApprovalRequirement { _ => None, } } + + pub fn reviewer(&self) -> Option { + match self { + Self::NeedsApproval { reviewer, .. } => *reviewer, + Self::Skip { .. } | Self::Forbidden { .. } => None, + } + } } /// - Never: do not ask @@ -229,6 +243,7 @@ pub(crate) fn default_exec_approval_requirement( } else if needs_approval { ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: None, } } else { diff --git a/codex-rs/core/src/tools/sandboxing_tests.rs b/codex-rs/core/src/tools/sandboxing_tests.rs index 28b9de9ce1..5def9fe20b 100644 --- a/codex-rs/core/src/tools/sandboxing_tests.rs +++ b/codex-rs/core/src/tools/sandboxing_tests.rs @@ -66,6 +66,7 @@ fn restricted_sandbox_requires_exec_approval_on_request() { ), ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: None, } ); @@ -109,6 +110,7 @@ fn default_exec_approval_requirement_keeps_prompt_when_granular_allows_sandbox_a requirement, ExecApprovalRequirement::NeedsApproval { reason: None, + reviewer: None, proposed_execpolicy_amendment: None, } ); diff --git a/codex-rs/execpolicy/README.md b/codex-rs/execpolicy/README.md index 5d1179362b..e99617987d 100644 --- a/codex-rs/execpolicy/README.md +++ b/codex-rs/execpolicy/README.md @@ -2,9 +2,11 @@ ## Overview -- Policy engine and CLI built around `prefix_rule(pattern=[...], decision?, justification?, match?, not_match?)` plus `host_executable(name=..., paths=[...])`. +- Policy engine and CLI built around `prefix_rule(pattern=[...], decision?, reviewer?, justification?, match?, not_match?)` plus `host_executable(name=..., paths=[...])`. - This release covers the prefix-rule subset of the execpolicy language plus host executable metadata; a richer language will follow. - Tokens are matched in order; any `pattern` element may be a list to denote alternatives. `decision` defaults to `allow`; valid values: `allow`, `prompt`, `forbidden`. +- `reviewer` is an optional reviewer override for `decision = "prompt"` rules. Valid values are `user` and `auto_review`; rules without it inherit the caller's configured reviewer. It is rejected for `allow` and `forbidden` rules. +- Managed `allowed_approvals_reviewers` constraints still apply; a disallowed rule override is ignored and the configured reviewer is inherited. - `justification` is an optional human-readable rationale for why a rule exists. It can be provided for any `decision` and may be surfaced in different contexts (for example, in approval prompts or rejection messages). When `decision = "forbidden"` is used, include a recommended alternative in the `justification`, when appropriate (e.g., ``"Use `jj` instead of `git`."``). - `match` / `not_match` supply example invocations that are validated at load time (think of them as unit tests); examples can be token arrays or strings (strings are tokenized with `shlex`). - The CLI always prints the JSON serialization of the evaluation result. @@ -18,6 +20,7 @@ prefix_rule( pattern = ["cmd", ["alt1", "alt2"]], # ordered tokens; list entries denote alternatives decision = "prompt", # allow | prompt | forbidden; defaults to allow + reviewer = "user", # user | auto_review; prompt rules only justification = "explain why this rule exists", match = [["cmd", "alt1"], "cmd alt2"], # examples that must match this rule not_match = [["cmd", "oops"], "cmd alt3"], # examples that must not match this rule @@ -82,7 +85,8 @@ cargo run -p codex-execpolicy -- check --rules path/to/policy.rules git status "matchedPrefix": ["", "..."], "decision": "allow|prompt|forbidden", "resolvedProgram": "/absolute/path/to/program", - "justification": "..." + "justification": "...", + "reviewer": "user|auto_review" } } ], @@ -93,6 +97,8 @@ cargo run -p codex-execpolicy -- check --rules path/to/policy.rules git status - When no rules match, `matchedRules` is an empty array and `decision` is omitted. - `matchedRules` lists every rule whose prefix matched the command; `matchedPrefix` is the exact prefix that matched. - `resolvedProgram` is omitted unless an absolute executable path matched via basename fallback. +- `reviewer` is omitted unless a matching prompt rule explicitly overrides the caller's configured reviewer. - The effective `decision` is the strictest severity across all matches (`forbidden` > `prompt` > `allow`). +- For matching prompt rules that specify different reviewers, `user` takes precedence over `auto_review`. Note: `execpolicy` commands are still in preview. The API may have breaking changes in the future. diff --git a/codex-rs/execpolicy/src/lib.rs b/codex-rs/execpolicy/src/lib.rs index 45d3642415..37631d324d 100644 --- a/codex-rs/execpolicy/src/lib.rs +++ b/codex-rs/execpolicy/src/lib.rs @@ -28,3 +28,4 @@ pub use rule::PrefixRule; pub use rule::Rule; pub use rule::RuleMatch; pub use rule::RuleRef; +pub use rule::RuleReviewer; diff --git a/codex-rs/execpolicy/src/parser.rs b/codex-rs/execpolicy/src/parser.rs index 33262db1b3..4387358751 100644 --- a/codex-rs/execpolicy/src/parser.rs +++ b/codex-rs/execpolicy/src/parser.rs @@ -32,6 +32,7 @@ use crate::rule::PatternToken; use crate::rule::PrefixPattern; use crate::rule::PrefixRule; use crate::rule::RuleRef; +use crate::rule::RuleReviewer; use crate::rule::validate_match_examples; use crate::rule::validate_not_match_examples; @@ -257,6 +258,16 @@ fn parse_network_rule_decision(raw: &str) -> Result { } } +fn parse_rule_reviewer(raw: &str) -> Result { + match raw { + "user" => Ok(RuleReviewer::User), + "auto_review" => Ok(RuleReviewer::AutoReview), + other => Err(Error::InvalidRule(format!( + "reviewer must be one of user, auto_review (got {other})" + ))), + } +} + fn error_location_from_file_span(span: FileSpan) -> ErrorLocation { let resolved = span.resolve_span(); ErrorLocation { @@ -352,12 +363,20 @@ fn policy_builtins(builder: &mut GlobalsBuilder) { r#match: Option>>, not_match: Option>>, justification: Option<&'v str>, + reviewer: Option<&'v str>, eval: &mut Evaluator<'v, '_, '_>, ) -> anyhow::Result { let decision = match decision { Some(raw) => Decision::parse(raw)?, None => Decision::Allow, }; + let reviewer = reviewer.map(parse_rule_reviewer).transpose()?; + if reviewer.is_some() && decision != Decision::Prompt { + return Err(Error::InvalidRule( + "reviewer can only be used with decision = \"prompt\"".to_string(), + ) + .into()); + } let justification = match justification { Some(raw) if raw.trim().is_empty() => { @@ -398,6 +417,7 @@ fn policy_builtins(builder: &mut GlobalsBuilder) { }, decision, justification: justification.clone(), + reviewer, }) as RuleRef }) .collect(); diff --git a/codex-rs/execpolicy/src/policy.rs b/codex-rs/execpolicy/src/policy.rs index 3102264e39..4900d92e62 100644 --- a/codex-rs/execpolicy/src/policy.rs +++ b/codex-rs/execpolicy/src/policy.rs @@ -9,6 +9,7 @@ use crate::rule::PrefixPattern; use crate::rule::PrefixRule; use crate::rule::RuleMatch; use crate::rule::RuleRef; +use crate::rule::RuleReviewer; use crate::rule::normalize_network_rule_host; use codex_utils_absolute_path::AbsolutePathBuf; use multimap::MultiMap; @@ -104,6 +105,7 @@ impl Policy { }, decision, justification: None, + reviewer: None, }); self.rules_by_program.insert(first_token.clone(), rule); @@ -355,6 +357,38 @@ pub struct Evaluation { } impl Evaluation { + /// Returns the explicit reviewer requested by matching prompt rules. + /// + /// When multiple prompt rules match, a user reviewer wins over auto-review. + /// None means that no matching prompt rule overrides the caller's + /// configured reviewer. + pub fn prompt_reviewer(&self) -> Option { + let mut reviewer = None; + + for rule_match in &self.matched_rules { + let RuleMatch::PrefixRuleMatch { + decision, + reviewer: Some(rule_reviewer), + .. + } = rule_match + else { + continue; + }; + + if *decision != Decision::Prompt { + continue; + } + + if *rule_reviewer == RuleReviewer::User { + return Some(RuleReviewer::User); + } + + reviewer = Some(RuleReviewer::AutoReview); + } + + reviewer + } + pub fn is_match(&self) -> bool { self.matched_rules .iter() diff --git a/codex-rs/execpolicy/src/rule.rs b/codex-rs/execpolicy/src/rule.rs index 6642cb1d9c..60facfdc6f 100644 --- a/codex-rs/execpolicy/src/rule.rs +++ b/codex-rs/execpolicy/src/rule.rs @@ -11,6 +11,16 @@ use std::any::Any; use std::fmt::Debug; use std::sync::Arc; +/// Selects who should review an approval request produced by a prompt rule. +/// +/// Rules without an explicit reviewer inherit the caller's configured reviewer. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RuleReviewer { + User, + AutoReview, +} + /// Matches a single command token, either a fixed string or one of several allowed alternatives. #[derive(Clone, Debug, Eq, PartialEq)] pub enum PatternToken { @@ -74,6 +84,9 @@ pub enum RuleMatch { /// (e.g., prompt reasons or rejection messages). #[serde(skip_serializing_if = "Option::is_none")] justification: Option, + /// Optional reviewer override for prompt rules. + #[serde(skip_serializing_if = "Option::is_none")] + reviewer: Option, }, HeuristicsRuleMatch { command: Vec, @@ -95,12 +108,14 @@ impl RuleMatch { matched_prefix, decision, justification, + reviewer, .. } => Self::PrefixRuleMatch { matched_prefix, decision, resolved_program: Some(resolved_program.clone()), justification, + reviewer, }, other => other, } @@ -112,6 +127,7 @@ pub struct PrefixRule { pub pattern: PrefixPattern, pub decision: Decision, pub justification: Option, + pub reviewer: Option, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -234,6 +250,7 @@ impl Rule for PrefixRule { decision: self.decision, resolved_program: None, justification: self.justification.clone(), + reviewer: self.reviewer, }) } diff --git a/codex-rs/execpolicy/tests/basic.rs b/codex-rs/execpolicy/tests/basic.rs index f6a86adb27..0b19585028 100644 --- a/codex-rs/execpolicy/tests/basic.rs +++ b/codex-rs/execpolicy/tests/basic.rs @@ -18,6 +18,7 @@ use codex_execpolicy::PrefixPattern; use codex_execpolicy::PrefixRule; use codex_execpolicy::RuleMatch; use codex_execpolicy::RuleRef; +use codex_execpolicy::RuleReviewer; use codex_execpolicy::blocking_append_allow_prefix_rule; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; @@ -159,6 +160,7 @@ prefix_rule( decision: Decision::Allow, resolved_program: None, justification: None, + reviewer: None, }], }, evaluation @@ -191,6 +193,7 @@ prefix_rule( decision: Decision::Forbidden, resolved_program: None, justification: Some("destructive command".to_string()), + reviewer: None, }], }, evaluation @@ -220,6 +223,7 @@ prefix_rule( decision: Decision::Allow, resolved_program: None, justification: Some("safe and commonly used".to_string()), + reviewer: None, }], }, evaluation @@ -246,6 +250,122 @@ prefix_rule( ); } +#[test] +fn prompt_rule_reviewer_is_attached_to_matches() -> Result<()> { + let policy_src = r#" +prefix_rule( + pattern = ["git", "push"], + decision = "prompt", + reviewer = "auto_review", +) + "#; + let mut parser = PolicyParser::new(); + parser.parse("test.rules", policy_src)?; + let policy = parser.build(); + + let evaluation = policy.check(&tokens(&["git", "push", "origin", "main"]), &allow_all); + assert_eq!( + Evaluation { + decision: Decision::Prompt, + matched_rules: vec![RuleMatch::PrefixRuleMatch { + matched_prefix: tokens(&["git", "push"]), + decision: Decision::Prompt, + resolved_program: None, + justification: None, + reviewer: Some(RuleReviewer::AutoReview), + }], + }, + evaluation + ); + assert_eq!(evaluation.prompt_reviewer(), Some(RuleReviewer::AutoReview)); + let serialized = serde_json::to_value(&evaluation)?; + assert_eq!( + serialized["matchedRules"][0]["prefixRuleMatch"]["reviewer"], + "auto_review" + ); + Ok(()) +} + +#[test] +fn prompt_rule_user_reviewer_wins_over_auto_review() -> Result<()> { + let policy_src = r#" +prefix_rule( + pattern = ["git"], + decision = "prompt", + reviewer = "auto_review", +) +prefix_rule( + pattern = ["git", "push"], + decision = "prompt", + reviewer = "user", +) + "#; + let mut parser = PolicyParser::new(); + parser.parse("test.rules", policy_src)?; + let policy = parser.build(); + + let evaluation = policy.check(&tokens(&["git", "push", "origin", "main"]), &allow_all); + assert_eq!(evaluation.prompt_reviewer(), Some(RuleReviewer::User)); + Ok(()) +} + +#[test] +fn prompt_rule_without_reviewer_inherits_configured_reviewer() -> Result<()> { + let policy_src = r#" +prefix_rule( + pattern = ["git", "push"], + decision = "prompt", +) + "#; + let mut parser = PolicyParser::new(); + parser.parse("test.rules", policy_src)?; + let policy = parser.build(); + + let evaluation = policy.check(&tokens(&["git", "push", "origin", "main"]), &allow_all); + assert_eq!(evaluation.prompt_reviewer(), None); + Ok(()) +} + +#[test] +fn reviewer_is_rejected_for_non_prompt_decisions() { + for decision in ["allow", "forbidden"] { + let policy_src = format!( + r#"prefix_rule( + pattern = ["git"], + decision = "{decision}", + reviewer = "user", +)"# + ); + let mut parser = PolicyParser::new(); + let err = parser + .parse("test.rules", &policy_src) + .expect_err("reviewer should require a prompt decision"); + assert!( + err.to_string() + .contains("reviewer can only be used with decision = \"prompt\"") + ); + } +} + +#[test] +fn reviewer_rejects_unknown_values() { + let policy_src = r#" +prefix_rule( + pattern = ["git"], + decision = "prompt", + reviewer = "guardian", +) + "#; + let mut parser = PolicyParser::new(); + let err = parser + .parse("test.rules", policy_src) + .expect_err("unknown reviewer should fail"); + assert!( + err.to_string() + .contains("reviewer must be one of user, auto_review") + ); +} + #[test] fn add_prefix_rule_extends_policy() -> Result<()> { let mut policy = Policy::empty(); @@ -260,6 +380,7 @@ fn add_prefix_rule_extends_policy() -> Result<()> { }, decision: Decision::Prompt, justification: None, + reviewer: None, })], rules ); @@ -273,6 +394,7 @@ fn add_prefix_rule_extends_policy() -> Result<()> { decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: None, }], }, evaluation @@ -321,6 +443,7 @@ prefix_rule( }, decision: Decision::Prompt, justification: None, + reviewer: None, }), RuleSnapshot::Prefix(PrefixRule { pattern: PrefixPattern { @@ -329,6 +452,7 @@ prefix_rule( }, decision: Decision::Forbidden, justification: None, + reviewer: None, }), ], git_rules @@ -343,6 +467,7 @@ prefix_rule( decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: None, }], }, status_eval @@ -358,12 +483,14 @@ prefix_rule( decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: None, }, RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git", "commit"]), decision: Decision::Forbidden, resolved_program: None, justification: None, + reviewer: None, }, ], }, @@ -398,6 +525,7 @@ prefix_rule( }, decision: Decision::Allow, justification: None, + reviewer: None, })], bash_rules ); @@ -409,6 +537,7 @@ prefix_rule( }, decision: Decision::Allow, justification: None, + reviewer: None, })], sh_rules ); @@ -422,6 +551,7 @@ prefix_rule( decision: Decision::Allow, resolved_program: None, justification: None, + reviewer: None, }], }, bash_eval @@ -436,6 +566,7 @@ prefix_rule( decision: Decision::Allow, resolved_program: None, justification: None, + reviewer: None, }], }, sh_eval @@ -470,6 +601,7 @@ prefix_rule( }, decision: Decision::Allow, justification: None, + reviewer: None, })], rules ); @@ -483,6 +615,7 @@ prefix_rule( decision: Decision::Allow, resolved_program: None, justification: None, + reviewer: None, }], }, npm_i @@ -500,6 +633,7 @@ prefix_rule( decision: Decision::Allow, resolved_program: None, justification: None, + reviewer: None, }], }, npm_install @@ -531,6 +665,7 @@ prefix_rule( decision: Decision::Allow, resolved_program: None, justification: None, + reviewer: None, }], }, match_eval @@ -559,6 +694,7 @@ fn strictest_decision_wins_across_matches() -> Result<()> { prefix_rule( pattern = ["git"], decision = "prompt", + reviewer = "user", ) prefix_rule( pattern = ["git", "commit"], @@ -579,12 +715,14 @@ prefix_rule( decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: Some(RuleReviewer::User), }, RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git", "commit"]), decision: Decision::Forbidden, resolved_program: None, justification: None, + reviewer: None, }, ], }, @@ -624,18 +762,21 @@ prefix_rule( decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: None, }, RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git"]), decision: Decision::Prompt, resolved_program: None, justification: None, + reviewer: None, }, RuleMatch::PrefixRuleMatch { matched_prefix: tokens(&["git", "commit"]), decision: Decision::Forbidden, resolved_program: None, justification: None, + reviewer: None, }, ], }, @@ -773,7 +914,7 @@ fn host_executable_resolution_uses_basename_rule_when_allowed() -> Result<()> { let git_path_literal = starlark_string(&git_path); let policy_src = format!( r#" -prefix_rule(pattern = ["git", "status"], decision = "prompt") +prefix_rule(pattern = ["git", "status"], decision = "prompt", reviewer = "user") host_executable(name = "git", paths = ["{git_path_literal}"]) "# ); @@ -797,9 +938,11 @@ host_executable(name = "git", paths = ["{git_path_literal}"]) decision: Decision::Prompt, resolved_program: Some(absolute_path(&git_path)), justification: None, + reviewer: Some(RuleReviewer::User), }], } ); + assert_eq!(evaluation.prompt_reviewer(), Some(RuleReviewer::User)); Ok(()) } @@ -919,6 +1062,7 @@ prefix_rule(pattern = ["git"], decision = "prompt") decision: Decision::Prompt, resolved_program: Some(absolute_path(&git_path)), justification: None, + reviewer: None, }], } ); @@ -956,6 +1100,7 @@ host_executable(name = "git", paths = ["{git_path_literal}"]) decision: Decision::Allow, resolved_program: None, justification: None, + reviewer: None, }], } ); diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index cbc113ff79..1e35cf7f9c 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -227,6 +227,7 @@ async fn run_codex_tool_session_inner( call_id, approval_id: _, reason: _, + approvals_reviewer: _, proposed_execpolicy_amendment: _, proposed_network_policy_amendments: _, parsed_cmd, diff --git a/codex-rs/protocol/src/approvals.rs b/codex-rs/protocol/src/approvals.rs index 5cf4f27f18..8f674e9378 100644 --- a/codex-rs/protocol/src/approvals.rs +++ b/codex-rs/protocol/src/approvals.rs @@ -1,3 +1,4 @@ +use crate::config_types::ApprovalsReviewer; use crate::mcp::RequestId; use crate::models::AdditionalPermissionProfile; use crate::models::PermissionProfile; @@ -248,6 +249,12 @@ pub struct ExecApprovalRequestEvent { /// Optional human-readable reason for the approval (e.g. retry without sandbox). #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option, + /// Optional reviewer selected by the matched exec-policy rule. + /// + /// When absent, clients should use the active turn-level reviewer. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub approvals_reviewer: Option, /// Optional network context for a blocked request that can be approved. #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)]