Tie network approval reviews to their originating execution (#44575)

## Why

Background commands can outlive their launching turn. Their network reviews need the original execution environment even when current turn settings change, and pending reviews must stop when the execution is cancelled.

## What changed

- Capture the execution's environment snapshot for Guardian network reviews while continuing to use current review settings.
- Deny requests from already cancelled executions before checking session host grants, and resolve pending approvals as denied when execution cancellation interrupts review.
- Preserve accepted review results and session grants when cancellation happens after acceptance.

## Testing

Add regression coverage for same-turn and later-turn settings changes, the original review working directory, cancellation before and after review acceptance, late callbacks, background process termination, and reuse of accepted session grants by new executions.

GitOrigin-RevId: 29487488da9ab43700ba6684c61eea86f30a03a8
This commit is contained in:
Abhinav authored and copyberry committed 2026-09-10 16:17:49 +00:00
1 parent 6bb5be869f
commit bfca0335fa
7 files changed
+586 -172

No files matched your search

+31 -1
View File
@@ -1,4 +1,5 @@
use crate::config::NetworkProxySpec;
use crate::environment_selection::TurnEnvironmentSnapshot;
use crate::guardian::GuardianNetworkAccessTrigger;
use crate::guardian::GuardianReviewContext;
use crate::network_policy_decision::denied_network_policy_message;
@@ -241,6 +242,7 @@ struct ActiveNetworkApprovalCall {
command: String,
environment_id: String,
permission_profile: PermissionProfile,
environments: TurnEnvironmentSnapshot,
cancellation_token: CancellationToken,
}
@@ -639,6 +641,12 @@ impl NetworkApprovalService {
else {
return NetworkDecision::deny(REASON_NOT_ALLOWED);
};
if owner_call
.as_ref()
.is_some_and(|call| call.cancellation_token.is_cancelled())
{
return NetworkDecision::deny(REASON_NOT_ALLOWED);
}
let active_turn = session.active_turn_context_and_strict_auto_review().await;
let Some(environment_id) = active_environment_id.or_else(|| {
active_turn
@@ -720,6 +728,11 @@ impl NetworkApprovalService {
let review_context = GuardianReviewContext::from_resolved_settings(
Arc::clone(&turn_context),
&step_settings,
// Review this new request under current settings, in its originating execution's
// environments. Completing the original turn does not transfer process ownership.
owner_call
.as_ref()
.map_or(&turn_context.environments, |call| &call.environments),
);
if !allows_network_approval_flow(review_context.approval_policy) {
if let Some(owner_call) = owner_call.as_ref() {
@@ -791,7 +804,22 @@ impl NetworkApprovalService {
retry_reason: Some(policy_denial_message.clone()),
network_approval_context: Some(network_approval_context.clone()),
};
let approval_decision = match session.request_approval(action, approval_context).await {
let approval = session.request_approval(action, approval_context);
let approval_result = if let Some(owner_call) = &owner_call {
// A ready review result takes precedence over concurrent cancellation.
let Some(result) = owner_call
.cancellation_token
.run_until_cancelled(approval)
.await
else {
pending_owner.complete(PendingApprovalDecision::Deny);
return NetworkDecision::deny(REASON_NOT_ALLOWED);
};
result
} else {
approval.await
};
let approval_decision = match approval_result {
Ok(decision) => decision,
Err(ToolError::Rejected(rejection)) => {
if let Some(owner_call) = owner_call.as_ref() {
@@ -1067,6 +1095,7 @@ pub(crate) fn build_network_policy_decider(
pub(crate) async fn begin_network_approval(
session: &Arc<Session>,
turn: &TurnContext,
environments: &TurnEnvironmentSnapshot,
managed_network_active: bool,
spec: Option<NetworkApprovalSpec>,
) -> Result<Option<ActiveNetworkApproval>, ToolError> {
@@ -1181,6 +1210,7 @@ pub(crate) async fn begin_network_approval(
command,
environment_id,
permission_profile,
environments: environments.clone(),
cancellation_token: cancellation_token.clone(),
})
.await;
@@ -10,9 +10,155 @@ use core_test_support::test_path_buf;
use futures::poll;
use pretty_assertions::assert_eq;
use std::time::Duration;
use test_case::test_case;
use tokio::time::timeout;
use tokio_util::sync::CancellationToken;
enum ExecutionCancellationTiming {
PendingReview,
AcceptedReview,
}
#[test_case(ExecutionCancellationTiming::PendingReview; "pending_review")]
#[test_case(ExecutionCancellationTiming::AcceptedReview; "accepted_review")]
#[tokio::test]
#[allow(
clippy::await_holding_invalid_type,
reason = "hold the commit lock to cancel execution after the review decision is accepted"
)]
async fn execution_cancellation_respects_network_approval_boundary(
timing: ExecutionCancellationTiming,
) {
use crate::session::tests::make_session_and_context_with_rx;
use crate::tasks::SessionTask;
struct PendingTask;
impl SessionTask for PendingTask {
fn kind(&self) -> crate::state::TaskKind {
crate::state::TaskKind::Regular
}
fn span_name(&self) -> &'static str {
"network_approval_test"
}
async fn run(
self: Arc<Self>,
_session: Arc<Session>,
_ctx: Arc<crate::session::turn_context::TurnContext>,
_input: Vec<crate::session::TurnInput>,
cancellation_token: CancellationToken,
) -> crate::tasks::SessionTaskResult {
cancellation_token.cancelled().await;
Ok(None)
}
}
let (session, _, events) = make_session_and_context_with_rx().await;
let (turn, _) = session
.new_turn_with_sub_id(
"active-turn".to_string(),
crate::session::SessionSettingsUpdate {
step_settings: crate::session::step_settings::StepSettingsUpdate {
approval_policy: Some(AskForApproval::OnRequest),
approvals_reviewer: Some(codex_config::types::ApprovalsReviewer::User),
..Default::default()
},
..Default::default()
},
crate::session::turn_context::NewTurnContextOptions::default(),
)
.await
.unwrap();
session.start_task(turn, Vec::new(), PendingTask).await;
let service = &session.services.network_approval;
register_call_with_default_shell_trigger(service, "execution-1").await;
let request = NetworkPolicyRequest {
protocol: NetworkProtocol::Http,
host: "example.com".to_string(),
port: 80,
environment_id: Some("local".to_string()),
execution_id: Some("execution-1".to_string()),
client_addr: None,
method: None,
command: None,
exec_policy_hint: None,
disconnect: None,
cancellation: None,
};
let decision = service.handle_inline_policy_request(Arc::clone(&session), request.clone());
tokio::pin!(decision);
let approval = timeout(Duration::from_secs(5), async {
loop {
tokio::select! {
result = &mut decision => panic!("expected pending approval, got {result:?}"),
event = events.recv() => {
if let EventMsg::ExecApprovalRequest(approval) = event.unwrap().msg {
break approval;
}
}
}
}
})
.await
.unwrap();
let expected_decision = match timing {
ExecutionCancellationTiming::PendingReview => {
service.record_call_outcome("execution-1", "original execution denial".to_string());
NetworkDecision::deny("not_allowed")
}
ExecutionCancellationTiming::AcceptedReview => {
let commit_guard = service.session_policy_commit_lock.lock().await;
session
.notify_approval(
&approval.effective_approval_id(),
ReviewDecision::ApprovedForSession,
)
.await;
// Consume the approval and stop at the held policy commit lock.
assert!(poll!(decision.as_mut()).is_pending());
service.record_call_outcome("execution-1", "original execution denial".to_string());
assert!(poll!(decision.as_mut()).is_pending());
drop(commit_guard);
NetworkDecision::Allow
}
};
assert_eq!(
timeout(Duration::from_secs(5), &mut decision)
.await
.expect("finish cancelled or accepted review"),
expected_decision,
);
let key =
HostApprovalKey::from_request(&request, NetworkApprovalProtocol::Http, "local".to_string());
assert_eq!(
service.session_approved_hosts.lock().await.contains(&key),
expected_decision == NetworkDecision::Allow,
);
// A late callback must not resurrect the cancelled execution, even with a host grant.
service.session_approved_hosts.lock().await.insert(key);
assert_eq!(
service
.handle_inline_policy_request(Arc::clone(&session), request)
.await,
NetworkDecision::deny("not_allowed"),
);
assert_eq!(
service.take_call_outcome("execution-1").await,
Some("original execution denial".to_string())
);
assert!(service.pending_host_approvals.lock().unwrap().is_empty());
while let Ok(event) = events.try_recv() {
assert!(!matches!(
event.msg,
EventMsg::ExecApprovalRequest(_) | EventMsg::GuardianAssessment(_)
));
}
session
.abort_all_tasks(codex_protocol::protocol::TurnAbortReason::Interrupted)
.await;
}
fn pending_key(host: HostApprovalKey, turn_id: &str, execution_id: &str) -> PendingHostApprovalKey {
PendingHostApprovalKey {
host,
@@ -492,6 +638,7 @@ async fn register_call_with_default_shell_trigger(
command: "curl https://example.com".to_string(),
environment_id: "local".to_string(),
permission_profile: PermissionProfile::workspace_write(),
environments: TurnEnvironmentSnapshot::default(),
cancellation_token: cancellation_token.clone(),
})
.await;
@@ -522,6 +669,7 @@ async fn active_call_preserves_triggering_command_context() {
command: "curl https://example.com".to_string(),
environment_id: "remote".to_string(),
permission_profile: PermissionProfile::workspace_write(),
environments: TurnEnvironmentSnapshot::default(),
cancellation_token: CancellationToken::new(),
})
.await;
+1
View File
@@ -62,6 +62,7 @@ impl ToolOrchestrator {
let network_approval = match begin_network_approval(
&tool_ctx.session,
&tool_ctx.step_context.turn,
&tool_ctx.step_context.environments,
attempt.enforce_managed_network,
network_approval_spec,
)
@@ -293,8 +293,9 @@ impl CoreShellActionProvider {
})?;
let approval_ctx = ApprovalContext {
review_context: GuardianReviewContext::from_resolved_settings(
turn_context,
Arc::clone(&turn_context),
&step_settings,
&turn_context.environments,
),
// The running process can outlive its launching tool or code-mode cell.
cancellation_token: None,