support reviewer overrides in execpolicy rules

This commit is contained in:
Sama Setty
2026-07-03 21:59:49 +00:00
parent 1f17e7512f
commit 1940a36879
32 changed files with 724 additions and 22 deletions
@@ -3804,6 +3804,7 @@ command = "python3 /enterprise/hooks/pre.py"
decision: Decision::Forbidden,
resolved_program: None,
justification: None,
reviewer: None,
}],
}
);
@@ -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<RequirementsExecPolicyPatternTokenToml>,
pub decision: Option<RequirementsExecPolicyDecisionToml>,
/// 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<RuleReviewer>,
pub justification: Option<String>,
}
@@ -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;
@@ -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::<PrefixRule>()
.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 })
));
}
+1
View File
@@ -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,
},
})
+17 -1
View File
@@ -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,
+108 -2
View File
@@ -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) =
@@ -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,
}],
}
);
+22 -6
View File
@@ -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<String> {
fn derive_prompt_reason(
command_args: &[String],
evaluation: &Evaluation,
reviewer: Option<ApprovalsReviewer>,
) -> Option<String> {
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,
}
+73
View File
@@ -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",
@@ -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)),
},
)
+2
View File
@@ -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;
+48
View File
@@ -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<ApprovalsReviewer>,
) -> Option<ApprovalsReviewer> {
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<String>,
requested_reviewer: Option<ApprovalsReviewer>,
allowed_reviewer: Option<ApprovalsReviewer>,
) -> Option<String> {
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,
+33
View File
@@ -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;
+2
View File
@@ -2129,6 +2129,7 @@ impl Session {
command: Vec<String>,
cwd: AbsolutePathBuf,
reason: Option<String>,
approvals_reviewer: Option<ApprovalsReviewer>,
network_approval_context: Option<NetworkApprovalContext>,
proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
additional_permissions: Option<AdditionalPermissionProfile>,
@@ -2183,6 +2184,7 @@ impl Session {
command,
cwd,
reason,
approvals_reviewer,
network_approval_context,
proposed_execpolicy_amendment,
proposed_network_policy_amendments,
@@ -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,
}],
}
);
@@ -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,
+26 -6
View File
@@ -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?;
@@ -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,
@@ -180,6 +180,7 @@ impl Approvable<ShellRequest> for ShellRuntime {
command,
cwd,
reason,
ctx.approvals_reviewer,
ctx.network_approval_context.clone(),
req.exec_approval_requirement
.proposed_execpolicy_amendment()
@@ -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<ApprovalsReviewer>,
additional_permissions: Option<AdditionalPermissionProfile>,
) -> anyhow::Result<PromptDecision> {
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<ApprovalsReviewer>,
prompt_permissions: Option<AdditionalPermissionProfile>,
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,
@@ -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,
}],
}
);
@@ -221,6 +221,7 @@ impl Approvable<UnifiedExecRequest> 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,
},
);
+15
View File
@@ -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<String>,
pub retry_reason: Option<String>,
/// Optional per-request reviewer selected by a matching exec-policy rule.
pub approvals_reviewer: Option<ApprovalsReviewer>,
pub network_approval_context: Option<NetworkApprovalContext>,
}
@@ -172,6 +175,10 @@ pub(crate) enum ExecApprovalRequirement {
/// Approval required for this tool call.
NeedsApproval {
reason: Option<String>,
/// Optional per-request reviewer selected by a matching exec-policy rule.
///
/// When omitted, approval routing falls back to the turn-level reviewer.
reviewer: Option<ApprovalsReviewer>,
/// 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<ExecPolicyAmendment>,
@@ -194,6 +201,13 @@ impl ExecApprovalRequirement {
_ => None,
}
}
pub fn reviewer(&self) -> Option<ApprovalsReviewer> {
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 {
@@ -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,
}
);
+8 -2
View File
@@ -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": ["<token>", "..."],
"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.
+1
View File
@@ -28,3 +28,4 @@ pub use rule::PrefixRule;
pub use rule::Rule;
pub use rule::RuleMatch;
pub use rule::RuleRef;
pub use rule::RuleReviewer;
+20
View File
@@ -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<Decision> {
}
}
fn parse_rule_reviewer(raw: &str) -> Result<RuleReviewer> {
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<UnpackList<Value<'v>>>,
not_match: Option<UnpackList<Value<'v>>>,
justification: Option<&'v str>,
reviewer: Option<&'v str>,
eval: &mut Evaluator<'v, '_, '_>,
) -> anyhow::Result<NoneType> {
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();
+34
View File
@@ -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<RuleReviewer> {
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()
+17
View File
@@ -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<String>,
/// Optional reviewer override for prompt rules.
#[serde(skip_serializing_if = "Option::is_none")]
reviewer: Option<RuleReviewer>,
},
HeuristicsRuleMatch {
command: Vec<String>,
@@ -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<String>,
pub reviewer: Option<RuleReviewer>,
}
#[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,
})
}
+146 -1
View File
@@ -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,
}],
}
);
@@ -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,
+7
View File
@@ -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<String>,
/// 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<ApprovalsReviewer>,
/// Optional network context for a blocked request that can be approved.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]