From 045a11fe2c701df09dd31d55e8c3f05e79cc4a77 Mon Sep 17 00:00:00 2001 From: jif Date: Fri, 27 Nov 2026 18:46:37 +0000 Subject: [PATCH] Respect sandbox read restrictions in remote plugin approvals (#64369) ## Why Remote command approvals could attribute a command to a plugin by reading a script that the turn's filesystem permissions denied access to. ## What changed Use the remote environment's sandbox policy and stored permission grants when resolving script paths, checking file metadata, and reading scripts for approval attribution. If the lookup is denied, the approval prompt still appears without plugin attribution. ## Testing Add a regression test that checks for an approval prompt without a plugin ID or script path when either the environment policy or a stored turn grant denies reads of an otherwise matching plugin script. GitOrigin-RevId: 123fd72c14cd31121d271fa800f005d3fc41a366 --- .../core-plugins/src/script_attribution.rs | 32 +++-- .../src/script_attribution_tests.rs | 6 +- codex-rs/core/src/session/mod.rs | 17 +-- codex-rs/core/src/session/turn_context.rs | 22 ++- codex-rs/core/src/tools/approvals.rs | 3 +- codex-rs/core/tests/suite/plugins.rs | 135 ++++++++++++++++++ 6 files changed, 183 insertions(+), 32 deletions(-) diff --git a/codex-rs/core-plugins/src/script_attribution.rs b/codex-rs/core-plugins/src/script_attribution.rs index 111b9e38e6..a67233cfca 100644 --- a/codex-rs/core-plugins/src/script_attribution.rs +++ b/codex-rs/core-plugins/src/script_attribution.rs @@ -18,6 +18,7 @@ use crate::store::PluginStore; use crate::store::plugin_version_for_source; use crate::store::validate_plugin_version_segment; use codex_exec_server::ExecutorFileSystem; +use codex_exec_server::FileSystemSandboxContext; use codex_exec_server::GetMetadataOptions; use codex_exec_server::ReadFileOptions; use codex_plugin::PluginId; @@ -337,8 +338,9 @@ impl TrustedPluginRoots { command: &[String], cwd: &PathUri, file_system: &dyn ExecutorFileSystem, + sandbox: Option<&FileSystemSandboxContext>, ) -> Option { - self.executor_candidate(command, cwd, file_system, PluginVersionMatch::Any) + self.executor_candidate(command, cwd, file_system, sandbox, PluginVersionMatch::Any) .await .map(|candidate| candidate.matched.attribution()) } @@ -351,10 +353,16 @@ impl TrustedPluginRoots { cwd: &PathUri, file_system: &dyn ExecutorFileSystem, ) -> Option { - self.executor_candidate(command, cwd, file_system, PluginVersionMatch::Exact) - .await? - .matched - .metrics_operation() + self.executor_candidate( + command, + cwd, + file_system, + /*sandbox*/ None, + PluginVersionMatch::Exact, + ) + .await? + .matched + .metrics_operation() } async fn executor_candidate( @@ -362,6 +370,7 @@ impl TrustedPluginRoots { command: &[String], cwd: &PathUri, file_system: &dyn ExecutorFileSystem, + sandbox: Option<&FileSystemSandboxContext>, version_match: PluginVersionMatch, ) -> Option> { if self.roots.is_empty() { @@ -381,20 +390,13 @@ impl TrustedPluginRoots { }) { return None; } - let script = file_system - .canonicalize(&script, /*sandbox*/ None) - .await - .ok()?; + let script = file_system.canonicalize(&script, sandbox).await.ok()?; let candidates = self.local_candidates_for_executor_script(&script, version_match); if candidates.is_empty() { return None; } let metadata = file_system - .get_metadata( - &script, - GetMetadataOptions::default(), - /*sandbox*/ None, - ) + .get_metadata(&script, GetMetadataOptions::default(), sandbox) .await .ok()?; if !metadata.is_file @@ -405,7 +407,7 @@ impl TrustedPluginRoots { return None; } let contents = file_system - .read_file(&script, ReadFileOptions::default(), /*sandbox*/ None) + .read_file(&script, ReadFileOptions::default(), sandbox) .await .ok()?; let mut matches = candidates diff --git a/codex-rs/core-plugins/src/script_attribution_tests.rs b/codex-rs/core-plugins/src/script_attribution_tests.rs index b4fc63abcf..1e406ea9fb 100644 --- a/codex-rs/core-plugins/src/script_attribution_tests.rs +++ b/codex-rs/core-plugins/src/script_attribution_tests.rs @@ -217,6 +217,7 @@ async fn resolves_relocated_script_through_executor_filesystem() { &command(&["python", "scripts/run.py"]), &cwd, LOCAL_FS.as_ref(), + /*sandbox*/ None, ) .await, Some(PluginCommandAttribution { @@ -232,6 +233,7 @@ async fn resolves_relocated_script_through_executor_filesystem() { &command(&["python", "scripts/run.py"]), &cwd, LOCAL_FS.as_ref(), + /*sandbox*/ None, ) .await, None @@ -796,7 +798,7 @@ async fn assert_executor_resolution( ) { assert_eq!( roots - .resolve_executor_attribution(command, cwd, LOCAL_FS.as_ref()) + .resolve_executor_attribution(command, cwd, LOCAL_FS.as_ref(), /*sandbox*/ None) .await, Some(PluginCommandAttribution { plugin_id: plugin_id.clone(), @@ -1168,7 +1170,7 @@ async fn unrelated_scripts_skip_executor_lookup() -> anyhow::Result<()> { // An executor lookup waits for provisioning; unrelated scripts must finish immediately. assert_eq!( futures::future::join3( - roots.resolve_executor_attribution(&command, &cwd, fs.as_ref()), + roots.resolve_executor_attribution(&command, &cwd, fs.as_ref(), /*sandbox*/ None), roots.resolve_metrics_operation_in_filesystem(&command, &cwd, fs.as_ref()), PluginMeasurementTarget::from_command(&command, &cwd, fs.as_ref()), ) diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index c38f3c9bb0..1c3f7c91b9 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -76,7 +76,6 @@ use codex_attachment_store::AttachmentStore; use codex_attachment_store::InlineAttachmentStore; use codex_connectors::connector_runtime_context_key; use codex_context_fragments::RenderedFragment; -use codex_exec_server::Environment; use codex_exec_server::EnvironmentManager; use codex_execpolicy::prefix_rule_migration; use codex_extension_api::ConversationHistorySnapshot; @@ -3456,7 +3455,7 @@ impl Session { proposed_execpolicy_amendment: Option, additional_permissions: Option, available_decisions: Option>, - command_environment: Option<&Environment>, + command_environment: Option<&TurnEnvironment>, mut command_approval: Option<&mut command_approval::CommandApproval>, ) -> ReviewDecision { let (network_approval_context, turn_binding) = network_approval.unzip(); @@ -3487,17 +3486,11 @@ impl Session { ) }); let plugin_attribution = if let Some(environment) = - command_environment.filter(|env| env.is_remote()) + command_environment.filter(|env| env.environment().is_remote()) { - // A slow attribution lookup should not prevent the approval prompt. - let fs = environment.get_filesystem_without_reconnect(); - tokio::time::timeout( - std::time::Duration::from_secs(5), - turn_context.plugin_attribution_for_executor_command(&command, &cwd, fs.as_ref()), - ) - .await - .ok() - .flatten() + turn_context + .plugin_attribution_for_remote_approval(&command, &cwd, environment) + .await } else { cwd.to_abs_path() .ok() diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index b50a05372d..aa469435ae 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -23,6 +23,7 @@ use arc_swap::ArcSwap; use codex_core_plugins::PluginCommandAttribution; use codex_core_plugins::ResolvedPluginMetricsOperation; use codex_core_plugins::TrustedPluginRoots; +use codex_exec_server::Environment; use codex_exec_server::ExecutorFileSystem; use codex_extension_api::SelectedPluginSnapshot; use codex_file_system::EnvironmentAccess; @@ -767,10 +768,29 @@ impl TurnContext { ) -> Option { self.extension_data .get::()? - .resolve_executor_attribution(command, cwd, file_system) + .resolve_executor_attribution(command, cwd, file_system, /*sandbox*/ None) .await } + pub(crate) async fn plugin_attribution_for_remote_approval( + &self, + command: &[String], + cwd: &PathUri, + environment: &TurnEnvironment, + ) -> Option { + let roots = self.extension_data.get::()?; + let fs = environment.environment().get_filesystem_without_reconnect(); + let grants = self.granted_permissions(&environment.selection.environment_id); + let sandbox = environment.sandbox_context(grants); + tokio::time::timeout( + std::time::Duration::from_secs(5), + roots.resolve_executor_attribution(command, cwd, fs.as_ref(), Some(&sandbox)), + ) + .await + .ok() + .flatten() + } + /// Legacy: returns the frozen initial-turn approval policy. /// Step-scoped consumers should use their captured `StepContext::settings`. pub(crate) fn approval_policy(&self) -> AskForApproval { diff --git a/codex-rs/core/src/tools/approvals.rs b/codex-rs/core/src/tools/approvals.rs index cd5e3b1bbf..bd837d3773 100644 --- a/codex-rs/core/src/tools/approvals.rs +++ b/codex-rs/core/src/tools/approvals.rs @@ -850,8 +850,7 @@ impl Session { ] }), environment - .filter(|_| !human_once && ctx.network_approval_context.is_none()) - .map(|env| env.environment().as_ref()), + .filter(|_| !human_once && ctx.network_approval_context.is_none()), command_approval, ) .await diff --git a/codex-rs/core/tests/suite/plugins.rs b/codex-rs/core/tests/suite/plugins.rs index 9cd34f795f..c65b753a0c 100644 --- a/codex-rs/core/tests/suite/plugins.rs +++ b/codex-rs/core/tests/suite/plugins.rs @@ -34,6 +34,12 @@ use codex_protocol::config_types::TrustLevel; use codex_protocol::items::TurnItem; use codex_protocol::mcp::ClientMcpExtensions; use codex_protocol::models::PermissionProfile; +#[cfg(unix)] +use codex_protocol::permissions::FileSystemAccessMode; +#[cfg(unix)] +use codex_protocol::permissions::FileSystemSandboxEntry; +#[cfg(unix)] +use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; #[cfg(unix)] @@ -43,6 +49,10 @@ use codex_protocol::protocol::Op; #[cfg(unix)] use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::ThreadSettingsOverrides; +#[cfg(unix)] +use codex_protocol::request_permissions::PermissionGrantScope; +#[cfg(unix)] +use codex_protocol::request_permissions::RequestPermissionsResponse; use codex_protocol::user_input::UserInput; use codex_skills_extension::HostSkillsLoadInput; use codex_skills_extension::SkillsExtensionConfig; @@ -735,6 +745,131 @@ printf 'STDIN_OK\n' Ok(()) } +#[cfg(unix)] +#[test_case(None; "environment_policy")] +#[test_case(Some(PermissionGrantScope::Turn); "stored_turn_grant")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn remote_command_approval_skips_attribution_for_a_read_denied_script( + grant_scope: Option, +) -> Result<()> { + skip_if_no_network!(Ok(())); + let executor = core_test_support::exec_server::ExecServerProcess::start().await?; + let server = start_mock_server().await; + let home = Arc::new(TempDir::new()?); + write_remote_plugin_script_and_config(home.as_ref()); + // The executor copy would match the trusted plugin byte for byte if read. + let executor_home = TempDir::new()?; + let script = write_remote_plugin_script_and_config(&executor_home).canonicalize()?; + let command = shlex::try_join(["/bin/sh", script.to_string_lossy().as_ref()])?; + if grant_scope.is_some() { + let args = serde_json::json!({ + "permissions": {"file_system": {"write": [script.parent().unwrap()]}} + }); + mount_sse_once( + &server, + sse(vec![ + ev_response_created("grant"), + ev_function_call("grant", "request_permissions", &args.to_string()), + ev_completed("grant"), + ]), + ) + .await; + } + let request = mount_sse_once( + &server, + sse(vec![ + ev_response_created("plugin"), + core_test_support::responses::ev_exec_command_call_with_args( + "plugin", + &serde_json::json!({ + "cmd": command, + "login": false, + "sandbox_permissions": "require_escalated", + "justification": "Run the plugin?", + }), + ), + ev_completed("plugin"), + ]), + ) + .await; + let base_url = server.uri(); + let test = test_codex() + .with_home(home) + .with_model("gpt-5.2") + .with_exec_server_url(executor.websocket_url.clone()) + .with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing()) + .with_config(move |config| { + config.chatgpt_base_url = base_url; + config.approvals_reviewer = ApprovalsReviewer::User; + config + .features + .enable(Feature::RequestPermissionsTool) + .unwrap(); + }) + .build(&server) + .await?; + let manager = test.thread_manager.environment_manager(); + manager + .default_environment() + .unwrap() + .wait_until_ready() + .await?; + let mut policy = PermissionProfile::workspace_write().file_system_sandbox_policy(); + let deny_script = FileSystemSandboxEntry::new( + codex_utils_absolute_path::AbsolutePathBuf::try_from(script)?.into(), + FileSystemAccessMode::Deny, + ); + if grant_scope.is_none() { + policy.entries.push(deny_script.clone()); + } + test.codex + .start_or_steer_turn( + TurnInputRequest::user_input(vec![UserInput::Text { + text: "run the plugin".to_string(), + text_elements: Vec::new(), + }]) + .with_thread_settings(ThreadSettingsOverrides { + approval_policy: Some(AskForApproval::OnRequest), + permission_profile: Some(PermissionProfile::from_runtime_permissions( + &policy, + NetworkSandboxPolicy::Restricted, + )), + ..Default::default() + }), + ) + .await?; + if let Some(scope) = grant_scope { + let request = wait_for_event_match(&test.codex, |event| match event { + EventMsg::RequestPermissions(request) => Some(request.clone()), + _ => None, + }) + .await; + // Grant the directory with a read denial on the script itself. + let mut permissions = request.permissions; + let file_system = permissions.file_system.as_mut().unwrap(); + file_system.entries.push(deny_script); + test.codex + .submit(Op::RequestPermissionsResponse { + id: request.call_id, + response: RequestPermissionsResponse { + permissions, + scope, + strict_auto_review: false, + }, + }) + .await?; + } + let prompt = wait_for_event_match(&test.codex, |event| match event { + EventMsg::ExecApprovalRequest(prompt) => Some(prompt.clone()), + _ => None, + }) + .await; + test.codex.shutdown_and_wait().await?; + assert_eq!((prompt.plugin_id, prompt.script_path), (None, None)); + request.single_request(); + Ok(()) +} + #[cfg(unix)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn remote_plugin_measurements_require_the_frontend_version() -> Result<()> {