diff --git a/codex-rs/core/src/tools/network_approval.rs b/codex-rs/core/src/tools/network_approval.rs index 4632966bf9..0a25366972 100644 --- a/codex-rs/core/src/tools/network_approval.rs +++ b/codex-rs/core/src/tools/network_approval.rs @@ -49,7 +49,6 @@ use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use tokio::sync::Mutex; use tokio::sync::Notify; -use tokio::sync::OnceCell; use tokio::sync::OwnedSemaphorePermit; use tokio::sync::RwLock; use tokio::sync::Semaphore; @@ -82,19 +81,42 @@ struct NetworkApprovalProxy { shared_ingress_for_remote: Option>, } +/// Owns the service entry from registration through command completion. +/// The map never owns this guard; cancelling startup therefore removes its entry on drop. +#[derive(Debug)] +struct NetworkApprovalRegistration { + registration_id: String, + calls: std::sync::Weak>, + finish_outcome: SyncOnceLock>, +} + +impl NetworkApprovalRegistration { + fn finish(&self) -> &Option { + self.finish_outcome.get_or_init(|| { + let calls = self.calls.upgrade()?; + let mut calls = calls + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + calls.active_calls.shift_remove(&self.registration_id); + calls.call_outcomes.remove(&self.registration_id) + }) + } +} + +impl Drop for NetworkApprovalRegistration { + fn drop(&mut self) { + let _ = self.finish(); + } +} + #[derive(Clone, Debug)] pub(crate) struct DeferredNetworkApproval { - registration_id: String, + registration: Arc, cancellation_token: CancellationToken, - finish_outcome: Arc>>, _execution_proxy: Option, } impl DeferredNetworkApproval { - pub(crate) fn registration_id(&self) -> &str { - &self.registration_id - } - pub(crate) fn cancellation_token(&self) -> CancellationToken { self.cancellation_token.clone() } @@ -117,21 +139,19 @@ impl DeferredNetworkApproval { std::future::pending().await } - async fn finish(&self, service: &NetworkApprovalService) -> Result<(), ToolError> { + pub(crate) fn finish(&self) -> Result<(), ToolError> { let outcome = self - .finish_outcome - .get_or_init(|| async { service.finish_call_outcome(&self.registration_id).await }) - .await - .clone(); - let outcome = - outcome.or_else(|| abandoned_network_approval_outcome(&self.cancellation_token)); + .registration + .finish() + .clone() + .or_else(|| abandoned_network_approval_outcome(&self.cancellation_token)); network_approval_outcome_to_result(outcome) } } #[derive(Debug)] pub(crate) struct ActiveNetworkApproval { - registration_id: Option, + registration: NetworkApprovalRegistration, cancellation_token: CancellationToken, execution_proxy: NetworkApprovalProxy, } @@ -145,18 +165,17 @@ impl ActiveNetworkApproval { &self.execution_proxy.proxy } - pub(crate) fn into_deferred(self) -> Option { + pub(crate) fn into_deferred(self) -> DeferredNetworkApproval { let ActiveNetworkApproval { - registration_id, + registration, cancellation_token, execution_proxy, } = self; - registration_id.map(|registration_id| DeferredNetworkApproval { - registration_id, + DeferredNetworkApproval { + registration: Arc::new(registration), cancellation_token, - finish_outcome: Arc::new(OnceCell::new()), _execution_proxy: Some(execution_proxy), - }) + } } } @@ -305,7 +324,7 @@ struct PendingNetworkApprovals { pub(crate) struct NetworkApprovalService { shared_ingress_registered: Arc, // Pending-request cleanup must publish a tool outcome synchronously before cancelling it. - calls: SyncMutex, + calls: Arc>, // Owner cleanup runs from Drop, so this lock cannot require an async task. pending_host_approvals: SyncMutex, // Keep persisted session policy and the in-memory approval caches in the same order. @@ -487,7 +506,7 @@ impl Default for NetworkApprovalService { fn default() -> Self { Self { shared_ingress_registered: Arc::default(), - calls: SyncMutex::new(NetworkApprovalCallState::default()), + calls: Arc::default(), pending_host_approvals: SyncMutex::default(), session_policy_commit_lock: Mutex::new(()), session_approved_hosts: Mutex::new(HashSet::new()), @@ -511,7 +530,12 @@ impl NetworkApprovalService { other_approved_hosts.extend(approved_hosts.iter().cloned()); } - async fn register_call(&self, call: ActiveNetworkApprovalCall) { + fn register_call(&self, call: ActiveNetworkApprovalCall) -> NetworkApprovalRegistration { + let registration = NetworkApprovalRegistration { + registration_id: call.registration_id.clone(), + calls: Arc::downgrade(&self.calls), + finish_outcome: SyncOnceLock::new(), + }; let mut calls = self .calls .lock() @@ -519,10 +543,7 @@ impl NetworkApprovalService { calls .active_calls .insert(call.registration_id.clone(), Arc::new(call)); - } - - pub(crate) async fn unregister_call(&self, registration_id: &str) { - self.remove_call(registration_id).await; + registration } async fn resolve_single_active_call(&self) -> Option> { @@ -699,19 +720,6 @@ impl NetworkApprovalService { call.cancellation_token.cancel(); } - async fn remove_call(&self, registration_id: &str) -> Option { - let mut calls = self - .calls - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - calls.active_calls.shift_remove(registration_id); - calls.call_outcomes.remove(registration_id) - } - - async fn finish_call_outcome(&self, registration_id: &str) -> Option { - self.remove_call(registration_id).await - } - pub(crate) async fn record_blocked_request(&self, blocked: BlockedRequest) { let Some(message) = denied_network_policy_message(&blocked) else { return; @@ -1263,7 +1271,7 @@ pub(crate) async fn begin_network_approval( return Ok(None); }; let cancellation_token = CancellationToken::new(); - session + let registration = session .services .network_approval .register_call(ActiveNetworkApprovalCall { @@ -1276,11 +1284,10 @@ pub(crate) async fn begin_network_approval( permission_profile, environments: environments.clone(), cancellation_token: cancellation_token.clone(), - }) - .await; + }); Ok(Some(ActiveNetworkApproval { - registration_id: Some(registration_id), + registration, cancellation_token, execution_proxy: NetworkApprovalProxy { proxy, @@ -1437,14 +1444,13 @@ pub(crate) async fn remote_network_proxy_launch( Ok((launch, credential_masking)) } -pub(crate) async fn finish_deferred_network_approval( - session: &Session, +pub(crate) fn finish_deferred_network_approval( deferred: Option, ) -> Result<(), ToolError> { let Some(deferred) = deferred else { return Ok(()); }; - deferred.finish(&session.services.network_approval).await + deferred.finish() } #[cfg(test)] diff --git a/codex-rs/core/src/tools/network_approval_tests.rs b/codex-rs/core/src/tools/network_approval_tests.rs index c3131fa157..94c8c87110 100644 --- a/codex-rs/core/src/tools/network_approval_tests.rs +++ b/codex-rs/core/src/tools/network_approval_tests.rs @@ -108,7 +108,7 @@ async fn execution_cancellation_respects_network_approval_boundary( ) .await; let service = &session.services.network_approval; - register_call_with_default_shell_trigger(service, "execution-1").await; + let (_execution_1, _) = register_call_with_default_shell_trigger(service, "execution-1").await; let request = NetworkPolicyRequest { protocol: NetworkProtocol::Http, host: "example.com".to_string(), @@ -141,6 +141,7 @@ async fn execution_cancellation_respects_network_approval_boundary( let key = HostApprovalKey::from_request(&request, NetworkApprovalProtocol::Http, "local".to_string()); let mut queued = None; + let mut _queued_registration = None; let expected_decision = match timing { ExecutionCancellationTiming::TurnFinished => { finish_turn.cancel(); @@ -169,7 +170,9 @@ async fn execution_cancellation_respects_network_approval_boundary( started, Some(CriticalPath::default()), ); - register_call_with_default_shell_trigger(service, "execution-2").await; + let (registration, _) = + register_call_with_default_shell_trigger(service, "execution-2").await; + _queued_registration = Some(registration); let mut waiter = Box::pin(service.handle_inline_policy_request( Arc::clone(&session), NetworkPolicyRequest { @@ -599,12 +602,11 @@ async fn manual_prompt_wakeups(decision: PendingApprovalDecision, expected: usiz #[tokio::test] async fn dropping_pending_owner_denies_waiters_and_preserves_replacement() { let service = NetworkApprovalService::default(); - let execution_cancellation = + let (_registration_execution_cancellation, execution_cancellation) = register_call_with_default_shell_trigger(&service, "execution-1").await; let deferred = DeferredNetworkApproval { - registration_id: "execution-1".to_string(), + registration: Arc::new(_registration_execution_cancellation), cancellation_token: execution_cancellation.clone(), - finish_outcome: Arc::new(OnceCell::new()), _execution_proxy: None, }; let key = pending_key( @@ -644,8 +646,7 @@ async fn dropping_pending_owner_denies_waiters_and_preserves_replacement() { ); assert!(execution_cancellation.is_cancelled()); let error = deferred - .finish(&service) - .await + .finish() .expect_err("abandoned approval should fail its execution closed"); assert!(matches!( error, @@ -794,31 +795,29 @@ fn denied_blocked_request_for_execution(host: &str, execution_id: &str) -> Block async fn register_call_with_default_shell_trigger( service: &NetworkApprovalService, registration_id: &str, -) -> CancellationToken { +) -> (NetworkApprovalRegistration, CancellationToken) { let cancellation_token = CancellationToken::new(); - service - .register_call(ActiveNetworkApprovalCall { - registration_id: registration_id.to_string(), - turn_id: "turn-1".to_string(), - tool_name: ToolName::plain("exec_command"), - trigger: GuardianNetworkAccessTrigger { - call_id: registration_id.to_string(), - tool_name: "exec_command".to_string(), - command: vec!["curl".to_string(), "https://example.com".to_string()], - cwd: PathUri::from_abs_path(&test_path_buf("/tmp").abs()), - sandbox_permissions: SandboxPermissions::UseDefault, - additional_permissions: None, - justification: None, - tty: None, - }, - 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; - cancellation_token + let registration = service.register_call(ActiveNetworkApprovalCall { + registration_id: registration_id.to_string(), + turn_id: "turn-1".to_string(), + tool_name: ToolName::plain("exec_command"), + trigger: GuardianNetworkAccessTrigger { + call_id: registration_id.to_string(), + tool_name: "exec_command".to_string(), + command: vec!["curl".to_string(), "https://example.com".to_string()], + cwd: PathUri::from_abs_path(&test_path_buf("/tmp").abs()), + sandbox_permissions: SandboxPermissions::UseDefault, + additional_permissions: None, + justification: None, + tty: None, + }, + 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(), + }); + (registration, cancellation_token) } #[tokio::test] @@ -836,19 +835,17 @@ async fn active_call_preserves_triggering_command_context() { tty: None, }; - service - .register_call(ActiveNetworkApprovalCall { - registration_id: "registration-1".to_string(), - turn_id: "turn-1".to_string(), - trigger: expected.clone(), - tool_name: tool_name.clone(), - 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; + let _registration = service.register_call(ActiveNetworkApprovalCall { + registration_id: "registration-1".to_string(), + turn_id: "turn-1".to_string(), + trigger: expected.clone(), + tool_name: tool_name.clone(), + command: "curl https://example.com".to_string(), + environment_id: "remote".to_string(), + permission_profile: PermissionProfile::workspace_write(), + environments: TurnEnvironmentSnapshot::default(), + cancellation_token: CancellationToken::new(), + }); let call = service .resolve_single_active_call() @@ -864,8 +861,10 @@ async fn active_call_preserves_triggering_command_context() { #[tokio::test] async fn multiple_active_calls_are_ambiguous_even_in_the_same_environment() { let service = NetworkApprovalService::default(); - register_call_with_default_shell_trigger(&service, "registration-1").await; - register_call_with_default_shell_trigger(&service, "registration-2").await; + let (_registration_1, _) = + register_call_with_default_shell_trigger(&service, "registration-1").await; + let (_registration_2, _) = + register_call_with_default_shell_trigger(&service, "registration-2").await; match service.resolve_active_call_attribution().await { ActiveNetworkApprovalAttribution::Ambiguous => {} @@ -878,7 +877,7 @@ async fn multiple_active_calls_are_ambiguous_even_in_the_same_environment() { #[tokio::test] async fn record_blocked_request_sets_policy_outcome_for_owner_call() { let service = NetworkApprovalService::default(); - let cancellation_token = + let (_registration_cancellation_token, cancellation_token) = register_call_with_default_shell_trigger(&service, "registration-1").await; service @@ -897,7 +896,8 @@ async fn record_blocked_request_sets_policy_outcome_for_owner_call() { #[tokio::test] async fn blocked_request_does_not_override_recorded_approval_outcome() { let service = NetworkApprovalService::default(); - register_call_with_default_shell_trigger(&service, "registration-1").await; + let (_registration_1, _) = + register_call_with_default_shell_trigger(&service, "registration-1").await; let rejection = "approval client unavailable"; service.record_call_outcome("registration-1", rejection.to_string()); @@ -914,7 +914,8 @@ async fn blocked_request_does_not_override_recorded_approval_outcome() { #[tokio::test] async fn specific_approval_outcome_replaces_earlier_blocked_request() { let service = NetworkApprovalService::default(); - register_call_with_default_shell_trigger(&service, "registration-1").await; + let (_registration_1, _) = + register_call_with_default_shell_trigger(&service, "registration-1").await; let rejection = "specific approval rejection"; service @@ -931,7 +932,8 @@ async fn specific_approval_outcome_replaces_earlier_blocked_request() { #[tokio::test] async fn disconnect_fallback_preserves_earlier_approval_outcome() { let service = NetworkApprovalService::default(); - let cancellation = register_call_with_default_shell_trigger(&service, "registration-1").await; + let (_registration_cancellation, cancellation) = + register_call_with_default_shell_trigger(&service, "registration-1").await; let denial = "approval client unavailable"; service.record_call_outcome("registration-1", denial.to_string()); @@ -947,7 +949,8 @@ async fn disconnect_fallback_preserves_earlier_approval_outcome() { #[tokio::test] async fn disconnect_fallback_cancels_execution_and_yields_to_explicit_denial() { let service = NetworkApprovalService::default(); - let cancellation = register_call_with_default_shell_trigger(&service, "registration-1").await; + let (_registration_cancellation, cancellation) = + register_call_with_default_shell_trigger(&service, "registration-1").await; let disconnect = "network disconnected"; let denial = "explicit approval denial"; @@ -969,7 +972,8 @@ async fn disconnect_fallback_cancels_execution_and_yields_to_explicit_denial() { #[tokio::test] async fn latest_specific_approval_outcome_replaces_earlier_specific_outcome() { let service = NetworkApprovalService::default(); - register_call_with_default_shell_trigger(&service, "registration-1").await; + let (_registration_1, _) = + register_call_with_default_shell_trigger(&service, "registration-1").await; service.record_call_outcome("registration-1", "earlier approval rejection".to_string()); service.record_call_outcome("registration-1", "latest approval rejection".to_string()); @@ -1000,23 +1004,22 @@ fn approval_denial_messages_are_bounded_for_model_context() { #[tokio::test] async fn deferred_finish_reuses_denial_result_after_first_consumer() { let service = NetworkApprovalService::default(); - let cancellation_token = + let (_registration_cancellation_token, cancellation_token) = register_call_with_default_shell_trigger(&service, "registration-1").await; let deferred = DeferredNetworkApproval { - registration_id: "registration-1".to_string(), + registration: Arc::new(_registration_cancellation_token), cancellation_token, - finish_outcome: Arc::new(OnceCell::new()), _execution_proxy: None, }; service.record_call_outcome("registration-1", "network denied".to_string()); let first = deferred - .finish(&service) - .await + .finish() .expect_err("first consumer should see denial"); - let second = deferred - .finish(&service) - .await + let observer = deferred.clone(); + drop(deferred); + let second = observer + .finish() .expect_err("second consumer should reuse denial"); assert!(matches!(first, ToolError::Rejected(message) if message == "network denied")); @@ -1026,9 +1029,9 @@ async fn deferred_finish_reuses_denial_result_after_first_consumer() { #[tokio::test] async fn record_call_outcome_ignores_inactive_call() { let service = NetworkApprovalService::default(); - let cancellation_token = + let (_registration_cancellation_token, cancellation_token) = register_call_with_default_shell_trigger(&service, "registration-1").await; - service.unregister_call("registration-1").await; + drop(_registration_cancellation_token); service.record_call_outcome("registration-1", "network denied".to_string()); @@ -1039,8 +1042,10 @@ async fn record_call_outcome_ignores_inactive_call() { #[tokio::test] async fn record_blocked_request_ignores_ambiguous_unattributed_blocked_requests() { let service = NetworkApprovalService::default(); - register_call_with_default_shell_trigger(&service, "registration-1").await; - register_call_with_default_shell_trigger(&service, "registration-2").await; + let (_registration_1, _) = + register_call_with_default_shell_trigger(&service, "registration-1").await; + let (_registration_2, _) = + register_call_with_default_shell_trigger(&service, "registration-2").await; service .record_blocked_request(denied_blocked_request("example.com")) @@ -1053,8 +1058,10 @@ async fn record_blocked_request_ignores_ambiguous_unattributed_blocked_requests( #[tokio::test] async fn attributed_blocked_request_targets_one_of_multiple_active_calls() { let service = NetworkApprovalService::default(); - let first = register_call_with_default_shell_trigger(&service, "registration-1").await; - let second = register_call_with_default_shell_trigger(&service, "registration-2").await; + let (_registration_first, first) = + register_call_with_default_shell_trigger(&service, "registration-1").await; + let (_registration_second, second) = + register_call_with_default_shell_trigger(&service, "registration-2").await; service .record_blocked_request(denied_blocked_request_for_execution( @@ -1073,3 +1080,28 @@ async fn attributed_blocked_request_targets_one_of_multiple_active_calls() { ) ); } + +#[tokio::test] +async fn deferred_registration_keeps_attribution_until_last_owner_drops() { + let service = NetworkApprovalService::default(); + let (registration, cancellation_token) = + register_call_with_default_shell_trigger(&service, "registration-1").await; + let deferred = DeferredNetworkApproval { + registration: Arc::new(registration), + cancellation_token: cancellation_token.clone(), + _execution_proxy: None, + }; + let observer = deferred.clone(); + drop(deferred); + + service + .record_blocked_request(denied_blocked_request("example.com")) + .await; + assert!( + cancellation_token.is_cancelled(), + "the remaining owner still receives denials" + ); + drop(observer); + assert!(service.resolve_single_active_call().await.is_none()); + assert_eq!(service.take_call_outcome("registration-1").await, None); +} diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index 7a606ff394..af3ce73a54 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -111,10 +111,9 @@ impl ToolOrchestrator { return (run_result, None); }; - let deferred = network_approval.into_deferred(); + let deferred = Some(network_approval.into_deferred()); if run_result.is_err() { - let finalize_result = - finish_deferred_network_approval(&tool_ctx.session, deferred).await; + let finalize_result = finish_deferred_network_approval(deferred); if let Err(err) = finalize_result { return (Err(err), None); } diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index e5b8933793..3c96fda486 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -265,7 +265,6 @@ struct PreparedProcessHandles { process: Arc, output: OutputHandles, pause_state: Option>, - session: Option>, network_approval: Option, call_id: String, hook_command: String, @@ -304,39 +303,20 @@ impl Drop for InitialExecCommandGuard { } } -async fn unregister_network_approval_for_entry(entry: &ProcessEntry) { - if let Some(network_approval) = entry.network_approval.as_ref() - && let Some(session) = entry.session.upgrade() - { - session - .services - .network_approval - .unregister_call(network_approval.registration_id()) - .await; +fn unregister_network_approval_for_entry(entry: &ProcessEntry) { + if let Some(network_approval) = entry.network_approval.as_ref() { + let _ = network_approval.finish(); } } async fn finish_network_approval_after_process_exit_for_entry( entry: &ProcessEntry, ) -> Result<(), String> { - let session = entry.session.upgrade(); - finish_deferred_network_approval_after_process_exit_for_session( - session.as_ref(), - entry.network_approval.clone(), - ) - .await + finish_deferred_network_approval_after_process_exit(entry.network_approval.clone()).await } -async fn finish_deferred_network_approval_for_session( - session: Option<&Arc>, - deferred: Option, -) -> Result<(), String> { - let Some(session) = session else { - return Ok(()); - }; - finish_deferred_network_approval(session.as_ref(), deferred) - .await - .map_err(network_approval_error_message) +fn finish_network_approval(deferred: Option) -> Result<(), String> { + finish_deferred_network_approval(deferred).map_err(network_approval_error_message) } fn network_approval_error_message(err: ToolError) -> String { @@ -346,14 +326,8 @@ fn network_approval_error_message(err: ToolError) -> String { } } -async fn network_denial_message_for_session( - session: Option<&Arc>, - deferred: Option, -) -> String { - let Some(session) = session else { - return NETWORK_ACCESS_DENIED_MESSAGE.to_string(); - }; - match finish_deferred_network_approval(session.as_ref(), deferred).await { +fn network_denial_message(deferred: Option) -> String { + match finish_deferred_network_approval(deferred) { Ok(()) => NETWORK_ACCESS_DENIED_MESSAGE.to_string(), Err(err) => network_approval_error_message(err), } @@ -368,8 +342,7 @@ async fn wait_for_late_network_denial(network_cancelled: &CancellationToken) -> .is_ok() } -async fn finish_deferred_network_approval_after_process_exit_for_session( - session: Option<&Arc>, +async fn finish_deferred_network_approval_after_process_exit( deferred: Option, ) -> Result<(), String> { if let Some(approval) = &deferred { @@ -381,7 +354,7 @@ async fn finish_deferred_network_approval_after_process_exit_for_session( _ = wait_for_late_network_denial(&network_cancelled) => {} } } - finish_deferred_network_approval_for_session(session, deferred).await + finish_network_approval(deferred) } fn fail_process_with_message(process: &UnifiedExecProcess, message: String) -> UnifiedExecError { @@ -431,7 +404,6 @@ async fn emit_failed_initial_exec_end_if_unstored( fn terminate_process_on_network_denial( process: Arc, - session: std::sync::Weak, deferred: DeferredNetworkApproval, ) -> tokio::task::JoinHandle<()> { let network_cancelled = deferred.cancellation_token(); @@ -447,8 +419,7 @@ fn terminate_process_on_network_denial( if !denied { return; } - let session = session.upgrade(); - let message = network_denial_message_for_session(session.as_ref(), Some(deferred)).await; + let message = network_denial_message(Some(deferred)); process.fail_and_terminate(message); }) } @@ -504,7 +475,7 @@ impl UnifiedExecProcessManager { store.remove(process_id) }; if let Some(entry) = removed { - unregister_network_approval_for_entry(&entry).await; + unregister_network_approval_for_entry(&entry); } } @@ -567,11 +538,7 @@ impl UnifiedExecProcessManager { let _ = completion.process.set(Arc::clone(&process)); } let network_denial_monitor = deferred_network_approval.as_ref().map(|deferred| { - terminate_process_on_network_denial( - Arc::clone(&process), - Arc::downgrade(&context.session), - deferred.clone(), - ) + terminate_process_on_network_denial(Arc::clone(&process), deferred.clone()) }); let output_buffer = Arc::clone(&process.output_handles().output_buffer); @@ -693,11 +660,7 @@ impl UnifiedExecProcessManager { .as_ref() .is_some_and(DeferredNetworkApproval::is_cancelled) { - let message = network_denial_message_for_session( - Some(&context.session), - deferred_network_approval.take(), - ) - .await; + let message = network_denial_message(deferred_network_approval.take()); emit_failed_initial_exec_end_if_unstored( process_stored, process.sandbox_type(), @@ -715,11 +678,7 @@ impl UnifiedExecProcessManager { return Err(fail_process_with_message(process.as_ref(), message)); } if let Some(message) = process.failure_message() { - let finish_result = finish_deferred_network_approval_for_session( - Some(&context.session), - deferred_network_approval.take(), - ) - .await; + let finish_result = finish_network_approval(deferred_network_approval.take()); emit_failed_initial_exec_end_if_unstored( process_stored, process.sandbox_type(), @@ -757,12 +716,10 @@ impl UnifiedExecProcessManager { } => (Some(process_id), exit_code), ProcessStatus::Exited { exit_code, entry } => { entry.process.cancellation_token().cancel(); - if let Err(message) = - finish_deferred_network_approval_after_process_exit_for_session( - Some(&context.session), - deferred_network_approval.take(), - ) - .await + if let Err(message) = finish_deferred_network_approval_after_process_exit( + deferred_network_approval.take(), + ) + .await { return Err(fail_process_with_message(entry.process.as_ref(), message)); } @@ -802,8 +759,7 @@ impl UnifiedExecProcessManager { } else { // Short-lived command: emit the completed command item immediately // using the same helper as the background watcher. - let finish_result = finish_deferred_network_approval_after_process_exit_for_session( - Some(&context.session), + let finish_result = finish_deferred_network_approval_after_process_exit( deferred_network_approval.take(), ) .await; @@ -1000,7 +956,6 @@ impl UnifiedExecProcessManager { process, output, pause_state, - session, network_approval, call_id, hook_command, @@ -1076,18 +1031,12 @@ impl UnifiedExecProcessManager { .as_ref() .is_some_and(DeferredNetworkApproval::is_cancelled) { - let message = - network_denial_message_for_session(session.as_ref(), network_approval.clone()) - .await; + let message = network_denial_message(network_approval.clone()); self.release_process(process_id, Some(locked_process)).await; return Err(fail_process_with_message(process.as_ref(), message)); } if let Some(message) = process.failure_message() { - let finish_result = finish_deferred_network_approval_for_session( - session.as_ref(), - network_approval.clone(), - ) - .await; + let finish_result = finish_network_approval(network_approval.clone()); self.release_process(process_id, Some(locked_process)).await; if let Err(message) = finish_result { return Err(fail_process_with_message(process.as_ref(), message)); @@ -1230,13 +1179,10 @@ impl UnifiedExecProcessManager { .session .upgrade() .map(|session| session.subscribe_elicitation_pause_state()); - let session = entry.session.upgrade(); - Ok(PreparedProcessHandles { process: Arc::clone(&entry.process), output, pause_state, - session, network_approval: entry.network_approval.clone(), call_id: entry.call_id.clone(), hook_command: entry.hook_command.clone(), @@ -1306,7 +1252,7 @@ impl UnifiedExecProcessManager { ); // Install the watcher before cancellable cleanup, and outside the process-store lock. if let Some(pruned_entry) = pruned_entry { - unregister_network_approval_for_entry(&pruned_entry).await; + unregister_network_approval_for_entry(&pruned_entry); pruned_entry.process.terminate(); } } @@ -1803,7 +1749,7 @@ impl UnifiedExecProcessManager { }; for entry in entries { - unregister_network_approval_for_entry(&entry).await; + unregister_network_approval_for_entry(&entry); entry.process.terminate(); } } @@ -1877,7 +1823,7 @@ impl UnifiedExecProcessManager { entry }; - unregister_network_approval_for_entry(&entry).await; + unregister_network_approval_for_entry(&entry); true } } diff --git a/codex-rs/core/src/unified_exec/process_manager_tests.rs b/codex-rs/core/src/unified_exec/process_manager_tests.rs index 2cf90d850e..66363515f8 100644 --- a/codex-rs/core/src/unified_exec/process_manager_tests.rs +++ b/codex-rs/core/src/unified_exec/process_manager_tests.rs @@ -470,7 +470,7 @@ async fn output_collection_preserves_omissions_from_drained_buffer() { #[tokio::test] async fn network_denial_fallback_message_names_sandbox_network_proxy() { - let message = network_denial_message_for_session(/*session*/ None, /*deferred*/ None).await; + let message = network_denial_message(/*deferred*/ None); assert_eq!( message, @@ -557,10 +557,8 @@ async fn late_network_denial_grace_observes_cancellation_after_exit() -> anyhow: .execution_proxy() .remote_policy_decider(/*allow_local_binding*/ true) .expect("remote policy callback"); - let finish = finish_deferred_network_approval_after_process_exit_for_session( - Some(&session), - approval.into_deferred(), - ); + let finish = + finish_deferred_network_approval_after_process_exit(Some(approval.into_deferred())); tokio::pin!(finish); assert!(futures::poll!(&mut finish).is_pending()); diff --git a/codex-rs/core/tests/suite/network_approval_completion.rs b/codex-rs/core/tests/suite/network_approval_completion.rs index 77366b60d3..e5e7303ab9 100644 --- a/codex-rs/core/tests/suite/network_approval_completion.rs +++ b/codex-rs/core/tests/suite/network_approval_completion.rs @@ -18,6 +18,8 @@ use codex_protocol::items::TurnItem; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::ThreadSettingsOverrides; use codex_protocol::sandbox::SandboxType; use codex_protocol::user_input::UserInput; @@ -41,6 +43,8 @@ use serde_json::json; use std::fs; use std::time::Duration; use test_case::test_case; +use tokio::io::AsyncReadExt; +use tokio::io::AsyncWriteExt; use tokio::net::TcpListener; use tokio::net::TcpStream; use tokio::time::timeout; @@ -437,3 +441,180 @@ async fn respond_to_setup_or_hook_request( }; send_exec_server_json(websocket, json!({"id": request["id"], "result": result})).await; } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn interrupted_exec_startup_does_not_poison_next_network_approval() -> Result<()> { + let server = start_mock_server().await; + let listener = TcpListener::bind("127.0.0.1:0").await?; + let exec_server_url = format!("ws://{}", listener.local_addr()?); + let (started, mut starts) = tokio::sync::mpsc::unbounded_channel(); + let exec_server = tokio::spawn(async move { + let mut websocket = accept_initialized_exec_server(listener).await; + loop { + let request = read_exec_server_json(&mut websocket, STARTUP_TIMEOUT).await; + match request["method"].as_str() { + Some("process/start") => { + let params: ExecParams = + serde_json::from_value(request["params"].clone()).unwrap(); + assert!( + params.network_proxy.is_some(), + "launch must register network approval" + ); + started.send(params).unwrap(); + // Hold the launch RPC open so interruption drops the active approval. + } + Some("process/terminate") => { + send_exec_server_json( + &mut websocket, + json!({ + "id": request["id"], "result": {"running": false} + }), + ) + .await; + } + _ => respond_to_setup_or_hook_request(&mut websocket, &request).await, + } + } + }); + let test = test_codex() + .with_exec_server_url(exec_server_url) + .with_cloud_config_bundle( + CloudConfigBundleFixture::loader_with_enterprise_requirement( + "[experimental_network]\nenabled = true", + ), + ) + .with_pre_build_hook(|home| { + fs::write( + home.join("config.toml"), + r#" +default_permissions = "workspace" +[permissions.workspace.filesystem] +":minimal" = "read" +[permissions.workspace.network] +enabled = true +mode = "full" +"#, + ) + .unwrap(); + }) + .with_config(|config| { + config.project_doc_max_bytes = 0; + // The raw HTTP client has no restricted-token identity for shared Windows ingress. + config.permissions.windows_sandbox_type = SandboxType::WindowsMxc; + config.approvals_reviewer = ApprovalsReviewer::User; + #[cfg(windows)] + config.set_windows_sandbox_enabled(/*value*/ true); + }) + // Supply the existing fake executor so process/start can remain pending. + .build(&server) + .await?; + let selection = test.codex.environment_selections().await.pop().unwrap(); + let mut config = environment_config_for_selection(&test.config, &selection); + config.network_policy = Some( + test.config + .permissions + .network + .as_ref() + .unwrap() + .environment_policy(), + ); + test.codex.environment_ready(&selection, config).await?; + for call_id in ["abandoned-launch", "live-launch"] { + let response = core_test_support::responses::mount_sse_once( + &server, + sse(vec![ + ev_function_call( + call_id, + "exec_command", + &json!({"cmd": "pwd", "yield_time_ms": 10_000}).to_string(), + ), + ev_completed(call_id), + ]), + ) + .await; + test.codex + .start_or_steer_turn( + TurnInputRequest::user_input(vec![UserInput::Text { + text: call_id.into(), + text_elements: Vec::new(), + }]) + .with_thread_settings(ThreadSettingsOverrides { + approval_policy: Some(AskForApproval::OnRequest), + approvals_reviewer: Some(ApprovalsReviewer::User), + ..Default::default() + }), + ) + .await?; + timeout(STARTUP_TIMEOUT, starts.recv()) + .await + .context("command did not start")? + .context("executor closed")?; + assert_eq!(response.requests().len(), 1); + if call_id == "abandoned-launch" { + test.codex.submit(Op::Interrupt).await?; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnAborted(_)) + }) + .await; + } + } + // Legacy clients send untagged requests to the shared controller proxy. + // There is now only one live call; an abandoned registration must not make it ambiguous. + let proxy_addr = test + .session_configured + .network_proxy + .as_ref() + .unwrap() + .http_addr + .clone(); + let mut proxy_request = tokio::spawn(async move { + let mut stream = TcpStream::connect(proxy_addr).await?; + stream.write_all(b"GET http://codex-network-test.invalid/ HTTP/1.1\r\nHost: codex-network-test.invalid\r\nConnection: close\r\n\r\n").await?; + let mut response = String::new(); + stream.read_to_string(&mut response).await?; + Ok::<_, std::io::Error>(response) + }); + let approval = timeout(Duration::from_secs(/*secs*/ 10), async { + loop { + tokio::select! { + result = &mut proxy_request => { + anyhow::bail!("sole live call lost network approval after interruption: {}", result??); + } + event = test.codex.next_event() => { + if let EventMsg::ExecApprovalRequest(approval) = event?.msg { + break Ok::<_, anyhow::Error>(approval); + } + } + } + } + }).await; + let result = async { + let approval = approval.context("live command did not receive network approval")??; + assert_eq!( + approval.command, + ["network-access", "http://codex-network-test.invalid:80"] + ); + test.codex + .submit(Op::ExecApproval { + id: approval.effective_approval_id(), + turn_id: Some(approval.turn_id), + decision: ReviewDecision::Denied { + rejection: "denied by test".to_string(), + }, + }) + .await?; + let response = timeout(Duration::from_secs(/*secs*/ 10), &mut proxy_request).await???; + assert!(response.starts_with("HTTP/1.1 403"), "{response}"); + Ok::<_, anyhow::Error>(()) + } + .await; + test.codex.submit(Op::Interrupt).await?; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnAborted(_)) + }) + .await; + proxy_request.abort(); + exec_server.abort(); + let _ = exec_server.await; + result +}