diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 0357d72660..23aa45be18 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -297,6 +297,15 @@ impl TurnContext { } } +pub(crate) struct CommandApprovalRequest { + pub(crate) call_id: String, + pub(crate) command: Vec, + pub(crate) cwd: PathBuf, + pub(crate) reason: Option, + pub(crate) risk: Option, + pub(crate) network_preflight_only: bool, +} + #[allow(dead_code)] #[derive(Clone)] pub(crate) struct SessionConfiguration { @@ -866,12 +875,7 @@ impl Session { pub async fn request_command_approval( &self, turn_context: &TurnContext, - call_id: String, - command: Vec, - cwd: PathBuf, - reason: Option, - risk: Option, - network_preflight_only: bool, + request: CommandApprovalRequest, ) -> ReviewDecision { let sub_id = turn_context.sub_id.clone(); // Add the tx_approve callback to the map before sending the request. @@ -891,15 +895,15 @@ impl Session { warn!("Overwriting existing pending approval for sub_id: {event_id}"); } - let parsed_cmd = parse_command(&command); + let parsed_cmd = parse_command(&request.command); let event = EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent { - call_id, - command, - cwd, - reason, - risk, + call_id: request.call_id, + command: request.command, + cwd: request.cwd, + reason: request.reason, + risk: request.risk, parsed_cmd, - network_preflight_only, + network_preflight_only: request.network_preflight_only, }); self.send_event(turn_context, event).await; rx_approve.await.unwrap_or_default() @@ -1362,6 +1366,9 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv Op::PatchApproval { id, decision } => { handlers::patch_approval(&sess, id, decision).await; } + Op::NetworkApprovalCache { host, decision } => { + handlers::network_approval_cache(&sess, host, decision).await; + } Op::AddToHistory { text } => { handlers::add_to_history(&sess, &config, text).await; } @@ -1413,6 +1420,7 @@ mod handlers { use crate::codex::spawn_review_thread; use crate::config::Config; use crate::mcp::auth::compute_auth_statuses; + use crate::network_proxy; use crate::tasks::CompactTask; use crate::tasks::RegularTask; use crate::tasks::UndoTask; @@ -1528,6 +1536,21 @@ mod handlers { } } + pub async fn network_approval_cache( + sess: &Arc, + host: String, + decision: ReviewDecision, + ) { + if !matches!( + decision, + ReviewDecision::Approved | ReviewDecision::ApprovedForSession + ) { + return; + } + let mut store = sess.services.tool_approvals.lock().await; + network_proxy::cache_network_approval(&mut store, &host, decision); + } + pub async fn add_to_history(sess: &Arc, config: &Arc, text: String) { let id = sess.conversation_id; let config = Arc::clone(config); diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index 95618226be..2a3f99ec45 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -230,12 +230,14 @@ async fn handle_exec_approval( // Race approval with cancellation and timeout to avoid hangs. let approval_fut = parent_session.request_command_approval( parent_ctx, - parent_ctx.sub_id.clone(), - event.command, - event.cwd, - event.reason, - event.risk, - event.network_preflight_only, + crate::codex::CommandApprovalRequest { + call_id: parent_ctx.sub_id.clone(), + command: event.command, + cwd: event.cwd, + reason: event.reason, + risk: event.risk, + network_preflight_only: event.network_preflight_only, + }, ); let decision = await_approval_with_cancel( approval_fut, diff --git a/codex-rs/core/src/network_proxy.rs b/codex-rs/core/src/network_proxy.rs index 3843b2e955..7711c07319 100644 --- a/codex-rs/core/src/network_proxy.rs +++ b/codex-rs/core/src/network_proxy.rs @@ -1,7 +1,9 @@ use crate::config::types::NetworkProxyConfig; use crate::config::types::NetworkProxyMode; use crate::default_client::CodexHttpClient; +use crate::protocol::ReviewDecision; use crate::protocol::SandboxPolicy; +use crate::tools::sandboxing::ApprovalStore; use anyhow::Context; use anyhow::Result; use anyhow::anyhow; @@ -26,6 +28,8 @@ const DENIED_DOMAINS_KEY: &str = "deniedDomains"; pub struct NetworkProxyBlockedRequest { pub host: String, pub reason: String, + #[serde(default)] + pub call_id: Option, pub client: Option, pub method: Option, pub mode: Option, @@ -87,6 +91,41 @@ pub async fn allow_once(client: &CodexHttpClient, admin_url: &str, host: &str) - Ok(()) } +#[derive(Debug, Clone, Serialize)] +pub(crate) struct NetworkApprovalKey { + host: String, +} + +impl NetworkApprovalKey { + fn new(host: &str) -> Option { + let host = host.trim(); + if host.is_empty() { + return None; + } + Some(Self { + host: host.to_ascii_lowercase(), + }) + } +} + +pub(crate) fn cache_network_approval( + store: &mut ApprovalStore, + host: &str, + decision: ReviewDecision, +) -> bool { + if !matches!( + decision, + ReviewDecision::Approved | ReviewDecision::ApprovedForSession + ) { + return false; + } + let Some(key) = NetworkApprovalKey::new(host) else { + return false; + }; + store.put(key, decision); + true +} + pub async fn set_mode( client: &CodexHttpClient, admin_url: &str, @@ -127,6 +166,55 @@ pub fn add_denied_domain(config_path: &Path, host: &str) -> Result { update_domain_list(config_path, host, DomainListKind::Deny) } +#[derive(Debug, Clone, Copy)] +pub struct DomainState { + pub allowed: bool, + pub denied: bool, +} + +pub fn domain_state(config_path: &Path, host: &str) -> Result { + let host = host.trim(); + if host.is_empty() { + return Err(anyhow!("host is empty")); + } + let policy = load_network_policy(config_path)?; + Ok(DomainState { + allowed: list_contains(&policy.allowed_domains, host), + denied: list_contains(&policy.denied_domains, host), + }) +} + +pub fn set_domain_state(config_path: &Path, host: &str, state: DomainState) -> Result { + let host = host.trim(); + if host.is_empty() { + return Err(anyhow!("host is empty")); + } + let mut doc = load_document(config_path)?; + let network = ensure_network_table(&mut doc); + let mut changed = false; + { + let allowed = ensure_array(network, ALLOWED_DOMAINS_KEY); + if state.allowed { + changed |= add_domain(allowed, host); + } else { + changed |= remove_domain(allowed, host); + } + } + { + let denied = ensure_array(network, DENIED_DOMAINS_KEY); + if state.denied { + changed |= add_domain(denied, host); + } else { + changed |= remove_domain(denied, host); + } + } + + if changed { + write_document(config_path, &doc)?; + } + Ok(changed) +} + pub fn should_preflight_network( network_proxy: &NetworkProxyConfig, sandbox_policy: &SandboxPolicy, @@ -161,6 +249,7 @@ pub fn preflight_blocked_request_if_enabled( Some(hit) => Ok(Some(NetworkProxyBlockedRequest { host: hit.host, reason: hit.reason, + call_id: None, client: None, method: None, mode: Some(network_proxy.mode), @@ -372,6 +461,10 @@ fn load_network_policy(config_path: &Path) -> Result { Ok(config.network) } +fn list_contains(domains: &[String], host: &str) -> bool { + domains.iter().any(|value| value.eq_ignore_ascii_case(host)) +} + fn host_matches(pattern: &str, host: &str) -> bool { let pattern = pattern.trim(); if pattern.is_empty() { diff --git a/codex-rs/core/src/tools/runtimes/apply_patch.rs b/codex-rs/core/src/tools/runtimes/apply_patch.rs index d915120d92..2d4198bd26 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch.rs @@ -122,12 +122,14 @@ impl Approvable for ApplyPatchRuntime { session .request_command_approval( turn, - call_id, - vec!["apply_patch".to_string()], - cwd, - Some(reason), - risk, - false, + crate::codex::CommandApprovalRequest { + call_id, + command: vec!["apply_patch".to_string()], + cwd, + reason: Some(reason), + risk, + network_preflight_only: false, + }, ) .await } else if user_explicitly_approved { diff --git a/codex-rs/core/src/tools/runtimes/shell.rs b/codex-rs/core/src/tools/runtimes/shell.rs index fa1dbd7b7d..bdd08cd991 100644 --- a/codex-rs/core/src/tools/runtimes/shell.rs +++ b/codex-rs/core/src/tools/runtimes/shell.rs @@ -111,12 +111,14 @@ impl Approvable for ShellRuntime { session .request_command_approval( turn, - call_id, - command, - cwd, - reason, - risk, - req.network_preflight_only, + crate::codex::CommandApprovalRequest { + call_id, + command, + cwd, + reason, + risk, + network_preflight_only: req.network_preflight_only, + }, ) .await }) diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index 17f99f7fba..b636aeee2d 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -130,12 +130,14 @@ impl Approvable for UnifiedExecRuntime<'_> { session .request_command_approval( turn, - call_id, - command, - cwd, - reason, - risk, - req.network_preflight_only, + crate::codex::CommandApprovalRequest { + call_id, + command, + cwd, + reason, + risk, + network_preflight_only: req.network_preflight_only, + }, ) .await }) diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 2d0b0f013a..9d792be33c 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -153,6 +153,14 @@ pub enum Op { decision: ReviewDecision, }, + /// Cache a network approval decision for this session. + NetworkApprovalCache { + /// The host that was approved. + host: String, + /// The user's decision in response to the request. + decision: ReviewDecision, + }, + /// Append an entry to the persistent cross-session message history. /// /// Note the entry is not guaranteed to be logged if the user has diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index d96786b273..079155be41 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -27,6 +27,8 @@ use codex_core::config::types::NetworkProxyConfig; use codex_core::default_client::create_client; use codex_core::model_family::find_family_for_model; use codex_core::network_proxy; +use codex_core::protocol::Op; +use codex_core::protocol::ReviewDecision; use codex_core::protocol::SessionSource; use codex_core::protocol::TokenUsage; use codex_core::protocol_config_types::ReasoningEffort as ReasoningEffortConfig; @@ -38,6 +40,7 @@ use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; use ratatui::style::Stylize; use ratatui::text::Line; +use std::collections::HashMap; use std::collections::HashSet; use std::path::PathBuf; use std::sync::Arc; @@ -137,6 +140,12 @@ async fn handle_model_migration_prompt_if_needed( None } +#[derive(Debug, Clone)] +struct NetworkProxyRestore { + host: String, + state: network_proxy::DomainState, +} + pub(crate) struct App { pub(crate) server: Arc, pub(crate) app_event_tx: AppEventSender, @@ -171,6 +180,8 @@ pub(crate) struct App { skip_world_writable_scan_once: bool, network_proxy_pending: HashSet, + network_proxy_allow_once: HashMap, + network_proxy_session_restore: HashMap, } impl App { @@ -268,6 +279,8 @@ impl App { pending_update_action: None, skip_world_writable_scan_once: false, network_proxy_pending: HashSet::new(), + network_proxy_allow_once: HashMap::new(), + network_proxy_session_restore: HashMap::new(), }; if app.config.network_proxy.enabled && app.config.network_proxy.prompt_on_block { @@ -325,6 +338,9 @@ impl App { app.handle_tui_event(tui, event).await? } } {} + if let Err(err) = app.restore_network_proxy_approvals().await { + tracing::error!(error = %err, "failed to restore network proxy approvals"); + } tui.terminal.clear()?; Ok(AppExitInfo { token_usage: app.token_usage(), @@ -745,10 +761,18 @@ impl App { if host.is_empty() || self.network_proxy_pending.contains(&host) { return Ok(true); } + if self.chat_widget.is_network_session_allowed(&host) { + self.chat_widget.resume_pending_exec_approval(); + return Ok(true); + } self.network_proxy_pending.insert(host); self.chat_widget.on_network_approval_request(request); } - AppEvent::NetworkProxyDecision { host, decision } => { + AppEvent::NetworkProxyDecision { + host, + decision, + call_id, + } => { let host = host.trim().to_string(); if host.is_empty() { return Ok(true); @@ -756,34 +780,112 @@ impl App { self.network_proxy_pending.remove(&host); let client = create_client(); let admin_url = self.config.network_proxy.admin_url.clone(); - let should_resume_exec = matches!( + let config_path = self.config.network_proxy.config_path.clone(); + let mut reload_needed = false; + let mut should_resume_exec = matches!( decision, crate::app_event::NetworkProxyDecision::AllowOnce + | crate::app_event::NetworkProxyDecision::AllowSession | crate::app_event::NetworkProxyDecision::AllowAlways ); match decision { crate::app_event::NetworkProxyDecision::AllowOnce => { - if let Err(err) = - network_proxy::allow_once(&client, &admin_url, &host).await - { - self.chat_widget - .add_error_message(format!("Failed to allow {host} once: {err}")); + if let Some(call_id) = call_id { + let original = match network_proxy::domain_state(&config_path, &host) { + Ok(state) => Some(state), + Err(err) => { + self.chat_widget.add_error_message(format!( + "Failed to read network policy for {host}: {err}" + )); + should_resume_exec = false; + None + } + }; + let allow_state = network_proxy::DomainState { + allowed: true, + denied: false, + }; + if let Some(original) = original { + match network_proxy::set_domain_state( + &config_path, + &host, + allow_state, + ) { + Ok(changed) => { + reload_needed |= changed; + self.network_proxy_allow_once.insert( + call_id, + NetworkProxyRestore { + host: host.clone(), + state: original, + }, + ); + self.chat_widget.submit_op(Op::NetworkApprovalCache { + host: host.clone(), + decision: ReviewDecision::Approved, + }); + } + Err(err) => { + self.chat_widget.add_error_message(format!( + "Failed to allow {host} once: {err}" + )); + should_resume_exec = false; + } + } + } + } else { + self.chat_widget.add_error_message( + "Allow once requires a command context.".to_string(), + ); + should_resume_exec = false; + } + } + crate::app_event::NetworkProxyDecision::AllowSession => { + let original = match network_proxy::domain_state(&config_path, &host) { + Ok(state) => Some(state), + Err(err) => { + self.chat_widget.add_error_message(format!( + "Failed to read network policy for {host}: {err}" + )); + should_resume_exec = false; + None + } + }; + let allow_state = network_proxy::DomainState { + allowed: true, + denied: false, + }; + if let Some(original) = original { + match network_proxy::set_domain_state(&config_path, &host, allow_state) + { + Ok(changed) => { + reload_needed |= changed; + self.network_proxy_session_restore + .entry(host.clone()) + .or_insert(original); + self.chat_widget.add_network_session_allow(host.clone()); + self.chat_widget.submit_op(Op::NetworkApprovalCache { + host: host.clone(), + decision: ReviewDecision::ApprovedForSession, + }); + } + Err(err) => { + self.chat_widget.add_error_message(format!( + "Failed to allow {host} for this session: {err}" + )); + should_resume_exec = false; + } + } } } crate::app_event::NetworkProxyDecision::AllowAlways => { - match network_proxy::add_allowed_domain( - &self.config.network_proxy.config_path, - &host, - ) { + let allow_state = network_proxy::DomainState { + allowed: true, + denied: false, + }; + match network_proxy::set_domain_state(&config_path, &host, allow_state) { Ok(changed) => { - if changed - && let Err(err) = - network_proxy::reload(&client, &admin_url).await - { - self.chat_widget.add_error_message(format!( - "Failed to reload network proxy after allowlist update: {err}" - )); - } + reload_needed |= changed; } Err(err) => { self.chat_widget.add_error_message(format!( @@ -793,19 +895,13 @@ impl App { } } crate::app_event::NetworkProxyDecision::Deny => { - match network_proxy::add_denied_domain( - &self.config.network_proxy.config_path, - &host, - ) { + let deny_state = network_proxy::DomainState { + allowed: false, + denied: true, + }; + match network_proxy::set_domain_state(&config_path, &host, deny_state) { Ok(changed) => { - if changed - && let Err(err) = - network_proxy::reload(&client, &admin_url).await - { - self.chat_widget.add_error_message(format!( - "Failed to reload network proxy after denylist update: {err}" - )); - } + reload_needed |= changed; } Err(err) => { self.chat_widget.add_error_message(format!( @@ -815,12 +911,43 @@ impl App { } } } + if reload_needed && let Err(err) = network_proxy::reload(&client, &admin_url).await + { + self.chat_widget.add_error_message(format!( + "Failed to reload network proxy after policy update: {err}" + )); + } if should_resume_exec { self.chat_widget.resume_pending_exec_approval(); } else { self.chat_widget.reject_pending_exec_approval(); } } + AppEvent::NetworkProxyAllowOnceExpired { call_id } => { + let Some(restore) = self.network_proxy_allow_once.remove(&call_id) else { + return Ok(true); + }; + let config_path = self.config.network_proxy.config_path.clone(); + let client = create_client(); + let admin_url = self.config.network_proxy.admin_url.clone(); + match network_proxy::set_domain_state(&config_path, &restore.host, restore.state) { + Ok(changed) => { + if changed + && let Err(err) = network_proxy::reload(&client, &admin_url).await + { + self.chat_widget.add_error_message(format!( + "Failed to reload network proxy after allow-once cleanup: {err}" + )); + } + } + Err(err) => { + self.chat_widget.add_error_message(format!( + "Failed to restore network policy for {}: {err}", + restore.host + )); + } + } + } } Ok(true) } @@ -829,6 +956,51 @@ impl App { self.chat_widget.token_usage() } + async fn restore_network_proxy_approvals(&mut self) -> Result<()> { + if self.network_proxy_allow_once.is_empty() && self.network_proxy_session_restore.is_empty() + { + return Ok(()); + } + let config_path = self.config.network_proxy.config_path.clone(); + let client = create_client(); + let admin_url = self.config.network_proxy.admin_url.clone(); + let mut reload_needed = false; + + let mut restores: HashMap = HashMap::new(); + for restore in self + .network_proxy_allow_once + .drain() + .map(|(_, value)| value) + { + restores.insert(restore.host, restore.state); + } + for (host, state) in self.network_proxy_session_restore.drain() { + restores.insert(host, state); + } + + for (host, state) in restores { + match network_proxy::set_domain_state(&config_path, &host, state) { + Ok(changed) => { + reload_needed |= changed; + } + Err(err) => { + tracing::error!( + error = %err, + host = host, + "failed to restore network policy" + ); + } + } + } + + if reload_needed { + network_proxy::reload(&client, &admin_url) + .await + .map_err(|err| color_eyre::eyre::eyre!(err))?; + } + Ok(()) + } + fn on_update_reasoning_effort(&mut self, effort: Option) { self.chat_widget.set_reasoning_effort(effort); self.config.model_reasoning_effort = effort; @@ -1027,6 +1199,8 @@ mod tests { pending_update_action: None, skip_world_writable_scan_once: false, network_proxy_pending: HashSet::new(), + network_proxy_allow_once: HashMap::new(), + network_proxy_session_restore: HashMap::new(), } } diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 1535b74451..6047280194 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -152,6 +152,12 @@ pub(crate) enum AppEvent { NetworkProxyDecision { host: String, decision: NetworkProxyDecision, + call_id: Option, + }, + + /// Restore allow-once network approvals after the command finishes. + NetworkProxyAllowOnceExpired { + call_id: String, }, /// Open the feedback note entry overlay after the user selects a category. @@ -169,6 +175,7 @@ pub(crate) enum AppEvent { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum NetworkProxyDecision { AllowOnce, + AllowSession, AllowAlways, Deny, } diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index 01236d76a6..1ea25c8c95 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -111,8 +111,8 @@ impl ApprovalOverlay { patch_options(), "Would you like to make the following edits?".to_string(), ), - ApprovalVariant::Network { .. } => ( - network_options(), + ApprovalVariant::Network { preflight_only, .. } => ( + network_options(*preflight_only), "Allow network access to this domain?".to_string(), ), }; @@ -166,8 +166,11 @@ impl ApprovalOverlay { (ApprovalVariant::ApplyPatch { id, .. }, ApprovalDecision::Review(decision)) => { self.handle_patch_decision(id, *decision); } - (ApprovalVariant::Network { host }, ApprovalDecision::Network(decision)) => { - self.handle_network_decision(host, *decision); + ( + ApprovalVariant::Network { host, call_id, .. }, + ApprovalDecision::Network(decision), + ) => { + self.handle_network_decision(host, call_id.as_deref(), *decision); } _ => {} } @@ -193,12 +196,18 @@ impl ApprovalOverlay { })); } - fn handle_network_decision(&self, host: &str, decision: NetworkProxyDecision) { + fn handle_network_decision( + &self, + host: &str, + call_id: Option<&str>, + decision: NetworkProxyDecision, + ) { let cell = history_cell::new_network_approval_decision_cell(host.to_string(), decision); self.app_event_tx.send(AppEvent::InsertHistoryCell(cell)); self.app_event_tx.send(AppEvent::NetworkProxyDecision { host: host.to_string(), decision, + call_id: call_id.map(ToString::to_string), }); } @@ -267,8 +276,12 @@ impl BottomPaneView for ApprovalOverlay { ApprovalVariant::ApplyPatch { id, .. } => { self.handle_patch_decision(id, ReviewDecision::Abort); } - ApprovalVariant::Network { host } => { - self.handle_network_decision(host, NetworkProxyDecision::Deny); + ApprovalVariant::Network { host, call_id, .. } => { + self.handle_network_decision( + host, + call_id.as_deref(), + NetworkProxyDecision::Deny, + ); } } } @@ -366,7 +379,7 @@ impl From for ApprovalRequestState { let mut header: Vec> = Vec::new(); let host = request.host.trim().to_string(); if !host.is_empty() { - header.push(Line::from(vec!["Host: ".into(), host.bold()])); + header.push(Line::from(vec!["Host: ".into(), host.clone().bold()])); } let reason = request.reason.trim().to_string(); if !reason.is_empty() { @@ -403,8 +416,14 @@ impl From for ApprovalRequestState { { header.push(Line::from(vec!["Client: ".into(), client.dim()])); } + let preflight_only = request.protocol.trim().eq_ignore_ascii_case("preflight"); + let call_id = request.call_id; Self { - variant: ApprovalVariant::Network { host: request.host }, + variant: ApprovalVariant::Network { + host, + call_id, + preflight_only, + }, header: Box::new(Paragraph::new(header).wrap(Wrap { trim: false })), } } @@ -456,9 +475,18 @@ fn network_reason_hint(reason: &str) -> Option<&'static str> { #[derive(Clone)] enum ApprovalVariant { - Exec { id: String, command: Vec }, - ApplyPatch { id: String }, - Network { host: String }, + Exec { + id: String, + command: Vec, + }, + ApplyPatch { + id: String, + }, + Network { + host: String, + call_id: Option, + preflight_only: bool, + }, } #[derive(Clone)] @@ -523,27 +551,41 @@ fn patch_options() -> Vec { ] } -fn network_options() -> Vec { - vec![ - ApprovalOption { +fn network_options(preflight_only: bool) -> Vec { + let mut options = Vec::new(); + if preflight_only { + options.push(ApprovalOption { label: "Allow once".to_string(), decision: ApprovalDecision::Network(NetworkProxyDecision::AllowOnce), display_shortcut: None, additional_shortcuts: vec![key_hint::plain(KeyCode::Char('y'))], - }, - ApprovalOption { - label: "Allow always (add to allowlist)".to_string(), - decision: ApprovalDecision::Network(NetworkProxyDecision::AllowAlways), - display_shortcut: None, - additional_shortcuts: vec![key_hint::plain(KeyCode::Char('a'))], - }, - ApprovalOption { - label: "Deny (add to denylist)".to_string(), - decision: ApprovalDecision::Network(NetworkProxyDecision::Deny), - display_shortcut: Some(key_hint::plain(KeyCode::Esc)), - additional_shortcuts: vec![key_hint::plain(KeyCode::Char('n'))], - }, - ] + }); + } + let mut allow_session = ApprovalOption { + label: "Allow for session".to_string(), + decision: ApprovalDecision::Network(NetworkProxyDecision::AllowSession), + display_shortcut: None, + additional_shortcuts: vec![key_hint::plain(KeyCode::Char('s'))], + }; + if !preflight_only { + allow_session + .additional_shortcuts + .push(key_hint::plain(KeyCode::Char('y'))); + } + options.push(allow_session); + options.push(ApprovalOption { + label: "Allow always (add to allowlist)".to_string(), + decision: ApprovalDecision::Network(NetworkProxyDecision::AllowAlways), + display_shortcut: None, + additional_shortcuts: vec![key_hint::plain(KeyCode::Char('a'))], + }); + options.push(ApprovalOption { + label: "Deny (add to denylist)".to_string(), + decision: ApprovalDecision::Network(NetworkProxyDecision::Deny), + display_shortcut: Some(key_hint::plain(KeyCode::Esc)), + additional_shortcuts: vec![key_hint::plain(KeyCode::Char('n'))], + }); + options } #[cfg(test)] diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 51639ca810..021b32c1a1 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; +use std::collections::HashSet; use std::collections::VecDeque; use std::path::PathBuf; use std::sync::Arc; @@ -286,6 +287,7 @@ pub(crate) struct ChatWidget { // Whether to add a final message separator after the last message needs_final_message_separator: bool, pending_exec_approval: Option, + network_proxy_session_allow: HashSet, last_rendered_width: std::cell::Cell>, // Feedback sink for /feedback @@ -888,6 +890,10 @@ impl ChatWidget { self.flush_active_cell(); } } + self.app_event_tx + .send(AppEvent::NetworkProxyAllowOnceExpired { + call_id: ev.call_id, + }); } pub(crate) fn handle_patch_apply_end_now( @@ -903,8 +909,9 @@ impl ChatWidget { pub(crate) fn handle_exec_approval_now(&mut self, id: String, ev: ExecApprovalRequestEvent) { if self.pending_exec_approval.is_none() - && let Some(request) = self.preflight_network_request(&ev.command) + && let Some(mut request) = self.preflight_network_request(&ev.command) { + request.call_id = Some(id.clone()); self.pending_exec_approval = Some(PendingExecApproval { id, event: ev, @@ -961,8 +968,25 @@ impl ChatWidget { } } + pub(crate) fn add_network_session_allow(&mut self, host: String) { + let host = host.trim().to_ascii_lowercase(); + if host.is_empty() { + return; + } + self.network_proxy_session_allow.insert(host); + } + + pub(crate) fn is_network_session_allowed(&self, host: &str) -> bool { + let normalized = host.trim().to_ascii_lowercase(); + if normalized.is_empty() { + return false; + } + self.network_proxy_session_allow + .contains(normalized.as_str()) + } + fn preflight_network_request(&self, command: &[String]) -> Option { - match network_proxy::preflight_blocked_request_if_enabled( + let blocked = match network_proxy::preflight_blocked_request_if_enabled( &self.config.network_proxy, &self.config.sandbox_policy, command, @@ -972,7 +996,12 @@ impl ChatWidget { tracing::debug!(error = %err, "network proxy preflight failed"); None } + }; + let request = blocked?; + if self.is_network_session_allowed(&request.host) { + return None; } + Some(request) } pub(crate) fn handle_apply_patch_approval_now( @@ -1139,6 +1168,7 @@ impl ChatWidget { is_review_mode: false, needs_final_message_separator: false, pending_exec_approval: None, + network_proxy_session_allow: HashSet::new(), last_rendered_width: std::cell::Cell::new(None), feedback, current_rollout_path: None, @@ -1207,6 +1237,7 @@ impl ChatWidget { is_review_mode: false, needs_final_message_separator: false, pending_exec_approval: None, + network_proxy_session_allow: HashSet::new(), last_rendered_width: std::cell::Cell::new(None), feedback, current_rollout_path: None, diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 5a8006b80c..24dd824b7d 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -317,6 +317,7 @@ fn make_chatwidget_manual() -> ( is_review_mode: false, needs_final_message_separator: false, pending_exec_approval: None, + network_proxy_session_allow: std::collections::HashSet::new(), last_rendered_width: std::cell::Cell::new(None), feedback: codex_feedback::CodexFeedback::new(), current_rollout_path: None, diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index fff75c7f1f..84a210ed59 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -471,6 +471,16 @@ pub fn new_network_approval_decision_cell( " this time".bold(), ], ), + NetworkProxyDecision::AllowSession => ( + "✔ ".green(), + vec![ + "You ".into(), + "approved".bold(), + " network access to ".into(), + host_span, + " for this session".bold(), + ], + ), NetworkProxyDecision::AllowAlways => ( "✔ ".green(), vec![