mirror of
https://github.com/openai/codex.git
synced 2026-11-16 14:55:43 +00:00
Centralize tool approval handling in Session (#37128)
## What changed - Move permission hooks, reviewer routing, approval caching, and user approval requests into the session-level approval flow. - Have shell, unified exec, and apply-patch runtimes describe requests as `ApprovalAction` values, which now provide their hook payloads and cache keys. - Pass a shared `ApprovalContext` through initial and retry approvals so telemetry and approval reasons are handled consistently. GitOrigin-RevId: 5bfa61daa97e4427f3a648f6cf9d1c27f1551942
This commit is contained in:
1 parent
9d00bb01c0
commit
778b869829
10 files changed
+414
-451
No files matched your search
@@ -1,24 +1,48 @@
|
||||
//! Central approval policy-stage execution and reviewer routing.
|
||||
|
||||
use crate::command_canonicalization::canonicalize_command_for_approval;
|
||||
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_with_reviewer;
|
||||
use crate::hook_runtime::run_permission_request_hooks;
|
||||
use crate::sandboxing::SandboxPermissions;
|
||||
use crate::session::session::Session;
|
||||
use crate::session::turn_context::TurnContext;
|
||||
use crate::tools::flat_tool_name;
|
||||
use crate::tools::sandboxing::ApprovalCtx;
|
||||
use crate::tools::hook_names::HookToolName;
|
||||
use crate::tools::runtimes::apply_patch::ApplyPatchApprovalKey;
|
||||
use crate::tools::runtimes::shell::ApprovalKey;
|
||||
use crate::tools::runtimes::unified_exec::UnifiedExecApprovalKey;
|
||||
use crate::tools::sandboxing::ApprovalRequestReasons;
|
||||
use crate::tools::sandboxing::PermissionRequestPayload;
|
||||
use crate::tools::sandboxing::ToolError;
|
||||
use crate::tools::sandboxing::ToolRuntime;
|
||||
use codex_config::types::ApprovalsReviewer;
|
||||
use crate::tools::sandboxing::with_cached_approval;
|
||||
use codex_hooks::PermissionRequestDecision;
|
||||
use codex_otel::ToolDecisionSource;
|
||||
use codex_protocol::approvals::ExecPolicyAmendment;
|
||||
use codex_protocol::approvals::NetworkApprovalContext;
|
||||
use codex_protocol::models::AdditionalPermissionProfile;
|
||||
use codex_protocol::protocol::FileChange;
|
||||
use codex_protocol::protocol::NetworkPolicyRuleAction;
|
||||
use codex_protocol::protocol::ReviewDecision;
|
||||
use codex_tools::ToolName;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ApprovalContext {
|
||||
pub(crate) turn: Arc<TurnContext>,
|
||||
pub(crate) call_id: String,
|
||||
pub(crate) tool_name: ToolName,
|
||||
pub(crate) strict_auto_review: bool,
|
||||
pub(crate) approval_reason: Option<String>,
|
||||
pub(crate) retry_reason: Option<String>,
|
||||
pub(crate) network_approval_context: Option<NetworkApprovalContext>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) enum ApprovalAction {
|
||||
@@ -26,20 +50,24 @@ pub(crate) enum ApprovalAction {
|
||||
id: String,
|
||||
environment_id: String,
|
||||
command: Vec<String>,
|
||||
hook_command: String,
|
||||
cwd: PathUri,
|
||||
sandbox_permissions: SandboxPermissions,
|
||||
additional_permissions: Option<AdditionalPermissionProfile>,
|
||||
justification: Option<String>,
|
||||
proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
|
||||
},
|
||||
ExecCommand {
|
||||
id: String,
|
||||
environment_id: String,
|
||||
command: Vec<String>,
|
||||
hook_command: String,
|
||||
cwd: PathUri,
|
||||
sandbox_permissions: SandboxPermissions,
|
||||
additional_permissions: Option<AdditionalPermissionProfile>,
|
||||
justification: Option<String>,
|
||||
tty: bool,
|
||||
proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
|
||||
},
|
||||
ApplyPatch {
|
||||
id: String,
|
||||
@@ -47,10 +75,88 @@ pub(crate) enum ApprovalAction {
|
||||
cwd: PathUri,
|
||||
files: Vec<PathUri>,
|
||||
patch: String,
|
||||
changes: Arc<HashMap<PathBuf, FileChange>>,
|
||||
permissions_preapproved: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub(crate) enum ApprovalCacheKey {
|
||||
Shell(ApprovalKey),
|
||||
ExecCommand(UnifiedExecApprovalKey),
|
||||
ApplyPatch(ApplyPatchApprovalKey),
|
||||
}
|
||||
|
||||
impl ApprovalAction {
|
||||
pub(crate) fn permission_request_payload(&self) -> PermissionRequestPayload {
|
||||
match self {
|
||||
Self::Shell {
|
||||
hook_command,
|
||||
justification,
|
||||
..
|
||||
}
|
||||
| Self::ExecCommand {
|
||||
hook_command,
|
||||
justification,
|
||||
..
|
||||
} => PermissionRequestPayload::bash(hook_command.clone(), justification.clone()),
|
||||
Self::ApplyPatch { patch, .. } => PermissionRequestPayload {
|
||||
tool_name: HookToolName::apply_patch(),
|
||||
tool_input: serde_json::json!({ "command": patch }),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cache_keys(&self) -> Vec<ApprovalCacheKey> {
|
||||
match self {
|
||||
Self::Shell {
|
||||
environment_id,
|
||||
command,
|
||||
cwd,
|
||||
sandbox_permissions,
|
||||
additional_permissions,
|
||||
..
|
||||
} => vec![ApprovalCacheKey::Shell(ApprovalKey {
|
||||
environment_id: environment_id.clone(),
|
||||
command: canonicalize_command_for_approval(command),
|
||||
cwd: cwd.clone(),
|
||||
sandbox_permissions: *sandbox_permissions,
|
||||
additional_permissions: additional_permissions.clone(),
|
||||
})],
|
||||
Self::ExecCommand {
|
||||
environment_id,
|
||||
command,
|
||||
cwd,
|
||||
tty,
|
||||
sandbox_permissions,
|
||||
additional_permissions,
|
||||
..
|
||||
} => vec![ApprovalCacheKey::ExecCommand(UnifiedExecApprovalKey {
|
||||
environment_id: environment_id.clone(),
|
||||
command: canonicalize_command_for_approval(command),
|
||||
cwd: cwd.clone(),
|
||||
tty: *tty,
|
||||
sandbox_permissions: *sandbox_permissions,
|
||||
additional_permissions: additional_permissions.clone(),
|
||||
})],
|
||||
Self::ApplyPatch {
|
||||
environment_id,
|
||||
files,
|
||||
..
|
||||
} => files
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|path| {
|
||||
ApprovalCacheKey::ApplyPatch(ApplyPatchApprovalKey {
|
||||
environment_id: environment_id.clone(),
|
||||
path,
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn into_guardian_request(self) -> std::io::Result<crate::guardian::GuardianApprovalRequest> {
|
||||
Ok(match self {
|
||||
Self::Shell {
|
||||
@@ -61,6 +167,7 @@ impl ApprovalAction {
|
||||
sandbox_permissions,
|
||||
additional_permissions,
|
||||
justification,
|
||||
..
|
||||
} => crate::guardian::GuardianApprovalRequest::Shell {
|
||||
id,
|
||||
command,
|
||||
@@ -78,6 +185,7 @@ impl ApprovalAction {
|
||||
additional_permissions,
|
||||
justification,
|
||||
tty,
|
||||
..
|
||||
} => crate::guardian::GuardianApprovalRequest::ExecCommand {
|
||||
id,
|
||||
command,
|
||||
@@ -93,6 +201,7 @@ impl ApprovalAction {
|
||||
cwd,
|
||||
files,
|
||||
patch,
|
||||
..
|
||||
} => crate::guardian::GuardianApprovalRequest::ApplyPatch {
|
||||
id,
|
||||
cwd: guardian_cwd(&environment_id, cwd)?,
|
||||
@@ -129,18 +238,14 @@ fn guardian_cwd(environment_id: &str, cwd: PathUri) -> std::io::Result<AbsoluteP
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum ApprovalReviewer {
|
||||
enum ApprovalReviewer {
|
||||
Guardian,
|
||||
User,
|
||||
}
|
||||
|
||||
impl ApprovalReviewer {
|
||||
pub(super) fn for_turn(turn: &TurnContext) -> Self {
|
||||
Self::for_reviewer(turn, turn.config.approvals_reviewer)
|
||||
}
|
||||
|
||||
fn for_reviewer(turn: &TurnContext, reviewer: ApprovalsReviewer) -> Self {
|
||||
if routes_approval_to_guardian_with_reviewer(turn, reviewer) {
|
||||
fn for_turn(turn: &TurnContext) -> Self {
|
||||
if routes_approval_to_guardian_with_reviewer(turn, turn.config.approvals_reviewer) {
|
||||
Self::Guardian
|
||||
} else {
|
||||
Self::User
|
||||
@@ -187,102 +292,207 @@ impl ApprovalResolution {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_tool_approval<Rq, Out, T>(
|
||||
tool: &mut T,
|
||||
req: &Rq,
|
||||
ctx: ApprovalCtx<'_>,
|
||||
reviewer: ApprovalReviewer,
|
||||
) -> Result<ReviewDecision, ToolError>
|
||||
where
|
||||
T: ToolRuntime<Rq, Out>,
|
||||
{
|
||||
if let Some(permission_request) = tool.permission_request_payload(req) {
|
||||
impl Session {
|
||||
pub(crate) async fn request_approval(
|
||||
self: &Arc<Self>,
|
||||
action: ApprovalAction,
|
||||
ctx: ApprovalContext,
|
||||
) -> Result<ReviewDecision, ToolError> {
|
||||
let permission_request_run_id = ctx
|
||||
.reasons
|
||||
.retry
|
||||
.retry_reason
|
||||
.as_ref()
|
||||
.map(|_| format!("{}:retry", ctx.call_id));
|
||||
match run_permission_request_hooks(
|
||||
ctx.session,
|
||||
ctx.turn,
|
||||
permission_request_run_id.as_deref().unwrap_or(ctx.call_id),
|
||||
permission_request,
|
||||
|
||||
// Approval precedence is:
|
||||
// 1. Hooks
|
||||
// 2. If StrictAutoReview || Guardian enabled, then Guardian. Else, user.
|
||||
let resolution = match run_permission_request_hooks(
|
||||
self,
|
||||
&ctx.turn,
|
||||
permission_request_run_id.as_deref().unwrap_or(&ctx.call_id),
|
||||
action.permission_request_payload(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Some(PermissionRequestDecision::Allow) => {
|
||||
let resolution = ApprovalResolution {
|
||||
decision: ReviewDecision::Approved,
|
||||
source: ApprovalResolutionSource::Hook,
|
||||
};
|
||||
record_resolution(&ctx, &resolution);
|
||||
return resolution.into_tool_result();
|
||||
}
|
||||
Some(PermissionRequestDecision::Deny { message }) => {
|
||||
let resolution = ApprovalResolution {
|
||||
decision: ReviewDecision::denied(message),
|
||||
source: ApprovalResolutionSource::Hook,
|
||||
};
|
||||
record_resolution(&ctx, &resolution);
|
||||
return resolution.into_tool_result();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
Some(PermissionRequestDecision::Allow) => ApprovalResolution {
|
||||
decision: ReviewDecision::Approved,
|
||||
source: ApprovalResolutionSource::Hook,
|
||||
},
|
||||
Some(PermissionRequestDecision::Deny { message }) => ApprovalResolution {
|
||||
decision: ReviewDecision::denied(message),
|
||||
source: ApprovalResolutionSource::Hook,
|
||||
},
|
||||
None => self.request_reviewer_approval(action, &ctx).await,
|
||||
};
|
||||
record_resolution(&ctx, &resolution);
|
||||
resolution.into_tool_result()
|
||||
}
|
||||
|
||||
let resolution = match reviewer {
|
||||
ApprovalReviewer::Guardian => {
|
||||
let review_id = new_guardian_review_id();
|
||||
let action = match tool
|
||||
.approval_action(req, &ctx)
|
||||
.and_then(ApprovalAction::into_guardian_request)
|
||||
{
|
||||
Ok(action) => action,
|
||||
Err(err) => {
|
||||
tracing::error!(%err, "failed to build automatic approval action");
|
||||
let resolution = ApprovalResolution {
|
||||
decision: ReviewDecision::denied(
|
||||
"automatic approval review could not prepare the action",
|
||||
),
|
||||
source: ApprovalResolutionSource::Guardian,
|
||||
};
|
||||
record_resolution(&ctx, &resolution);
|
||||
return resolution.into_tool_result();
|
||||
async fn request_reviewer_approval(
|
||||
self: &Arc<Self>,
|
||||
action: ApprovalAction,
|
||||
ctx: &ApprovalContext,
|
||||
) -> ApprovalResolution {
|
||||
let reviewer = if ctx.strict_auto_review {
|
||||
ApprovalReviewer::Guardian
|
||||
} else {
|
||||
ApprovalReviewer::for_turn(&ctx.turn)
|
||||
};
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
async fn request_guardian_approval(
|
||||
self: &Arc<Self>,
|
||||
action: ApprovalAction,
|
||||
ctx: &ApprovalContext,
|
||||
) -> ReviewDecision {
|
||||
let review_id = new_guardian_review_id();
|
||||
let action = match action.into_guardian_request() {
|
||||
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",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
review_approval_request(
|
||||
self,
|
||||
&ctx.turn,
|
||||
review_id,
|
||||
action,
|
||||
ApprovalRequestReasons {
|
||||
approval: ctx.approval_reason.clone(),
|
||||
retry: ctx.retry_reason.clone(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn request_user_approval(
|
||||
&self,
|
||||
action: &ApprovalAction,
|
||||
ctx: &ApprovalContext,
|
||||
) -> ReviewDecision {
|
||||
match action {
|
||||
ApprovalAction::Shell {
|
||||
environment_id,
|
||||
command,
|
||||
cwd,
|
||||
additional_permissions,
|
||||
justification,
|
||||
proposed_execpolicy_amendment,
|
||||
..
|
||||
}
|
||||
| ApprovalAction::ExecCommand {
|
||||
environment_id,
|
||||
command,
|
||||
cwd,
|
||||
additional_permissions,
|
||||
justification,
|
||||
proposed_execpolicy_amendment,
|
||||
..
|
||||
} => {
|
||||
let cwd = match guardian_cwd(environment_id, cwd.clone()) {
|
||||
Ok(cwd) => cwd,
|
||||
Err(err) => {
|
||||
tracing::error!(%err, "failed to resolve approval command cwd");
|
||||
return ReviewDecision::Abort;
|
||||
}
|
||||
};
|
||||
let tool_name = match action {
|
||||
ApprovalAction::Shell { .. } => "shell",
|
||||
ApprovalAction::ExecCommand { .. } => "unified_exec",
|
||||
ApprovalAction::ApplyPatch { .. } => unreachable!("matched command approval"),
|
||||
};
|
||||
let reason = ctx
|
||||
.retry_reason
|
||||
.clone()
|
||||
.or_else(|| ctx.approval_reason.clone())
|
||||
.or_else(|| justification.clone());
|
||||
with_cached_approval(&self.services, tool_name, action.cache_keys(), || async {
|
||||
self.request_command_approval(
|
||||
&ctx.turn,
|
||||
ctx.call_id.clone(),
|
||||
/*approval_id*/ None,
|
||||
Some(environment_id.clone()),
|
||||
command.clone(),
|
||||
cwd,
|
||||
reason,
|
||||
ctx.network_approval_context.clone(),
|
||||
proposed_execpolicy_amendment.clone(),
|
||||
additional_permissions.clone(),
|
||||
/*available_decisions*/ None,
|
||||
/*plugin_attribution_override*/ None,
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await
|
||||
}
|
||||
ApprovalAction::ApplyPatch {
|
||||
changes,
|
||||
permissions_preapproved,
|
||||
..
|
||||
} => {
|
||||
let reason = ctx
|
||||
.retry_reason
|
||||
.clone()
|
||||
.or_else(|| ctx.approval_reason.clone());
|
||||
if *permissions_preapproved && reason.is_none() {
|
||||
return ReviewDecision::Approved;
|
||||
}
|
||||
};
|
||||
review_approval_request(
|
||||
ctx.session,
|
||||
ctx.turn,
|
||||
review_id,
|
||||
action,
|
||||
ctx.reasons.clone(),
|
||||
)
|
||||
.await
|
||||
if reason.is_some() {
|
||||
return self
|
||||
.request_patch_approval(
|
||||
&ctx.turn,
|
||||
ctx.call_id.clone(),
|
||||
changes.as_ref().clone(),
|
||||
reason,
|
||||
/*grant_root*/ None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
with_cached_approval(
|
||||
&self.services,
|
||||
"apply_patch",
|
||||
action.cache_keys(),
|
||||
|| async {
|
||||
self.request_patch_approval(
|
||||
&ctx.turn,
|
||||
ctx.call_id.clone(),
|
||||
changes.as_ref().clone(),
|
||||
/*reason*/ None,
|
||||
/*grant_root*/ None,
|
||||
)
|
||||
.await
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
ApprovalReviewer::User => tool.start_approval_async(req, ctx.clone()).await,
|
||||
};
|
||||
let source = match reviewer {
|
||||
ApprovalReviewer::Guardian => ApprovalResolutionSource::Guardian,
|
||||
ApprovalReviewer::User => ApprovalResolutionSource::User,
|
||||
};
|
||||
let resolution = ApprovalResolution {
|
||||
decision: resolution,
|
||||
source,
|
||||
};
|
||||
record_resolution(&ctx, &resolution);
|
||||
resolution.into_tool_result()
|
||||
}
|
||||
}
|
||||
|
||||
fn record_resolution(ctx: &ApprovalCtx<'_>, resolution: &ApprovalResolution) {
|
||||
fn record_resolution(ctx: &ApprovalContext, resolution: &ApprovalResolution) {
|
||||
let source = match resolution.source {
|
||||
ApprovalResolutionSource::Hook => ToolDecisionSource::Config,
|
||||
ApprovalResolutionSource::Guardian => ToolDecisionSource::AutomatedReviewer,
|
||||
ApprovalResolutionSource::User => ToolDecisionSource::User,
|
||||
};
|
||||
let tool_name = flat_tool_name(ctx.tool_name);
|
||||
let tool_name = flat_tool_name(&ctx.tool_name);
|
||||
ctx.turn.session_telemetry.tool_decision(
|
||||
tool_name.as_ref(),
|
||||
ctx.call_id,
|
||||
&ctx.call_id,
|
||||
&resolution.decision,
|
||||
source,
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user