mirror of
https://github.com/openai/codex.git
synced 2026-11-20 22:40:37 +00:00
Route approvals through the extension decision API (#43432)
## What changed - Let approval extensions choose between cached approval, synchronous review, and a user prompt for tool and permission requests, while core enforces mandatory Guardian and fresh-review requirements. - Carry an optional `review_reason` on Guardian assessment events and use it to trigger strict-review notifications, retaining the fallback for older events. - Require synchronous review when cached evidence has an unusable encrypted parent compaction. ## Testing Add regression coverage for manual prompts and cached approvals with non-UTF-8 working directories. Update approval contributors in existing tests to use the decision API. GitOrigin-RevId: a4e66416070bdaa881daa41429c49021629f44c1
This commit is contained in:
@@ -5,12 +5,10 @@ use crate::exec_policy::prompt_is_rejected_by_policy;
|
||||
use crate::guardian::GuardianNetworkAccessTrigger;
|
||||
use crate::guardian::GuardianReviewContext;
|
||||
use crate::guardian::GuardianReviewOptions;
|
||||
use crate::guardian::decide_approval;
|
||||
use crate::guardian::guardian_timeout_message;
|
||||
use crate::guardian::new_guardian_review_id;
|
||||
use crate::guardian::review_approval_request;
|
||||
use crate::guardian::review_approval_request_with_cancel;
|
||||
use crate::guardian::routes_approval_policy_to_guardian;
|
||||
use crate::guardian::spawn_approval_request_review;
|
||||
use crate::guardian::spawn_approval_decision;
|
||||
use crate::hook_runtime::run_permission_request_hooks;
|
||||
use crate::mcp_tool_call::request_mcp_tool_user_approval;
|
||||
use crate::sandboxing::SandboxPermissions;
|
||||
@@ -64,12 +62,14 @@ pub(crate) struct ApprovalContext {
|
||||
pub(crate) network_approval_context: Option<NetworkApprovalContext>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
|
||||
#[serde(tag = "tool", rename_all = "snake_case")]
|
||||
pub(crate) enum ApprovalAction {
|
||||
ExecCommand {
|
||||
id: String,
|
||||
environment_id: String,
|
||||
command: Vec<String>,
|
||||
#[serde(skip_serializing)]
|
||||
hook_command: String,
|
||||
cwd: PathUri,
|
||||
sandbox_permissions: SandboxPermissions,
|
||||
@@ -107,6 +107,7 @@ pub(crate) enum ApprovalAction {
|
||||
cwd: PathUri,
|
||||
files: Vec<PathUri>,
|
||||
patch: String,
|
||||
#[serde(skip_serializing)]
|
||||
changes: Arc<HashMap<PathBuf, FileChange>>,
|
||||
permissions_preapproved: bool,
|
||||
},
|
||||
@@ -122,6 +123,7 @@ pub(crate) enum ApprovalAction {
|
||||
tool_title: Option<String>,
|
||||
tool_description: Option<String>,
|
||||
annotations: Option<crate::guardian::GuardianMcpAnnotations>,
|
||||
#[serde(skip_serializing)]
|
||||
hook_tool_name: HookToolName,
|
||||
approval_policy: AskForApproval,
|
||||
reviewer: ApprovalsReviewer,
|
||||
@@ -138,7 +140,9 @@ pub(crate) enum ApprovalAction {
|
||||
protocol: NetworkApprovalProtocol,
|
||||
port: u16,
|
||||
trigger: Option<GuardianNetworkAccessTrigger>,
|
||||
#[serde(skip_serializing)]
|
||||
hook_command: String,
|
||||
#[serde(skip_serializing)]
|
||||
hook_run_id: String,
|
||||
command: Vec<String>,
|
||||
cwd: AbsolutePathBuf,
|
||||
@@ -414,22 +418,6 @@ impl ApprovalAction {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum ApprovalReviewer {
|
||||
Guardian,
|
||||
User,
|
||||
}
|
||||
|
||||
impl ApprovalReviewer {
|
||||
fn for_policy(approval_policy: AskForApproval, reviewer: ApprovalsReviewer) -> Self {
|
||||
if routes_approval_policy_to_guardian(approval_policy, reviewer) {
|
||||
Self::Guardian
|
||||
} else {
|
||||
Self::User
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum ApprovalResolutionSource {
|
||||
Hook,
|
||||
@@ -556,51 +544,33 @@ impl Session {
|
||||
action: ApprovalAction,
|
||||
ctx: &ApprovalContext,
|
||||
) -> ApprovalResolution {
|
||||
let reviewer = if ctx.strict_auto_review {
|
||||
ApprovalReviewer::Guardian
|
||||
} else if let ApprovalAction::McpToolCall {
|
||||
approval_policy,
|
||||
reviewer,
|
||||
..
|
||||
} = &action
|
||||
{
|
||||
ApprovalReviewer::for_policy(*approval_policy, *reviewer)
|
||||
if let Some(decision) = self.request_guardian_approval(action.clone(), ctx).await {
|
||||
ApprovalResolution {
|
||||
decision,
|
||||
source: ApprovalResolutionSource::Guardian,
|
||||
}
|
||||
} else {
|
||||
ApprovalReviewer::for_policy(
|
||||
ctx.review_context.approval_policy,
|
||||
ctx.review_context.approvals_reviewer,
|
||||
)
|
||||
};
|
||||
|
||||
let decision = match reviewer {
|
||||
ApprovalReviewer::Guardian => self.request_guardian_approval(action, ctx).await,
|
||||
ApprovalReviewer::User => self.request_user_approval(&action, ctx).await,
|
||||
};
|
||||
let source = match reviewer {
|
||||
ApprovalReviewer::Guardian => ApprovalResolutionSource::Guardian,
|
||||
ApprovalReviewer::User => ApprovalResolutionSource::User,
|
||||
};
|
||||
ApprovalResolution { decision, source }
|
||||
ApprovalResolution {
|
||||
decision: self.request_user_approval(&action, ctx).await,
|
||||
source: ApprovalResolutionSource::User,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn request_guardian_approval(
|
||||
self: &Arc<Self>,
|
||||
action: ApprovalAction,
|
||||
ctx: &ApprovalContext,
|
||||
) -> ReviewDecision {
|
||||
// Guardian inherits only the current turn's ready environments. A retained
|
||||
// terminal handle may outlive its selection, but must not be reviewed in
|
||||
// a different environment that happens to have the same launch directory.
|
||||
if let ApprovalAction::WriteStdin { environment_id, .. } = &action
|
||||
&& !ctx
|
||||
.review_context
|
||||
.environments()
|
||||
.turn_environments()
|
||||
.any(|environment| environment.selection.environment_id == *environment_id)
|
||||
) -> Option<ReviewDecision> {
|
||||
let mut context = ctx.review_context.clone();
|
||||
if let ApprovalAction::McpToolCall {
|
||||
approval_policy,
|
||||
reviewer,
|
||||
..
|
||||
} = &action
|
||||
{
|
||||
return ReviewDecision::denied(
|
||||
"automatic approval review cannot access the terminal's environment; select it before retrying",
|
||||
);
|
||||
context.approval_policy = *approval_policy;
|
||||
context.approvals_reviewer = *reviewer;
|
||||
}
|
||||
let is_network_approval = matches!(&action, ApprovalAction::NetworkAccess { .. });
|
||||
let review_id = new_guardian_review_id();
|
||||
@@ -628,74 +598,67 @@ impl Session {
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let action = match action.into_guardian_request(exec_command_cwd_convention) {
|
||||
Ok(action) => action,
|
||||
Err(err) => {
|
||||
tracing::error!(%err, "failed to build automatic approval action");
|
||||
return ReviewDecision::denied(
|
||||
"automatic approval review could not prepare the action",
|
||||
);
|
||||
}
|
||||
};
|
||||
let action = crate::guardian::ReviewAction::from_approval_action(
|
||||
action,
|
||||
exec_command_cwd_convention,
|
||||
);
|
||||
|
||||
if let Some(cancellation_token) = &ctx.cancellation_token {
|
||||
let review = spawn_approval_request_review(
|
||||
let reasons = ApprovalRequestReasons {
|
||||
approval: ctx.approval_reason.clone(),
|
||||
retry: ctx.retry_reason.clone(),
|
||||
};
|
||||
let options = GuardianReviewOptions {
|
||||
require_guardian: ctx.strict_auto_review,
|
||||
plugin_attribution_override: None,
|
||||
approval_request_source: GuardianApprovalRequestSource::MainTurn,
|
||||
external_cancel: ctx.cancellation_token.clone(),
|
||||
require_synchronous_review: false,
|
||||
};
|
||||
if ctx.cancellation_token.is_some() {
|
||||
spawn_approval_decision(
|
||||
Arc::clone(self),
|
||||
ctx.review_context.clone(),
|
||||
context,
|
||||
review_id,
|
||||
action,
|
||||
ApprovalRequestReasons {
|
||||
approval: ctx.approval_reason.clone(),
|
||||
retry: ctx.retry_reason.clone(),
|
||||
},
|
||||
GuardianReviewOptions {
|
||||
plugin_attribution_override: None,
|
||||
approval_request_source: GuardianApprovalRequestSource::MainTurn,
|
||||
external_cancel: Some(cancellation_token.clone()),
|
||||
require_synchronous_review: false,
|
||||
},
|
||||
);
|
||||
review.await.unwrap_or_else(|_| {
|
||||
ReviewDecision::denied("automatic approval review could not complete")
|
||||
reasons,
|
||||
options,
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|_| {
|
||||
Some(ReviewDecision::denied(
|
||||
"automatic approval review could not complete",
|
||||
))
|
||||
})
|
||||
} else if is_network_approval {
|
||||
let review_cancel = CancellationToken::new();
|
||||
let review_cancel_guard = review_cancel.clone().drop_guard();
|
||||
let review_session = Arc::clone(self);
|
||||
let review_context = ctx.review_context.clone();
|
||||
let retry_reason = ctx.retry_reason.clone();
|
||||
let review = tokio::spawn(async move {
|
||||
review_approval_request_with_cancel(
|
||||
&review_session,
|
||||
review_context,
|
||||
review_id,
|
||||
action,
|
||||
retry_reason,
|
||||
GuardianReviewOptions {
|
||||
plugin_attribution_override: None,
|
||||
approval_request_source: GuardianApprovalRequestSource::MainTurn,
|
||||
external_cancel: Some(review_cancel),
|
||||
require_synchronous_review: false,
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
let review = tokio::spawn(decide_approval(
|
||||
Arc::clone(self),
|
||||
context,
|
||||
review_id,
|
||||
action,
|
||||
reasons,
|
||||
GuardianReviewOptions {
|
||||
external_cancel: Some(review_cancel),
|
||||
..options
|
||||
},
|
||||
));
|
||||
let decision = review.await.unwrap_or_else(|err| {
|
||||
warn!("network Guardian review task failed: {err}");
|
||||
ReviewDecision::denied("automatic approval review could not complete")
|
||||
Some(ReviewDecision::denied(
|
||||
"automatic approval review could not complete",
|
||||
))
|
||||
});
|
||||
drop(review_cancel_guard.disarm());
|
||||
decision
|
||||
} else {
|
||||
review_approval_request(
|
||||
self,
|
||||
ctx.review_context.clone(),
|
||||
decide_approval(
|
||||
Arc::clone(self),
|
||||
context,
|
||||
review_id,
|
||||
action,
|
||||
ApprovalRequestReasons {
|
||||
approval: ctx.approval_reason.clone(),
|
||||
retry: ctx.retry_reason.clone(),
|
||||
},
|
||||
reasons,
|
||||
options,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -76,6 +76,109 @@ fn approval_resolution_uses_acting_model_timeout_instructions() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test_case::test_case(ApprovalsReviewer::User, codex_extension_api::ApprovalDecision::AskUser; "manual prompt")]
|
||||
#[test_case::test_case(ApprovalsReviewer::AutoReview, codex_extension_api::ApprovalDecision::Allow; "cached allow")]
|
||||
#[tokio::test]
|
||||
async fn non_utf8_cwd_preserves_approval_routing(
|
||||
reviewer: ApprovalsReviewer,
|
||||
decision: codex_extension_api::ApprovalDecision,
|
||||
) -> anyhow::Result<()> {
|
||||
use anyhow::Context;
|
||||
use codex_extension_api::ApprovalDecision;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
|
||||
struct Contributor {
|
||||
cwd: codex_utils_path_uri::LegacyAppPathString,
|
||||
decision: ApprovalDecision,
|
||||
}
|
||||
|
||||
impl codex_extension_api::ApprovalReviewContributor for Contributor {
|
||||
fn decide<'a>(
|
||||
&'a self,
|
||||
input: &'a codex_extension_api::ApprovalDecisionInput<'_>,
|
||||
) -> codex_extension_api::ExtensionFuture<'a, Option<ApprovalDecision>> {
|
||||
Box::pin(async move {
|
||||
assert_eq!(input.action["cwd"], serde_json::json!(self.cwd));
|
||||
Some(self.decision.clone())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let cwd = PathUri::from_abs_path(&AbsolutePathBuf::try_from(PathBuf::from(
|
||||
std::ffi::OsString::from_vec(b"/tmp/non-utf8-\xe9".to_vec()),
|
||||
))?);
|
||||
let (mut session, turn, events) = make_session_and_context_with_rx().await;
|
||||
let mut extensions = codex_extension_api::ExtensionRegistryBuilder::new();
|
||||
extensions.approval_review_contributor(Arc::new(Contributor {
|
||||
cwd: codex_utils_path_uri::LegacyAppPathString::from_path_uri(&cwd, PathConvention::Posix)?,
|
||||
decision,
|
||||
}));
|
||||
Arc::get_mut(&mut session)
|
||||
.context("session is uniquely owned")?
|
||||
.services
|
||||
.extensions = Arc::new(extensions.build());
|
||||
*session.active_turn.lock().await = Some(crate::state::ActiveTurn::default());
|
||||
let mut review_context = GuardianReviewContext::from(&turn);
|
||||
review_context.approval_policy = AskForApproval::OnRequest;
|
||||
review_context.approvals_reviewer = reviewer;
|
||||
let context = ApprovalContext {
|
||||
review_context,
|
||||
cancellation_token: None,
|
||||
call_id: "non-utf8-cwd".to_string(),
|
||||
tool_name: ToolName::plain("exec_command"),
|
||||
strict_auto_review: false,
|
||||
approval_reason: None,
|
||||
retry_reason: None,
|
||||
network_approval_context: None,
|
||||
};
|
||||
let action = ApprovalAction::ExecCommand {
|
||||
id: context.call_id.clone(),
|
||||
environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
command: vec!["npm".to_string(), "install".to_string()],
|
||||
hook_command: "npm install".to_string(),
|
||||
cwd: cwd.clone(),
|
||||
sandbox_permissions: if reviewer == ApprovalsReviewer::User {
|
||||
SandboxPermissions::RequireEscalated
|
||||
} else {
|
||||
SandboxPermissions::UseDefault
|
||||
},
|
||||
additional_permissions: None,
|
||||
justification: None,
|
||||
tty: false,
|
||||
proposed_execpolicy_amendment: None,
|
||||
};
|
||||
let approval = session.request_reviewer_approval(action, &context);
|
||||
tokio::pin!(approval);
|
||||
let expected = if reviewer == ApprovalsReviewer::User {
|
||||
tokio::select! {
|
||||
resolution = &mut approval => panic!("expected a user prompt, got {resolution:?}"),
|
||||
event = events.recv() => {
|
||||
let codex_protocol::protocol::EventMsg::ExecApprovalRequest(request) =
|
||||
event.context("receive user prompt")?.msg
|
||||
else {
|
||||
panic!("expected a command approval prompt");
|
||||
};
|
||||
assert_eq!(request.cwd, codex_utils_path_uri::LegacyAppPathString::from(cwd));
|
||||
assert_eq!(request.command, vec!["npm", "install"]);
|
||||
session.notify_approval(&request.call_id, ReviewDecision::Approved).await;
|
||||
}
|
||||
}
|
||||
ApprovalResolution {
|
||||
decision: ReviewDecision::Approved,
|
||||
source: ApprovalResolutionSource::User,
|
||||
}
|
||||
} else {
|
||||
ApprovalResolution {
|
||||
decision: ReviewDecision::Approved,
|
||||
source: ApprovalResolutionSource::Guardian,
|
||||
}
|
||||
};
|
||||
assert_eq!(approval.await, expected);
|
||||
assert!(events.try_recv().is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_mcp_reviewer_override_takes_precedence_over_action_context() {
|
||||
let (session, turn, events) = make_session_and_context_with_rx().await;
|
||||
|
||||
Reference in New Issue
Block a user