diff --git a/codex-rs/core/src/guardian/permissions.rs b/codex-rs/core/src/guardian/permissions.rs index 2aef89bc82..0a983fed1e 100644 --- a/codex-rs/core/src/guardian/permissions.rs +++ b/codex-rs/core/src/guardian/permissions.rs @@ -30,7 +30,7 @@ pub(super) fn for_request( request: &GuardianApprovalRequest, context: Option<&GuardianReviewContext>, ) -> anyhow::Result> { - match request { + let mut permissions = match request { GuardianApprovalRequest::McpToolCall { prompt_permissions: Some((environment_id, sandbox)), .. @@ -38,7 +38,16 @@ pub(super) fn for_request( _ => context .map(|context| for_environment(context, request.target_environment_id())) .transpose(), + }?; + if let Some(permissions) = &mut permissions + && let GuardianApprovalRequest::ExecCommand { + sandbox_permissions, + .. + } = request + { + permissions.reviewing_escalated_exec = sandbox_permissions.requires_escalated_permissions(); } + Ok(permissions) } pub(super) fn for_mcp_environment( @@ -142,6 +151,7 @@ fn executor_permissions( .map(|path| path.inferred_native_path_string()) .collect(), denied_globs, + reviewing_escalated_exec: false, }) } @@ -159,5 +169,6 @@ fn host_permissions( .map(|root| root.to_string_lossy().into_owned()) .collect(), denied_globs: file_system_policy.get_unreadable_globs_with_cwd(cwd), + reviewing_escalated_exec: false, } } diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index b930213af1..f54d7035c0 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -44,7 +44,10 @@ use codex_sandboxing::policy_transforms::effective_permission_profile; use codex_sandboxing::policy_transforms::merge_permission_profiles; use codex_skills_extension::HostSkillsSnapshot; use codex_skills_extension::SkillLoadOutcome; +use codex_utils_path_uri::LegacyAppPathString; +use codex_utils_path_uri::PathConvention; use codex_utils_path_uri::PathUri; +use codex_utils_path_uri::Platform; use codex_utils_plugins::PluginIdentity; use futures::FutureExt; use futures::future::BoxFuture; @@ -240,6 +243,24 @@ impl TurnEnvironment { self.config().permission_profile.permission_profile() } + pub(crate) fn executor_path_convention(&self) -> Option { + if let Some(os) = self.executor_platform_os.as_deref() { + return Platform::from_platform_os(Some(os)).path_convention(); + } + // Legacy executors report their shell path. A leading // can also be POSIX. + let shell = LegacyAppPathString::from_path(&self.shell.as_ref()?.shell_path); + if shell.as_str().starts_with('/') { + return Some(PathConvention::Posix); + } + shell.infer_absolute_path_convention() + } + + pub(crate) fn has_denied_reads(&self) -> bool { + self.permission_profile() + .file_system_sandbox_policy() + .has_denied_read_restrictions_for_convention(self.executor_path_convention()) + } + /// Borrows this snapshot's filesystem using its permissions and any additional grants. pub(crate) fn fs_accessor( &self, diff --git a/codex-rs/core/src/tools/handlers/unified_exec/preparation.rs b/codex-rs/core/src/tools/handlers/unified_exec/preparation.rs index f9e93c9273..bc811dd4b3 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec/preparation.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec/preparation.rs @@ -9,6 +9,7 @@ use crate::exec::DEFAULT_EXEC_COMMAND_TIMEOUT_MS; use crate::exec_policy::ExecApprovalRequest; use crate::exec_policy::prompt_is_rejected_by_policy; use crate::function_tool::FunctionCallError; +use crate::guardian::routes_approval_policy_to_guardian; use crate::sandboxing::SandboxPermissions; use crate::session::session::Session; use crate::session::step_context::StepContext; @@ -23,6 +24,8 @@ use crate::tools::handlers::parse_arguments_with_base_path; use crate::tools::handlers::resolve_sandbox_permissions; use crate::tools::sandboxing::ApprovalAction; use crate::tools::sandboxing::ExecApprovalRequirement; +use crate::tools::sandboxing::default_exec_approval_requirement; +use crate::tools::sandboxing::ensure_executor_can_escalate_with_denied_reads; use crate::windows_sandbox::windows_sandbox_level_for_legacy_checks; use codex_features::Feature; use codex_sandboxing::SandboxManager; @@ -75,14 +78,17 @@ impl PreparedExecCommand { Some("windows") | Some(_) => DangerousCommandPlatform::Windows, None => DangerousCommandPlatform::host(), }; - session + let approval_policy = step.settings.approval_policy(); + let profile = environment.permission_profile(); + let sandbox_permissions = self.permissions.sandbox_permissions; + let requirement = session .services .exec_policy .create_exec_approval_requirement_for_shell( ExecApprovalRequest { command: &self.resolved.command, - approval_policy: step.settings.approval_policy(), - permission_profile: environment.permission_profile().clone(), + approval_policy, + permission_profile: profile.clone(), environment_policy: environment.config().exec_policy.as_ref(), windows_sandbox_level: windows_sandbox_level_for_legacy_checks( environment.config().windows_sandbox_type, @@ -91,7 +97,7 @@ impl PreparedExecCommand { sandbox_permissions: if self.permissions.permissions_preapproved { SandboxPermissions::UseDefault } else { - self.permissions.sandbox_permissions + sandbox_permissions }, prefix_rule: self.prefix_rule.clone(), allow_prefix_rules: step.turn.allow_prefix_rules(), @@ -99,7 +105,29 @@ impl PreparedExecCommand { configured_shell, command_platform, ) - .await + .await; + + // With denied reads, a saved allow rule skips review but cannot grant broader writes. + if let ExecApprovalRequirement::Skip { + bypass_sandbox: true, + .. + } = requirement + && sandbox_permissions.requires_escalated_permissions() + && routes_approval_policy_to_guardian( + approval_policy, + step.settings.approvals_reviewer(), + ) + && environment.has_denied_reads() + && ensure_executor_can_escalate_with_denied_reads(environment.environment()) + .await + .is_ok() + { + return default_exec_approval_requirement( + approval_policy, + &profile.file_system_sandbox_policy(), + ); + } + requirement } pub(crate) fn approval_action( diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index e4b4856181..4c948352b3 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -21,9 +21,9 @@ use crate::tools::sandboxing::ToolCtx; use crate::tools::sandboxing::ToolError; use crate::tools::sandboxing::ToolRuntime; use crate::tools::sandboxing::default_exec_approval_requirement; +use crate::tools::sandboxing::ensure_executor_can_escalate_with_denied_reads; use crate::tools::sandboxing::ensure_native_sandbox; use crate::tools::sandboxing::sandbox_override_for_first_attempt; -use crate::tools::sandboxing::unsandboxed_execution_allowed; use codex_otel::ToolDecisionSource; use codex_protocol::error::CodexErrorDetails; use codex_protocol::error::SandboxErr; @@ -37,6 +37,7 @@ use codex_sandboxing::SandboxManager; use codex_sandboxing::SandboxSelection; use codex_sandboxing::SandboxType; use codex_sandboxing::policy_transforms::effective_network_sandbox_policy; +use codex_utils_path_uri::PathConvention; use std::sync::Arc; use std::time::Instant; @@ -129,7 +130,12 @@ impl ToolOrchestrator { let mut initial_approval_source = None; let environment = tool.turn_environment(req); - let sandbox_manager = SandboxManager::new(); + // Keep :slash_tmp restrictions when the executor path convention is unknown. + let sandbox_manager = SandboxManager::new().with_executor_path_convention( + environment + .executor_path_convention() + .unwrap_or(PathConvention::Posix), + ); #[cfg(target_os = "macos")] let sandbox_manager = sandbox_manager.with_allowed_symlinked_codex_home( environment @@ -221,11 +227,12 @@ impl ToolOrchestrator { } // 2) First attempt under the selected sandbox. - let unsandboxed_allowed = unsandboxed_execution_allowed(&file_system_sandbox_policy); + let has_denied_reads = file_system_sandbox_policy + .has_denied_read_restrictions_for_convention(environment.executor_path_convention()); let sandbox_override = sandbox_override_for_first_attempt( tool.sandbox_permissions(req), &requirement, - &file_system_sandbox_policy, + has_denied_reads, /*already_approved*/ initial_approval_source.is_some(), ); let (escalated_profile, writable_root_metadata) = if sandbox_override @@ -256,24 +263,8 @@ impl ToolOrchestrator { } else { (None, false) }; - if (escalated_profile.is_some() || writable_root_metadata) - && environment.environment().is_remote() - { - let info = environment.environment().info().await.map_err(|err| { - ToolError::Rejected(format!( - "could not verify exec-server support for escalation with denied reads: {err}" - )) - })?; - if !matches!(info.platform_os.as_deref(), Some("windows" | "macos")) - && !info - .capabilities - .linux_approved_root_write_preserves_restrictions - { - return Err(ToolError::Rejected( - "this exec-server cannot safely escalate with denied reads; upgrade the exec-server and retry" - .to_string(), - )); - } + if escalated_profile.is_some() || writable_root_metadata { + ensure_executor_can_escalate_with_denied_reads(environment.environment()).await?; } let escalated_local_profile = escalated_profile .as_ref() @@ -460,7 +451,7 @@ impl ToolOrchestrator { return Err(ToolError::Codex(err)); } } - if !unsandboxed_allowed && network_approval_context.is_none() { + if has_denied_reads && network_approval_context.is_none() { otel.sandbox_outcome( &otel_tn, otel_ci, @@ -504,7 +495,7 @@ impl ToolOrchestrator { ) }; - let retry_attempt = if unsandboxed_allowed { + let retry_attempt = if !has_denied_reads { // Review and cache the same escalation that the executor will run. if let Some(ApprovalAction::ExecCommand { sandbox_permissions, diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index bf4c195eba..db80e0cfd8 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -29,6 +29,7 @@ use crate::tools::sandboxing::Approvable; use crate::tools::sandboxing::ApprovalAction; use crate::tools::sandboxing::ExecApprovalRequirement; use crate::tools::sandboxing::SandboxAttempt; +use crate::tools::sandboxing::SandboxOverride; use crate::tools::sandboxing::Sandboxable; use crate::tools::sandboxing::ToolCtx; use crate::tools::sandboxing::ToolError; @@ -180,13 +181,9 @@ impl<'a> ToolRuntime, UnifiedExecAttempt> for UnifiedExec ctx: &ToolCtx, ) -> Option { let prepared = req.prepared; - let file_system_sandbox_policy = prepared - .turn_environment - .permission_profile() - .file_system_sandbox_policy(); let sandbox_permissions = sandbox_permissions_preserving_denied_reads( prepared.permissions.sandbox_permissions, - &file_system_sandbox_policy, + prepared.turn_environment.has_denied_reads(), ); // Explicit full escalation bypasses controller and attachment-owned network proxies. // Denied-read restrictions above can still require a sandboxed launch. @@ -237,7 +234,9 @@ impl<'a> ToolRuntime, UnifiedExecAttempt> for UnifiedExec let (file_system_sandbox_policy, _) = attempt.permissions.to_runtime_permissions(); let launch_sandbox_permissions = sandbox_permissions_preserving_denied_reads( prepared.permissions.sandbox_permissions, - &file_system_sandbox_policy, + file_system_sandbox_policy.has_denied_read_restrictions_for_convention( + prepared.turn_environment.executor_path_convention(), + ), ); let managed_network = attempt.network_proxy(managed_network_for_sandbox_permissions( req.network.as_ref(), @@ -592,12 +591,9 @@ impl<'a> ToolRuntime, UnifiedExecAttempt> for UnifiedExec prepared.permissions.additional_permissions.as_ref(), internal_permissions.as_ref(), ); - let baseline_file_system = prepared - .turn_environment - .permission_profile() - .file_system_sandbox_policy(); - let permissions = if baseline_file_system.has_denied_read_restrictions() - && attempt.exec_server_permissions.file_system_sandbox_policy() != baseline_file_system + let permissions = if attempt.sandbox_override + == SandboxOverride::EscalatedSandboxWithRestrictions + && attempt.exec_server_permissions != prepared.turn_environment.permission_profile() { permissions.with_filesystem_escalation() } else { diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index 2989de0ab4..9c99bca7f1 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -260,12 +260,12 @@ pub(crate) fn ensure_native_sandbox( pub(crate) fn sandbox_override_for_first_attempt( sandbox_permissions: SandboxPermissions, exec_approval_requirement: &ExecApprovalRequirement, - file_system_sandbox_policy: &FileSystemSandboxPolicy, + has_denied_reads: bool, already_approved: bool, ) -> SandboxOverride { // Only actual approval of an explicit escalation may widen the filesystem; // a command allow rule does not authorize removing filesystem restrictions. - if !unsandboxed_execution_allowed(file_system_sandbox_policy) { + if has_denied_reads { return if sandbox_permissions.requires_escalated_permissions() && already_approved { SandboxOverride::EscalatedSandboxWithRestrictions } else { @@ -292,25 +292,35 @@ pub(crate) fn sandbox_override_for_first_attempt( } } -/// Returns true when the active filesystem policy can be represented by -/// running without a filesystem sandbox. -/// -/// Denied reads only exist inside the sandbox. If a policy contains any -/// denied-read paths, bypassing the sandbox would silently grant those reads, -/// so escalation must keep the command sandboxed with the denied reads intact. -pub(crate) fn unsandboxed_execution_allowed( - file_system_sandbox_policy: &FileSystemSandboxPolicy, -) -> bool { - !file_system_sandbox_policy.has_denied_read_restrictions() +pub(crate) async fn ensure_executor_can_escalate_with_denied_reads( + environment: &codex_exec_server::Environment, +) -> Result<(), ToolError> { + if !environment.is_remote() { + return Ok(()); + } + let info = environment.info().await.map_err(|err| { + ToolError::Rejected(format!( + "could not verify exec-server support for escalation with denied reads: {err}" + )) + })?; + if !matches!(info.platform_os.as_deref(), Some("windows" | "macos")) + && !info + .capabilities + .linux_approved_root_write_preserves_restrictions + { + return Err(ToolError::Rejected( + "this exec-server cannot safely escalate with denied reads; upgrade the exec-server and retry" + .to_string(), + )); + } + Ok(()) } pub(crate) fn sandbox_permissions_preserving_denied_reads( sandbox_permissions: SandboxPermissions, - file_system_sandbox_policy: &FileSystemSandboxPolicy, + has_denied_reads: bool, ) -> SandboxPermissions { - if sandbox_permissions.requires_escalated_permissions() - && !unsandboxed_execution_allowed(file_system_sandbox_policy) - { + if sandbox_permissions.requires_escalated_permissions() && has_denied_reads { // `RequireEscalated` normally asks the executor to bypass the sandbox. // When denied reads are active, that would drop the only mechanism that // enforces them, so fall back to the default sandboxed attempt instead. diff --git a/codex-rs/core/src/tools/sandboxing_tests.rs b/codex-rs/core/src/tools/sandboxing_tests.rs index 5c7996d796..3cfbfbc395 100644 --- a/codex-rs/core/src/tools/sandboxing_tests.rs +++ b/codex-rs/core/src/tools/sandboxing_tests.rs @@ -170,7 +170,7 @@ fn additional_permissions_allow_bypass_sandbox_first_attempt_when_execpolicy_ski bypass_sandbox: true, proposed_execpolicy_amendment: None, }, - &FileSystemSandboxPolicy::default(), + /*has_denied_reads*/ false, /*already_approved*/ false, ), SandboxOverride::BypassSandboxFirstAttempt @@ -186,7 +186,7 @@ fn guardian_bypasses_sandbox_for_explicit_escalation_on_first_attempt() { bypass_sandbox: false, proposed_execpolicy_amendment: None, }, - &FileSystemSandboxPolicy::default(), + /*has_denied_reads*/ false, /*already_approved*/ true, ), SandboxOverride::BypassSandboxFirstAttempt @@ -202,6 +202,7 @@ fn deny_read_preserves_the_sandbox_for_explicit_escalation_and_blocks_policy_byp access: FileSystemAccessMode::Deny, missing_path_behavior: None, }]); + let has_denied_reads = file_system_policy.has_denied_read_restrictions(); assert_eq!( sandbox_override_for_first_attempt( @@ -210,13 +211,12 @@ fn deny_read_preserves_the_sandbox_for_explicit_escalation_and_blocks_policy_byp bypass_sandbox: false, proposed_execpolicy_amendment: None, }, - &file_system_policy, + has_denied_reads, /*already_approved*/ true, ), SandboxOverride::EscalatedSandboxWithRestrictions, "explicit escalation must widen the first attempt without dropping the sandbox", ); - assert!(!unsandboxed_execution_allowed(&file_system_policy)); assert!(matches!( ensure_native_sandbox(SandboxOverride::EscalatedSandboxWithRestrictions, SandboxType::None), Err(ToolError::Rejected(reason)) if reason.contains("requires an available filesystem sandbox"), @@ -224,21 +224,21 @@ fn deny_read_preserves_the_sandbox_for_explicit_escalation_and_blocks_policy_byp assert_eq!( sandbox_permissions_preserving_denied_reads( SandboxPermissions::RequireEscalated, - &file_system_policy, + has_denied_reads, ), SandboxPermissions::UseDefault, ); assert_eq!( sandbox_permissions_preserving_denied_reads( SandboxPermissions::WithAdditionalPermissions, - &file_system_policy, + has_denied_reads, ), SandboxPermissions::WithAdditionalPermissions, ); assert_eq!( sandbox_permissions_preserving_denied_reads( SandboxPermissions::RequireEscalated, - &FileSystemSandboxPolicy::default(), + /*has_denied_reads*/ false, ), SandboxPermissions::RequireEscalated, ); @@ -249,7 +249,7 @@ fn deny_read_preserves_the_sandbox_for_explicit_escalation_and_blocks_policy_byp bypass_sandbox: true, proposed_execpolicy_amendment: None, }, - &file_system_policy, + has_denied_reads, /*already_approved*/ true, ), SandboxOverride::NoOverride, diff --git a/codex-rs/core/src/unified_exec/stdin_approval.rs b/codex-rs/core/src/unified_exec/stdin_approval.rs index 9b28eee9f1..19374a0cbc 100644 --- a/codex-rs/core/src/unified_exec/stdin_approval.rs +++ b/codex-rs/core/src/unified_exec/stdin_approval.rs @@ -43,6 +43,7 @@ pub(crate) struct TerminalPermissions { #[derive(PartialEq, Eq)] struct TerminalPolicy { sandbox: FileSystemSandboxContext, + has_denied_reads: bool, environment_network: Option, controller_network: Option, controller_proxy: bool, @@ -69,6 +70,7 @@ impl TerminalPolicy { } Self { sandbox, + has_denied_reads: environment.has_denied_reads(), environment_network: environment.config().network_policy.clone(), controller_network: turn.config.permissions.network.clone(), controller_proxy: turn.network.is_some(), @@ -125,9 +127,7 @@ impl TerminalPermissions { let bypassed = self.launch_permissions.requires_escalated_permissions(); // Approval cannot retrofit denied reads onto a running process. Unless // its sandbox still matches, start a new terminal under the current policy. - if baseline - .file_system_sandbox_policy() - .has_denied_read_restrictions() + if current.has_denied_reads && (bypassed || self.policy.file_system_context() != current.file_system_context()) { return Err( diff --git a/codex-rs/core/src/unified_exec/stdin_approval_tests.rs b/codex-rs/core/src/unified_exec/stdin_approval_tests.rs index 170edefa49..5dad3ac237 100644 --- a/codex-rs/core/src/unified_exec/stdin_approval_tests.rs +++ b/codex-rs/core/src/unified_exec/stdin_approval_tests.rs @@ -19,6 +19,9 @@ use std::sync::Arc; fn terminal_permissions(profile: &PermissionProfile) -> TerminalPermissions { TerminalPermissions { policy: TerminalPolicy { + has_denied_reads: profile + .file_system_sandbox_policy() + .has_denied_read_restrictions(), sandbox: FileSystemSandboxContext::from_permission_profile( effective_permission_profile(profile, /*additional_permissions*/ None), PathUri::from_host_native_path(std::env::temp_dir()).expect("local temporary cwd"), diff --git a/codex-rs/core/tests/suite/approvals.rs b/codex-rs/core/tests/suite/approvals.rs index 78ee33e05f..04ab90c4b1 100644 --- a/codex-rs/core/tests/suite/approvals.rs +++ b/codex-rs/core/tests/suite/approvals.rs @@ -713,7 +713,7 @@ async fn submit_turn_preserving_active_permission_profile( .with_thread_settings(ThreadSettingsOverrides { environments: Some(local_requests(test.config.cwd.clone())), approval_policy: Some(approval_policy), - approvals_reviewer: Some(ApprovalsReviewer::User), + approvals_reviewer: Some(test.config.approvals_reviewer), collaboration_mode: Some(CollaborationMode { mode: ModeKind::Default, settings: Settings { @@ -3869,15 +3869,21 @@ touch {outside_path:?} } #[cfg(unix)] -#[test_case(Some(ReviewDecision::Approved); "approved")] -#[test_case(Some(ReviewDecision::denied("rejected by user")); "denied")] -#[test_case(None; "allow_rule_skips_approval_without_widening")] +#[test_case(ApprovalsReviewer::User, Some(ReviewDecision::Approved); "approved")] +#[test_case(ApprovalsReviewer::User, Some(ReviewDecision::denied("rejected by user")); "denied")] +#[test_case(ApprovalsReviewer::User, None; "allow_rule_skips_approval_without_widening")] +#[test_case(ApprovalsReviewer::AutoReview, Some(ReviewDecision::Approved); "allow_rule_approved_by_auto_review")] +#[test_case(ApprovalsReviewer::AutoReview, Some(ReviewDecision::denied("rejected by guardian")); "allow_rule_denied_by_auto_review")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn explicit_escalation_with_denied_reads(decision: Option) -> Result<()> { +async fn explicit_escalation_with_denied_reads( + reviewer: ApprovalsReviewer, + decision: Option, +) -> Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; let home = Arc::new(TempDir::new()?); - if decision.is_none() { + let auto_review = reviewer == ApprovalsReviewer::AutoReview; + if decision.is_none() || auto_review { let rules = home.path().join("rules"); fs::create_dir(&rules)?; fs::write( @@ -3891,6 +3897,7 @@ async fn explicit_escalation_with_denied_reads(decision: Option) let mut builder = test_codex() .with_home(home) .with_config(move |config| { + config.approvals_reviewer = reviewer; config.permissions.approval_policy = Constrained::allow_any(approval_policy); config.features.enable(Feature::UnifiedExec).unwrap(); let mut file_system = PermissionProfile::workspace_write_with( @@ -3935,27 +3942,45 @@ async fn explicit_escalation_with_denied_reads(decision: Option) SandboxPermissions::RequireEscalated, /*justification*/ None, )?; - mount_sse_once(&server, sse(vec![event, ev_completed("run")])).await; - let response = mount_sse_once(&server, sse(vec![ev_completed("done")])).await; + let mut bodies = vec![sse(vec![event, ev_completed("run")])]; + if auto_review { + let assessment = match &decision { + Some(ReviewDecision::Approved) => json!({"outcome": "allow"}), + Some(ReviewDecision::Denied { rejection }) => { + json!({"outcome": "deny", "rationale": rejection}) + } + other => panic!("unexpected Guardian decision: {other:?}"), + }; + bodies.push(sse(vec![ + ev_assistant_message("guardian", &assessment.to_string()), + ev_completed("guardian"), + ])); + } + bodies.push(sse(vec![ev_completed("done")])); + let responses = mount_sse_sequence(&server, bodies).await; submit_turn_preserving_active_permission_profile(&test, "run the command", approval_policy) .await?; let approved = decision == Some(ReviewDecision::Approved); - let rejected = decision.is_some() && !approved; - if let Some(decision) = decision { + if !auto_review && let Some(decision) = &decision { let request = expect_exec_approval(&test, command).await; assert!(!outside_marker.exists() && !workspace_marker.exists()); test.codex .submit(Op::ExecApproval { id: request.effective_approval_id(), turn_id: None, - decision, + decision: decision.clone(), }) .await?; } wait_for_completion_without_approval(&test).await; - let result = parse_result(&response.single_request().function_call_output(call_id)); - if rejected { - assert!(result.stdout.contains("rejected by user"), "{result:?}"); + let requests = responses.requests(); + let reviews = requests.iter().filter(|request| { + request.body_json()["client_metadata"]["x-openai-subagent"] == "guardian" + }); + assert_eq!(reviews.count(), usize::from(auto_review)); + let result = parse_result(&requests.last().unwrap().function_call_output(call_id)); + if let Some(ReviewDecision::Denied { rejection }) = decision { + assert!(result.stdout.contains(&rejection), "{result:?}"); assert!(!workspace_marker.exists()); } else { assert_eq!( diff --git a/codex-rs/core/tests/suite/guardian_environments_tests.rs b/codex-rs/core/tests/suite/guardian_environments_tests.rs index cd8d9d72fc..6cec6b6dfa 100644 --- a/codex-rs/core/tests/suite/guardian_environments_tests.rs +++ b/codex-rs/core/tests/suite/guardian_environments_tests.rs @@ -429,6 +429,10 @@ async fn guardian_reviews_target_environment_and_reuses_prefix(tool: &str) -> Re .context("permission context")?; let permissions = &latest[start + 1]; assert!(permissions.contains(&format!("environment {environment_id:?}"))); + assert_eq!( + permissions.contains("The command stays sandboxed"), + tool == "exec_command" && environment_id == secondary_id + ); if environment_id == secondary_id { assert!(permissions.contains(&denied.inferred_native_path_string())); } else { diff --git a/codex-rs/core/tests/suite/guardian_review.rs b/codex-rs/core/tests/suite/guardian_review.rs index 3004778720..4e5d7adf8f 100644 --- a/codex-rs/core/tests/suite/guardian_review.rs +++ b/codex-rs/core/tests/suite/guardian_review.rs @@ -2221,7 +2221,12 @@ async fn guardian_session_is_reused_for_consecutive_tool_reviews_without_prewarm let permission_section = [ "\n>>> PARENT TURN PERMISSION CONTEXT START\n".to_string(), format!( - "The active permission profile for environment \"local\" denies reading these paths/globs. These are policy restrictions; do not approve escalation whose purpose is to read them.\n- path `{}`\n- glob `{}`\n", + "The active permission profile for environment \"local\" denies reading these \ + paths/globs. These are policy restrictions; do not approve escalation whose purpose \ + is to read them. Approval can grant read and write access across the rest of the \ + filesystem, including repository metadata. The command stays sandboxed with the same \ + read denials. A command can encounter a blocked read incidentally and still \ + complete its intended operation.\n- path `{}`\n- glob `{}`\n", fs::canonicalize(&secret_file)?.display(), test.config.cwd.join("guardian-*.key").display(), ), diff --git a/codex-rs/core/tests/suite/unified_exec_process_events.rs b/codex-rs/core/tests/suite/unified_exec_process_events.rs index 760dcda85f..c22c9d9c7d 100644 --- a/codex-rs/core/tests/suite/unified_exec_process_events.rs +++ b/codex-rs/core/tests/suite/unified_exec_process_events.rs @@ -98,6 +98,7 @@ enum PushedExecScenario { DenyOldLinux, DenyOldLinuxWithRoot(FileSystemAccessMode), DenyLinux, + SavedRuleWithSlashTmp(SavedRuleExecutor), ElevatedPowerShell, RejectedLongWindowsDangerousCommand, SandboxedInterceptedPatch, @@ -110,6 +111,14 @@ enum PushedExecScenario { ReplayGap, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SavedRuleExecutor { + OldWindows, + OldLinux, + Linux, + Windows, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ManagedNetworkScenario { None, @@ -188,6 +197,16 @@ async fn respond_environment_info( scenario: PushedExecScenario, ) { let shell = if matches!( + scenario, + PushedExecScenario::SavedRuleWithSlashTmp(SavedRuleExecutor::OldWindows) + ) { + json!({ "name": "bash", "path": "C:/Program Files/Git/bin/bash.exe" }) + } else if matches!( + scenario, + PushedExecScenario::SavedRuleWithSlashTmp(SavedRuleExecutor::OldLinux) + ) { + json!({ "name": "zsh", "path": "//usr/bin/zsh" }) + } else if matches!( scenario, PushedExecScenario::DenyWin | PushedExecScenario::DenyWinUnchanged @@ -211,6 +230,11 @@ async fn respond_environment_info( json!({ "name": "zsh", "path": "/bin/zsh" }) }; let platform_os = match scenario { + PushedExecScenario::SavedRuleWithSlashTmp( + SavedRuleExecutor::OldWindows | SavedRuleExecutor::OldLinux, + ) => None, + PushedExecScenario::SavedRuleWithSlashTmp(SavedRuleExecutor::Windows) => Some("windows"), + PushedExecScenario::SavedRuleWithSlashTmp(_) => Some("linux"), PushedExecScenario::DenyWin | PushedExecScenario::DenyWinUnchanged | PushedExecScenario::RejectedLongWindowsDangerousCommand => Some("windows"), @@ -238,7 +262,11 @@ async fn respond_environment_info( ) { capabilities["linuxRootWritePreservesDevices"] = json!(true); } - if matches!(scenario, PushedExecScenario::DenyLinux) { + if matches!( + scenario, + PushedExecScenario::DenyLinux + | PushedExecScenario::SavedRuleWithSlashTmp(SavedRuleExecutor::Linux) + ) { capabilities["linuxApprovedRootWritePreservesRestrictions"] = json!(true); } let mut response = json!({ @@ -580,6 +608,7 @@ async fn serve_exec_with_pushed_events( | PushedExecScenario::DenyOldLinux | PushedExecScenario::DenyOldLinuxWithRoot(_) | PushedExecScenario::DenyLinux + | PushedExecScenario::SavedRuleWithSlashTmp(_) | PushedExecScenario::CodexPath | PushedExecScenario::CodexPathDefaultFeature | PushedExecScenario::CodexPathDisabledFeature @@ -773,6 +802,7 @@ async fn serve_exec_with_pushed_events( | PushedExecScenario::DenyOldLinux | PushedExecScenario::DenyOldLinuxWithRoot(_) | PushedExecScenario::DenyLinux + | PushedExecScenario::SavedRuleWithSlashTmp(_) | PushedExecScenario::ElevatedPowerShell => { panic!("completed remote PowerShell must not read a remote process") } @@ -891,6 +921,10 @@ async fn serve_exec_with_pushed_events( #[cfg_attr(not(windows), test_case(PushedExecScenario::DenyOldLinuxWithRoot(FileSystemAccessMode::Deny), ManagedNetworkScenario::None, false ; "old_linux_deny_read_keeps_root_deny_unchanged"))] #[cfg_attr(not(windows), test_case(PushedExecScenario::DenyOldLinuxWithRoot(FileSystemAccessMode::Write), ManagedNetworkScenario::None, false ; "device_only_linux_deny_read_rejects_unchanged_writable_root_metadata"))] #[cfg_attr(not(windows), test_case(PushedExecScenario::DenyLinux, ManagedNetworkScenario::None, false ; "linux_deny_read_allows_approved_escalation"))] +#[test_case(PushedExecScenario::SavedRuleWithSlashTmp(SavedRuleExecutor::OldLinux), ManagedNetworkScenario::None, false ; "saved_escalation_with_slash_tmp_denial_keeps_baseline_on_old_linux")] +#[test_case(PushedExecScenario::SavedRuleWithSlashTmp(SavedRuleExecutor::Linux), ManagedNetworkScenario::None, false ; "saved_escalation_with_slash_tmp_denial_reviews_and_widens_on_linux")] +#[test_case(PushedExecScenario::SavedRuleWithSlashTmp(SavedRuleExecutor::Windows), ManagedNetworkScenario::None, true ; "saved_escalation_with_slash_tmp_denial_bypasses_on_windows")] +#[test_case(PushedExecScenario::SavedRuleWithSlashTmp(SavedRuleExecutor::OldWindows), ManagedNetworkScenario::None, true ; "saved_escalation_with_slash_tmp_denial_bypasses_on_legacy_windows")] #[test_case(PushedExecScenario::ElevatedPowerShell, ManagedNetworkScenario::None, true ; "windows_elevated_powershell_disables_profile")] #[cfg_attr(not(windows), test_case(PushedExecScenario::RejectedLongWindowsDangerousCommand, ManagedNetworkScenario::None, true ; "remote_windows_dangerous_command_rejection_is_bounded"))] #[cfg_attr(not(windows), test_case(PushedExecScenario::SandboxedInterceptedPatch, ManagedNetworkScenario::None, true ; "foreign_windows_intercepted_patch_is_sandboxed"))] @@ -936,6 +970,11 @@ async fn exec_command_consumes_pushed_remote_process_events( policy_callbacks: true } ); + let saved_rule = if let PushedExecScenario::SavedRuleWithSlashTmp(target) = scenario { + Some(target) + } else { + None + }; let deny_read = matches!( scenario, PushedExecScenario::DenyWin @@ -943,6 +982,7 @@ async fn exec_command_consumes_pushed_remote_process_events( | PushedExecScenario::DenyOldLinux | PushedExecScenario::DenyOldLinuxWithRoot(_) | PushedExecScenario::DenyLinux + | PushedExecScenario::SavedRuleWithSlashTmp(_) ); let listener = TcpListener::bind("127.0.0.1:0").await?; let server = start_mock_server().await; @@ -1062,6 +1102,16 @@ async fn exec_command_consumes_pushed_remote_process_events( ev_completed("resp-drained"), ])); } + if let Some(target) = saved_rule { + wiremock::Mock::given(wiremock::matchers::header("x-openai-subagent", "guardian")) + .respond_with(core_test_support::responses::sse_response(sse(vec![ + ev_assistant_message("guardian", r#"{"outcome":"allow"}"#), + ev_completed("guardian"), + ]))) + .expect(u64::from(target == SavedRuleExecutor::Linux)) + .mount(&server) + .await; + } let response_mock = mount_sse_sequence(&server, responses).await; let exec_server_url = format!("ws://{}", listener.local_addr()?); let process_started = Arc::new(AtomicBool::new(false)); @@ -1160,6 +1210,16 @@ timeout = 900 } let mut builder = builder.with_config(move |config| { config.project_doc_max_bytes = 0; + if saved_rule.is_some() { + config.approvals_reviewer = ApprovalsReviewer::AutoReview; + let dir = config.codex_home.join("rules"); + fs::create_dir_all(&dir).expect("create rules directory"); + fs::write( + dir.join("default.rules"), + r#"prefix_rule(pattern=["codex-deny-read-escalation-test"], decision="allow")"#, + ) + .expect("write allow rule"); + } if matches!(scenario, PushedExecScenario::CodexPathDisabledFeature) { config .features @@ -1193,6 +1253,15 @@ timeout = 900 let turn_permission_profile = if managed_network_configured { test.session_configured.permission_profile.clone() + } else if saved_rule.is_some() { + let mut filesystem = FileSystemSandboxPolicy::read_only(); + filesystem.entries.push(FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::SlashTmp, + }, + FileSystemAccessMode::Deny, + )); + PermissionProfile::from_runtime_permissions(&filesystem, NetworkSandboxPolicy::Enabled) } else if deny_read { let mut filesystem = FileSystemSandboxPolicy::read_only(); if let PushedExecScenario::DenyOldLinuxWithRoot(access) = scenario { @@ -1723,7 +1792,16 @@ timeout = 900 json!(["/bin/zsh", "-lc", "pwd"]) ); } - if foreign_cwd { + let windows_rule = matches!( + saved_rule, + Some(SavedRuleExecutor::Windows | SavedRuleExecutor::OldWindows) + ); + if windows_rule { + assert_eq!( + exec_server_result.process_start["params"]["sandbox"], + Value::Null + ); + } else if foreign_cwd { let params = &exec_server_result.process_start["params"]; assert_eq!(params["cwd"], "file:///C:/workspace"); assert_eq!(params["sandbox"]["cwd"], "file:///C:/workspace"); @@ -1745,7 +1823,7 @@ timeout = 900 assert_eq!(params["sandbox"]["windowsSandboxLevel"], "restricted-token"); } } - if deny_read { + if deny_read && !windows_rule { let params = &exec_server_result.process_start["params"]; let params: ExecParams = serde_json::from_value(params.clone())?; let sandbox = params.sandbox.context("sandbox with denied reads")?; @@ -1754,7 +1832,9 @@ timeout = 900 let policy = policy.materialize_project_roots_with_path_uris(context.workspace_roots); if matches!( scenario, - PushedExecScenario::DenyWinUnchanged | PushedExecScenario::DenyOldLinuxWithRoot(_) + PushedExecScenario::DenyWinUnchanged + | PushedExecScenario::DenyOldLinuxWithRoot(_) + | PushedExecScenario::SavedRuleWithSlashTmp(SavedRuleExecutor::OldLinux) ) { let baseline = turn_permission_profile.file_system_sandbox_policy(); assert_eq!( @@ -1766,8 +1846,13 @@ timeout = 900 let matcher = ReadDenyMatcher::from_context(&policy, &context).context("denied reads")?; assert!(policy.can_write_path(&context.cwd.join("../outside")?, &context)); + let denied_paths: &[&str] = if saved_rule.is_some() { + &["/tmp/secret"] + } else { + &["secret.txt", "private.token"] + }; for root in context.workspace_roots { - for path in ["secret.txt", "private.token"] { + for path in denied_paths { assert!(matcher.is_read_denied_uri(&root.join(path)?, &context)); } } @@ -1937,6 +2022,7 @@ timeout = 900 | PushedExecScenario::DenyOldLinux | PushedExecScenario::DenyOldLinuxWithRoot(_) | PushedExecScenario::DenyLinux + | PushedExecScenario::SavedRuleWithSlashTmp(_) | PushedExecScenario::CodexPath | PushedExecScenario::CodexPathDefaultFeature | PushedExecScenario::CodexPathDisabledFeature diff --git a/codex-rs/guardian-context/src/permissions.rs b/codex-rs/guardian-context/src/permissions.rs index 4596604a9e..21a7c370fb 100644 --- a/codex-rs/guardian-context/src/permissions.rs +++ b/codex-rs/guardian-context/src/permissions.rs @@ -18,6 +18,7 @@ pub struct PermissionContext { pub environment_id: Option, pub denied_paths: Vec, pub denied_globs: Vec, + pub reviewing_escalated_exec: bool, } impl ContextualUserFragment for PermissionContext { @@ -60,8 +61,16 @@ impl ContextualUserFragment for PermissionContext { input_text(if entries.is_empty() { format!("{scope} has no explicit denied-read paths/globs.\n") } else { + let after_approval = if self.reviewing_escalated_exec { + " Approval can grant read and write access across the rest of the filesystem, \ + including repository metadata. The command stays sandboxed with the same read \ + denials. A command can encounter a blocked read incidentally and still \ + complete its intended operation." + } else { + "" + }; format!( - "{scope} denies reading these paths/globs. These are policy restrictions; do not approve escalation whose purpose is to read them.\n{}\n", + "{scope} denies reading these paths/globs. These are policy restrictions; do not approve escalation whose purpose is to read them.{after_approval}\n{}\n", entries.join("\n") ) }) diff --git a/codex-rs/guardian-context/src/registry_tests.rs b/codex-rs/guardian-context/src/registry_tests.rs index 9a3617dac0..893201edd6 100644 --- a/codex-rs/guardian-context/src/registry_tests.rs +++ b/codex-rs/guardian-context/src/registry_tests.rs @@ -215,6 +215,7 @@ fn reused_registry_preserves_section_identity_and_source_roles() { environment_id: None, denied_paths: vec!["/private".into()], denied_globs: vec!["**/*.key".into()], + reviewing_escalated_exec: false, }; let action = super::PlannedAction { tool_descriptions: None, diff --git a/codex-rs/protocol/src/permissions.rs b/codex-rs/protocol/src/permissions.rs index 96e590c822..97d105231b 100644 --- a/codex-rs/protocol/src/permissions.rs +++ b/codex-rs/protocol/src/permissions.rs @@ -695,7 +695,7 @@ impl FileSystemSandboxPolicy { } /// Returns whether this policy denies reads on the selected executor. - fn has_denied_read_restrictions_for_convention( + pub fn has_denied_read_restrictions_for_convention( &self, convention: Option, ) -> bool { diff --git a/codex-rs/sandboxing/src/manager.rs b/codex-rs/sandboxing/src/manager.rs index 087b72cd99..19d7ea8d4d 100644 --- a/codex-rs/sandboxing/src/manager.rs +++ b/codex-rs/sandboxing/src/manager.rs @@ -9,7 +9,7 @@ use crate::WindowsSandboxProxySettingsMode; #[cfg(target_os = "linux")] use crate::bwrap::WSL1_BWRAP_WARNING; use crate::policy_transforms::effective_permission_profile; -use crate::policy_transforms::should_require_platform_sandbox; +use crate::policy_transforms::should_require_platform_sandbox_for_convention; use codex_network_proxy::NetworkProxy; use codex_network_proxy::PreparedNetworkRoute; use codex_protocol::config_types::WindowsSandboxLevel; @@ -18,6 +18,7 @@ use codex_protocol::models::PermissionProfile; use codex_protocol::sandbox::SandboxOverride; pub use codex_protocol::sandbox::SandboxType; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_path_uri::PathConvention; use codex_utils_path_uri::PathUri; use std::collections::HashMap; use std::ffi::OsStr; @@ -320,6 +321,7 @@ pub(super) trait SandboxBackend { #[derive(Clone, Default)] pub struct SandboxManager { + executor_path_convention: Option, #[cfg(windows)] windows_token_session: Option, linux_sandbox_pid_namespace: LinuxSandboxPidNamespace, @@ -334,6 +336,12 @@ impl SandboxManager { Self::default() } + /// Evaluate the need for sandboxing using the selected executor's path convention. + pub fn with_executor_path_convention(mut self, convention: PathConvention) -> Self { + self.executor_path_convention = Some(convention); + self + } + /// Creates a manager that applies the narrower runtime profile required by filesystem helpers. pub fn for_file_system_helpers() -> Self { Self { @@ -423,10 +431,12 @@ impl SandboxManager { SandboxablePreference::Auto => { let (file_system_policy, network_policy) = permission_profile.to_runtime_permissions(); - should_require_platform_sandbox( + should_require_platform_sandbox_for_convention( &file_system_policy, network_policy, has_managed_network_requirements, + self.executor_path_convention + .unwrap_or(PathConvention::native()), ) } } diff --git a/codex-rs/sandboxing/src/policy_transforms.rs b/codex-rs/sandboxing/src/policy_transforms.rs index fed7bd15b1..bc4ec08c77 100644 --- a/codex-rs/sandboxing/src/policy_transforms.rs +++ b/codex-rs/sandboxing/src/policy_transforms.rs @@ -647,6 +647,20 @@ pub fn should_require_platform_sandbox( file_system_policy: &FileSystemSandboxPolicy, network_policy: NetworkSandboxPolicy, has_managed_network_requirements: bool, +) -> bool { + should_require_platform_sandbox_for_convention( + file_system_policy, + network_policy, + has_managed_network_requirements, + PathConvention::native(), + ) +} + +pub(crate) fn should_require_platform_sandbox_for_convention( + file_system_policy: &FileSystemSandboxPolicy, + network_policy: NetworkSandboxPolicy, + has_managed_network_requirements: bool, + convention: PathConvention, ) -> bool { if has_managed_network_requirements { return true; @@ -660,7 +674,9 @@ pub fn should_require_platform_sandbox( } match file_system_policy.kind { - FileSystemSandboxKind::Restricted => !file_system_policy.has_full_disk_write_access(), + FileSystemSandboxKind::Restricted => { + !file_system_policy.has_full_disk_write_access_for_convention(Some(convention)) + } FileSystemSandboxKind::Unrestricted | FileSystemSandboxKind::ExternalSandbox => false, } }