From 841b5490b2517a8d86a1ead7bd9790f11176e363 Mon Sep 17 00:00:00 2001 From: "Adam Perry @ OpenAI" Date: Thu, 17 Sep 2026 04:28:44 +0000 Subject: [PATCH] Preserve filesystem sandbox policy context when the cwd disappears (#46112) ## Why Removing the selected working directory can prevent filesystem sandbox helpers from launching, even when the requested absolute paths remain accessible. Permission rules must stay anchored to the selected directory while those operations continue. ## What changed - Require a policy `cwd` in `FileSystemSandboxContext` and launch filesystem helpers from the filesystem root while preserving the policy directory and workspace roots. - Carry explicit `policyContext` in filesystem RPCs, preserving legacy wire fields and resolving omitted directories from older clients at executor ingress. - Keep permission paths as executor file URIs and validate host compatibility where they are enforced. - Bind Windows relative denial globs to the policy directory before changing the helper's launch directory, preserving home-relative patterns. ## Testing Add regression coverage for `apply_patch` after working-directory removal, legacy RPC directory fallbacks, cross-platform permission URI transport, and Windows relative read denials. The patch regression verifies that an allowed file is updated while an explicitly denied file remains unreadable and unchanged. GitOrigin-RevId: b0f4db722b27cb72ec129fc297c85732afac11f7 --- codex-rs/Cargo.lock | 1 + codex-rs/core/src/apply_patch_tests.rs | 2 +- codex-rs/core/src/environment_selection.rs | 6 +- codex-rs/core/src/session/mod.rs | 26 +- codex-rs/core/src/session/tests.rs | 4 +- codex-rs/core/src/session/turn_context.rs | 4 +- .../core/src/tools/handlers/apply_patch.rs | 7 +- .../src/tools/handlers/extension_tools.rs | 4 +- codex-rs/core/src/tools/handlers/mod.rs | 12 +- .../src/tools/handlers/request_permissions.rs | 6 +- .../handlers/unified_exec/exec_command.rs | 9 +- .../core/src/tools/runtimes/apply_patch.rs | 4 +- .../src/tools/runtimes/apply_patch_tests.rs | 13 +- codex-rs/core/src/tools/sandboxing.rs | 4 +- codex-rs/core/src/tools/sandboxing_tests.rs | 4 +- .../src/unified_exec/process_manager_tests.rs | 5 +- .../core/src/unified_exec/shell_snapshot.rs | 4 +- .../core/src/unified_exec/stdin_approval.rs | 7 +- .../src/unified_exec/stdin_approval_tests.rs | 1 + codex-rs/core/tests/suite/apply_patch_cli.rs | 146 ++++ codex-rs/core/tests/suite/remote_env.rs | 12 +- codex-rs/exec-server-protocol/src/protocol.rs | 405 +++++++++- codex-rs/exec-server/BUILD.bazel | 2 + codex-rs/exec-server/Cargo.toml | 1 + .../exec-server/src/capability_discovery.rs | 7 + codex-rs/exec-server/src/client.rs | 52 +- codex-rs/exec-server/src/environment.rs | 4 +- codex-rs/exec-server/src/fs_sandbox.rs | 243 ++++-- codex-rs/exec-server/src/local_file_system.rs | 13 +- codex-rs/exec-server/src/process_sandbox.rs | 15 +- .../exec-server/src/process_sandbox_tests.rs | 51 +- .../exec-server/src/remote_file_stream.rs | 4 +- .../exec-server/src/remote_file_system.rs | 21 +- .../src/remote_file_system_path_uri_tests.rs | 322 +++++++- .../sandboxed_file_system_path_uri_tests.rs | 36 +- .../src/server/file_system_handler.rs | 5 +- codex-rs/exec-server/src/server/registry.rs | 89 ++- .../exec-server/tests/capability_discovery.rs | 733 +++++++++++++++++- codex-rs/exec-server/tests/exec_process.rs | 14 +- .../tests/exec_process/windows_sandbox.rs | 2 +- codex-rs/exec-server/tests/file_stream.rs | 6 +- .../exec-server/tests/file_system/shared.rs | 14 +- .../exec-server/tests/file_system/support.rs | 21 +- .../exec-server/tests/file_system_unix.rs | 4 +- .../exec-server/tests/file_system_windows.rs | 120 +++ .../tests/executor_file_system_authority.rs | 6 +- .../src/exec_permission_profile_serde.rs | 22 + codex-rs/file-system/src/lib.rs | 252 ++++-- 48 files changed, 2419 insertions(+), 326 deletions(-) create mode 100644 codex-rs/file-system/src/exec_permission_profile_serde.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 77470f0ae1..86413b6d60 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -3263,6 +3263,7 @@ dependencies = [ "codex-shell-command", "codex-test-binary-support", "codex-utils-absolute-path", + "codex-utils-cargo-bin", "codex-utils-home-dir", "codex-utils-path-uri", "codex-utils-pty", diff --git a/codex-rs/core/src/apply_patch_tests.rs b/codex-rs/core/src/apply_patch_tests.rs index 275b2a2da7..45e33822f2 100644 --- a/codex-rs/core/src/apply_patch_tests.rs +++ b/codex-rs/core/src/apply_patch_tests.rs @@ -59,7 +59,7 @@ async fn prepare_apply_patch_uses_action_policy_before_turn_policy() { environment.config_mut().permission_profile = PermissionProfileSnapshot::legacy(permission_profile); let sandbox = environment.sandbox_context(/*additional_permissions*/ None); - let context = sandbox.policy_context().expect("local sandbox context"); + let context = sandbox.policy_context(); let prepared = prepare_apply_patch( &step, diff --git a/codex-rs/core/src/environment_selection.rs b/codex-rs/core/src/environment_selection.rs index c1993ab5fc..62761030bf 100644 --- a/codex-rs/core/src/environment_selection.rs +++ b/codex-rs/core/src/environment_selection.rs @@ -1333,8 +1333,7 @@ url = "ws://127.0.0.1:8765" assert_eq!( environment .sandbox_context(/*additional_permissions*/ None) - .policy_context() - .expect("selected environment sandbox context has cwd"), + .policy_context(), FileSystemSandboxPolicyContext { cwd: environment.cwd(), workspace_roots: &[], @@ -1686,8 +1685,7 @@ url = "ws://127.0.0.1:8765" assert_eq!( environment .sandbox_context(/*additional_permissions*/ None) - .policy_context() - .expect("selected environment sandbox context has cwd"), + .policy_context(), FileSystemSandboxPolicyContext { cwd: environment.cwd(), workspace_roots: &[], diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index c242c83cd4..c5df08eee1 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -3055,13 +3055,7 @@ impl Session { let requested_permissions = args.permissions; let sandbox_context = environment.sandbox_context(/*additional_permissions*/ None); - let Some(context) = sandbox_context.policy_context() else { - return Some(RequestPermissionsResponse { - permissions: RequestPermissionProfile::default(), - scope: PermissionGrantScope::Turn, - strict_auto_review: false, - }); - }; + let context = sandbox_context.policy_context(); { let originating_turn_state = { let active = self.active_turn.lock().await; @@ -3292,19 +3286,11 @@ impl Session { let sandbox_context = entry .environment .sandbox_context(/*additional_permissions*/ None); - let response = if let Some(context) = sandbox_context.policy_context() { - Self::normalize_request_permissions_response( - entry.requested_permissions, - response, - &context, - ) - } else { - RequestPermissionsResponse { - permissions: RequestPermissionProfile::default(), - scope: PermissionGrantScope::Turn, - strict_auto_review: false, - } - }; + let response = Self::normalize_request_permissions_response( + entry.requested_permissions, + response, + &sandbox_context.policy_context(), + ); self.record_granted_request_permissions_for_turn( &response, &entry.environment.selection.environment_id, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 723f85a882..0bea18376c 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -9062,8 +9062,8 @@ async fn capability_discovery_uses_environment_permission_profile() { environment_config.windows_sandbox_private_desktop = false; environment_config.use_legacy_landlock = true; let expected_sandbox = FileSystemSandboxContext { - permissions: environment.permission_profile().clone().into(), - cwd: Some(environment.cwd().clone()), + permissions: environment.permission_profile().clone(), + cwd: environment.cwd().clone(), workspace_roots: environment.workspace_roots().to_vec(), user_home_dir: environment.user_home_dir.clone(), temporary_directories: environment.temporary_directories.clone(), diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index ae88a809ae..13a68466f3 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -222,8 +222,8 @@ impl TurnEnvironment { additional_permissions.as_ref(), ); FileSystemSandboxContext { - permissions: permissions.into(), - cwd: Some(self.cwd().clone()), + permissions, + cwd: self.cwd().clone(), workspace_roots: self.workspace_roots().to_vec(), user_home_dir: self.user_home_dir.clone(), temporary_directories: self.temporary_directories.clone(), diff --git a/codex-rs/core/src/tools/handlers/apply_patch.rs b/codex-rs/core/src/tools/handlers/apply_patch.rs index 5ab6666283..527c8770fc 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch.rs @@ -552,12 +552,7 @@ async fn execute_verified_patch( ) -> Result { let cwd = action.cwd.clone(); let sandbox_context = turn_environment.sandbox_context(/*additional_permissions*/ None); - let Some(policy_context) = file_system_sandbox_policy_context_for_cwd(&sandbox_context, &cwd) - else { - return Err(FunctionCallError::RespondToModel( - "apply_patch requires an executor cwd".to_string(), - )); - }; + let policy_context = file_system_sandbox_policy_context_for_cwd(&sandbox_context, &cwd); let sandbox_route = if turn_environment.environment.is_remote() { PatchSandboxRoute::ExecutorManaged } else { diff --git a/codex-rs/core/src/tools/handlers/extension_tools.rs b/codex-rs/core/src/tools/handlers/extension_tools.rs index 92ac4bdb81..0fcb6165c2 100644 --- a/codex-rs/core/src/tools/handlers/extension_tools.rs +++ b/codex-rs/core/src/tools/handlers/extension_tools.rs @@ -299,7 +299,7 @@ mod tests { struct CapturingExtensionExecutor { captured_call: Arc>>>, - captured_sandbox_cwds: Arc>>>, + captured_sandbox_cwds: Arc>>, } impl<'call> codex_extension_api::ToolExecutor> @@ -432,7 +432,7 @@ mod tests { let expected_sandbox_cwds = turn .environments .turn_environments() - .map(|environment| Some(environment.cwd().clone())) + .map(|environment| environment.cwd().clone()) .collect::>(); let history_item = ResponseItem::Message { id: None, diff --git a/codex-rs/core/src/tools/handlers/mod.rs b/codex-rs/core/src/tools/handlers/mod.rs index ce09df5b33..38cc41c748 100644 --- a/codex-rs/core/src/tools/handlers/mod.rs +++ b/codex-rs/core/src/tools/handlers/mod.rs @@ -243,10 +243,10 @@ pub(super) struct EffectiveAdditionalPermissions { pub(super) fn file_system_sandbox_policy_context_for_cwd<'a>( sandbox_context: &'a FileSystemSandboxContext, cwd: &'a PathUri, -) -> Option> { - let mut context = sandbox_context.policy_context()?; +) -> codex_protocol::permissions::FileSystemSandboxPolicyContext<'a> { + let mut context = sandbox_context.policy_context(); context.cwd = cwd; - Some(context) + context } pub(super) fn implicit_granted_permissions( @@ -298,9 +298,9 @@ pub(super) async fn apply_granted_turn_permissions( if additional_permissions.is_none() { Some(granted.clone()) } else { - effective_permissions.as_ref().and_then(|effective| { - preapproved_permission_profile(effective, granted, context.as_ref()?) - }) + effective_permissions + .as_ref() + .and_then(|effective| preapproved_permission_profile(effective, granted, &context)) } }); let permissions_preapproved = preapproved_permissions.is_some(); diff --git a/codex-rs/core/src/tools/handlers/request_permissions.rs b/codex-rs/core/src/tools/handlers/request_permissions.rs index bb3a7de75d..ececd52c6d 100644 --- a/codex-rs/core/src/tools/handlers/request_permissions.rs +++ b/codex-rs/core/src/tools/handlers/request_permissions.rs @@ -79,11 +79,7 @@ impl RequestPermissionsHandler { }; let sandbox_context = turn_environment.sandbox_context(/*additional_permissions*/ None); - let context = sandbox_context.policy_context().ok_or_else(|| { - FunctionCallError::RespondToModel( - "request_permissions requires an executor cwd".to_string(), - ) - })?; + let context = sandbox_context.policy_context(); let mut arguments: Value = parse_arguments(&arguments)?; resolve_permission_path_strings(&mut arguments, &context)?; let mut args: RequestPermissionsArgs = diff --git a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs index 0a026fbb6d..0e43be8318 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs @@ -322,14 +322,7 @@ impl ExecCommandHandler { let requested_additional_permissions = additional_permissions.clone(); let sandbox_context = turn_environment.sandbox_context(/*additional_permissions*/ None); - let Some(permission_context) = - file_system_sandbox_policy_context_for_cwd(&sandbox_context, &cwd) - else { - manager.release_process_id(process_id).await; - return Err(FunctionCallError::RespondToModel( - "selected environment sandbox context is missing cwd".to_string(), - )); - }; + let permission_context = file_system_sandbox_policy_context_for_cwd(&sandbox_context, &cwd); let effective_additional_permissions = apply_granted_turn_permissions( context.session.as_ref(), turn_environment, diff --git a/codex-rs/core/src/tools/runtimes/apply_patch.rs b/codex-rs/core/src/tools/runtimes/apply_patch.rs index 435883b4b1..776c0fffe8 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch.rs @@ -97,8 +97,8 @@ impl ApplyPatchRuntime { req.additional_permissions.as_ref(), ); Some(FileSystemSandboxContext { - permissions: permissions.into(), - cwd: Some(attempt.sandbox_cwd.clone()), + permissions, + cwd: attempt.sandbox_cwd.clone(), workspace_roots: attempt.workspace_roots.to_vec(), user_home_dir: req.turn_environment.user_home_dir.clone(), temporary_directories: None, diff --git a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs index 85a76226d5..be3080d105 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch_tests.rs @@ -265,15 +265,10 @@ async fn file_system_sandbox_context_preserves_executor_workspace_permissions() ); let expected_permissions = PermissionProfile::from_runtime_permissions(&file_system_policy, network_policy); - let native_permissions: PermissionProfile = sandbox - .permissions - .clone() - .try_into() - .expect("native sandbox permissions"); - assert_eq!(native_permissions, expected_permissions); + assert_eq!(sandbox.permissions, expected_permissions); assert_eq!( sandbox.cwd, - Some(codex_utils_path_uri::PathUri::from_abs_path(&path)) + codex_utils_path_uri::PathUri::from_abs_path(&path) ); assert_eq!( sandbox.windows_sandbox_selection, @@ -348,8 +343,8 @@ async fn file_system_sandbox_context_respects_sandbox_request() { assert_eq!( ApplyPatchRuntime::file_system_sandbox_context_for_attempt(&req, &attempt), Some(FileSystemSandboxContext { - permissions: permissions.into(), - cwd: Some(cwd.clone()), + permissions, + cwd: cwd.clone(), workspace_roots: vec![cwd], user_home_dir: Some(user_home_dir), temporary_directories: None, diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index 1bcce42afd..1c8201dde2 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -520,8 +520,8 @@ impl<'a> SandboxAttempt<'a> { exec_request.exec_server_managed_network = managed_network; if self.sandbox_requested { exec_request.exec_server_sandbox = Some(FileSystemSandboxContext { - permissions: exec_server_permissions.into(), - cwd: Some(exec_request.windows_sandbox_policy_cwd.clone()), + permissions: exec_server_permissions, + cwd: exec_request.windows_sandbox_policy_cwd.clone(), workspace_roots: self.workspace_roots.to_vec(), user_home_dir: None, temporary_directories: None, diff --git a/codex-rs/core/src/tools/sandboxing_tests.rs b/codex-rs/core/src/tools/sandboxing_tests.rs index ee146a1ebb..392d62e7e7 100644 --- a/codex-rs/core/src/tools/sandboxing_tests.rs +++ b/codex-rs/core/src/tools/sandboxing_tests.rs @@ -368,8 +368,8 @@ fn exec_server_env_keeps_command_native_and_carries_sandbox_context() { assert_eq!( request.exec_server_sandbox, Some(codex_exec_server::FileSystemSandboxContext { - permissions: exec_server_permissions.clone().into(), - cwd: Some(cwd_uri.clone()), + permissions: exec_server_permissions.clone(), + cwd: cwd_uri.clone(), workspace_roots: vec![cwd_uri.clone()], user_home_dir: None, temporary_directories: None, 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 8be6eda337..bb928ad8f9 100644 --- a/codex-rs/core/src/unified_exec/process_manager_tests.rs +++ b/codex-rs/core/src/unified_exec/process_manager_tests.rs @@ -271,7 +271,10 @@ fn exec_server_params_use_path_uri_and_env_policy_overlay_contract() { request.exec_server_shell_snapshot = None; request.exec_server_sandbox = Some( - codex_exec_server::FileSystemSandboxContext::from_permission_profile(permission_profile), + codex_exec_server::FileSystemSandboxContext::from_permission_profile( + permission_profile, + request.cwd.clone(), + ), ); let first = params_for_request(&request); let second = params_for_request(&request); diff --git a/codex-rs/core/src/unified_exec/shell_snapshot.rs b/codex-rs/core/src/unified_exec/shell_snapshot.rs index 941266f5d2..343c89df03 100644 --- a/codex-rs/core/src/unified_exec/shell_snapshot.rs +++ b/codex-rs/core/src/unified_exec/shell_snapshot.rs @@ -92,8 +92,8 @@ impl Session { /*has_managed_network_requirements*/ false, ) .then(|| FileSystemSandboxContext { - permissions: environment.permission_profile().clone().into(), - cwd: Some(environment.cwd().clone()), + permissions: environment.permission_profile().clone(), + cwd: environment.cwd().clone(), workspace_roots: environment.workspace_roots().to_vec(), user_home_dir: None, temporary_directories: None, diff --git a/codex-rs/core/src/unified_exec/stdin_approval.rs b/codex-rs/core/src/unified_exec/stdin_approval.rs index 750fd3f954..75172d173e 100644 --- a/codex-rs/core/src/unified_exec/stdin_approval.rs +++ b/codex-rs/core/src/unified_exec/stdin_approval.rs @@ -12,7 +12,6 @@ use crate::session::turn_context::TurnEnvironment; use crate::tools::sandboxing::ApprovalAction; use crate::tools::sandboxing::ToolError; use codex_features::Feature; -use codex_file_system::ExecPermissionProfile; use codex_file_system::FileSystemSandboxContext; use codex_network_proxy::EnvironmentNetworkPolicy; use codex_protocol::models::AdditionalPermissionProfile; @@ -69,7 +68,7 @@ impl TerminalPolicy { fn file_system_context(&self) -> FileSystemSandboxContext { let mut context = self.sandbox.clone(); // Network changes require review, not rejection for denied-read drift. - if let ExecPermissionProfile::Managed { network, .. } = &mut context.permissions { + if let PermissionProfile::Managed { network, .. } = &mut context.permissions { *network = NetworkSandboxPolicy::Restricted; } context @@ -131,7 +130,7 @@ impl TerminalPermissions { Ok(if bypassed || &self.policy != current { SandboxPermissions::RequireEscalated } else if self.policy.sandbox.permissions - == effective_permission_profile(baseline, /*additional_permissions*/ None).into() + == effective_permission_profile(baseline, /*additional_permissions*/ None) { SandboxPermissions::UseDefault } else { @@ -145,7 +144,7 @@ impl TerminalPermissions { ) -> Result { let authority = if self.launch_permissions.requires_escalated_permissions() { "This terminal was launched outside the sandbox, bypassing any managed network proxy." - } else if self.policy.sandbox.permissions == ExecPermissionProfile::Disabled { + } else if self.policy.sandbox.permissions == PermissionProfile::Disabled { "This terminal runs without a filesystem sandbox." } else { match sandbox_permissions { 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 8f0a2b38c2..5d06ebcf99 100644 --- a/codex-rs/core/src/unified_exec/stdin_approval_tests.rs +++ b/codex-rs/core/src/unified_exec/stdin_approval_tests.rs @@ -20,6 +20,7 @@ fn terminal_permissions(profile: &PermissionProfile) -> TerminalPermissions { policy: TerminalPolicy { 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"), ), environment_network: None, controller_network: None, diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index b5dda68de7..75de4ed1da 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -43,6 +43,7 @@ use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::ThreadSettingsOverrides; use codex_protocol::protocol::TurnEnvironmentSelection; +use codex_protocol::protocol::TurnEnvironmentSelections; use codex_protocol::user_input::UserInput; #[cfg(target_os = "linux")] use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0; @@ -939,6 +940,151 @@ async fn intercepted_apply_patch_verification_uses_local_sandbox() -> Result<()> Ok(()) } +/// An intercepted update can verify allowed absolute paths after the turn cwd disappears, +/// while the same turn still cannot read or update an explicitly denied target. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn intercepted_apply_patch_updates_absolute_target_after_turn_cwd_is_removed() -> Result<()> { + skip_if_no_network!(Ok(())); + skip_if_target_windows!( + Ok(()), + "the default Windows restricted-token test backend cannot enforce denied reads" + ); + + let harness = apply_patch_harness_with(|builder| builder.with_model("gpt-5.4")).await?; + let test = harness.test(); + let workspace = test.workspace_path_uri("")?; + let original_cwd = test.workspace_path_uri("policy-cwd")?; + let allowed_target = test.workspace_path_uri("allowed.txt")?; + let denied_target = test.workspace_path_uri("denied.txt")?; + harness.create_dir_all("policy-cwd").await?; + harness.write_file("allowed.txt", "original\n").await?; + harness.write_file("denied.txt", "private\n").await?; + + let file_system_policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + access: FileSystemAccessMode::Read, + missing_path_behavior: None, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: workspace.clone(), + }, + access: FileSystemAccessMode::Write, + missing_path_behavior: None, + }, + FileSystemSandboxEntry { + path: FileSystemPath::Path { + path: denied_target.clone(), + }, + access: FileSystemAccessMode::Deny, + missing_path_behavior: None, + }, + ]); + let permissions = PermissionProfile::from_runtime_permissions( + &file_system_policy, + NetworkSandboxPolicy::Restricted, + ); + let (sandbox_policy, permission_profile) = + turn_permission_fields(permissions, test.config.cwd.as_path()); + let selection = TurnEnvironmentSelection { + cwd: original_cwd, + workspace_roots: vec![workspace.clone()], + ..test.executor_environment().selection().clone() + }; + + let workdir = workspace.inferred_native_path_string(); + let allowed_patch = format!( + "apply_patch <<'EOF'\n*** Begin Patch\n*** Update File: {}\n@@\n-original\n+changed\n*** End Patch\nEOF\n", + allowed_target.inferred_native_path_string(), + ); + let denied_patch = format!( + "apply_patch <<'EOF'\n*** Begin Patch\n*** Update File: {}\n@@\n-private\n+changed\n*** End Patch\nEOF\n", + denied_target.inferred_native_path_string(), + ); + let responses = mount_sse_sequence( + harness.server(), + vec![ + sse(vec![ + ev_response_created("resp-remove"), + ev_exec_command_call_with_args( + "remove-cwd", + &json!({"cmd": "rmdir policy-cwd", "workdir": workdir, "login": false}), + ), + ev_completed("resp-remove"), + ]), + sse(vec![ + ev_response_created("resp-allowed"), + ev_exec_command_call_with_args( + "patch-allowed", + &json!({"cmd": allowed_patch, "workdir": workdir, "login": false}), + ), + ev_completed("resp-allowed"), + ]), + sse(vec![ + ev_response_created("resp-denied"), + ev_exec_command_call_with_args( + "patch-denied", + &json!({"cmd": denied_patch, "workdir": workdir, "login": false}), + ), + ev_completed("resp-denied"), + ]), + sse(vec![ + ev_assistant_message("msg-done", "done"), + ev_completed("resp-done"), + ]), + ], + ) + .await; + + test.codex + .start_or_steer_turn( + TurnInputRequest::user_input(vec![UserInput::Text { + text: "remove the turn cwd, then update the allowed and denied files".into(), + text_elements: Vec::new(), + }]) + .with_thread_settings(ThreadSettingsOverrides { + environments: Some(TurnEnvironmentSelections::new( + test.config.cwd.clone(), + vec![selection], + )), + approval_policy: Some(AskForApproval::Never), + sandbox_policy: Some(sandbox_policy), + permission_profile, + ..Default::default() + }), + ) + .await?; + wait_for_event(&test.codex, |event| { + matches!(event, EventMsg::TurnComplete(_)) + }) + .await; + + assert!(!harness.path_exists("policy-cwd").await?); + let allowed_output = responses + .function_call_output_text("patch-allowed") + .expect("the model should receive the allowed patch output"); + assert!(allowed_output.contains("Success."), "{allowed_output}"); + let denied_output = responses + .function_call_output_text("patch-denied") + .expect("the model should receive the denied patch output"); + assert!( + denied_output.contains("apply_patch verification failed") + && denied_output.contains("Failed to read"), + "{denied_output}", + ); + assert_eq!( + ( + harness.read_file_text("allowed.txt").await?, + harness.read_file_text("denied.txt").await?, + ), + ("changed\n".to_string(), "private\n".to_string()), + ); + Ok(()) +} + #[cfg(unix)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn escalated_patch_rejects_symlink_swapped_after_approval_request() -> Result<()> { diff --git a/codex-rs/core/tests/suite/remote_env.rs b/codex-rs/core/tests/suite/remote_env.rs index f305233450..e5295233de 100644 --- a/codex-rs/core/tests/suite/remote_env.rs +++ b/codex-rs/core/tests/suite/remote_env.rs @@ -2940,7 +2940,8 @@ fn absolute_path(path: PathBuf) -> AbsolutePathBuf { fn read_only_sandbox(readable_root: PathBuf) -> FileSystemSandboxContext { let readable_root = absolute_path(readable_root); - FileSystemSandboxContext::from_permission_profile(PermissionProfile::from_runtime_permissions( + let cwd = PathUri::from_abs_path(&readable_root); + let permissions = PermissionProfile::from_runtime_permissions( &FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { path: FileSystemPath::Path { path: readable_root.into(), @@ -2949,12 +2950,14 @@ fn read_only_sandbox(readable_root: PathBuf) -> FileSystemSandboxContext { missing_path_behavior: None, }]), NetworkSandboxPolicy::Restricted, - )) + ); + FileSystemSandboxContext::from_permission_profile(permissions, cwd) } fn workspace_write_sandbox(writable_root: PathBuf) -> FileSystemSandboxContext { let writable_root = absolute_path(writable_root); - FileSystemSandboxContext::from_permission_profile(PermissionProfile::from_runtime_permissions( + let cwd = PathUri::from_abs_path(&writable_root); + let permissions = PermissionProfile::from_runtime_permissions( &FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { path: FileSystemPath::Path { path: writable_root.into(), @@ -2963,7 +2966,8 @@ fn workspace_write_sandbox(writable_root: PathBuf) -> FileSystemSandboxContext { missing_path_behavior: None, }]), NetworkSandboxPolicy::Restricted, - )) + ); + FileSystemSandboxContext::from_permission_profile(permissions, cwd) } fn assert_normalized_path_rejected(error: &std::io::Error) { diff --git a/codex-rs/exec-server-protocol/src/protocol.rs b/codex-rs/exec-server-protocol/src/protocol.rs index 67125ab0c2..fc9060f564 100644 --- a/codex-rs/exec-server-protocol/src/protocol.rs +++ b/codex-rs/exec-server-protocol/src/protocol.rs @@ -5,6 +5,7 @@ use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use codex_file_system::FileSystemSandboxContext; pub use codex_file_system::WalkOptions; pub use codex_file_system::WalkOutcome; +use codex_file_system::WireFileSystemSandboxContext; use codex_network_proxy::ManagedNetworkSandboxContext; use codex_network_proxy::RemoteNetworkProxyLaunchConfig; use codex_protocol::ThreadId; @@ -15,6 +16,7 @@ use codex_utils_path_uri::PathUri; use serde::Deserialize; use serde::Serialize; +use crate::JSONRPCErrorError; use crate::ProcessId; pub const INITIALIZE_METHOD: &str = "initialize"; @@ -328,6 +330,70 @@ pub struct ExecParams { pub network_proxy: Option, } +/// Executor ingress for process requests from clients that may omit the sandbox policy cwd. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireExecParams { + process_id: ProcessId, + metadata: Option, + argv: Vec, + cwd: PathUri, + env_policy: Option, + shell_snapshot: Option, + env: HashMap, + tty: bool, + #[serde(default)] + pipe_stdin: bool, + arg0: Option, + sandbox: Option, + #[serde(default)] + enforce_managed_network: bool, + managed_network: Option, + network_proxy: Option, +} + +impl From for ExecParams { + fn from(wire: WireExecParams) -> Self { + let WireExecParams { + process_id, + metadata, + argv, + cwd, + env_policy, + shell_snapshot, + env, + tty, + pipe_stdin, + arg0, + sandbox, + enforce_managed_network, + managed_network, + network_proxy, + } = wire; + let sandbox = sandbox.map(|sandbox| { + // Legacy processes used the required process cwd as their sandbox policy cwd. + let policy_cwd = sandbox.cwd().unwrap_or(&cwd).clone(); + sandbox.into_context(policy_cwd) + }); + Self { + process_id, + metadata, + argv, + cwd, + env_policy, + shell_snapshot, + env, + tty, + pipe_stdin, + arg0, + sandbox, + enforce_managed_network, + managed_network, + network_proxy, + } + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ExecEnvPolicy { @@ -461,6 +527,16 @@ pub struct FsReadFileParams { pub sandbox: Option, } +/// Filesystem RPC wire request with legacy optional sandbox policy cwd. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireFsReadFileParams { + path: PathUri, + #[serde(default, skip_serializing_if = "Option::is_none")] + follow_symlinks: Option, + sandbox: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FsReadFileResponse { @@ -475,6 +551,15 @@ pub struct FsOpenParams { pub sandbox: Option, } +/// Filesystem RPC wire request with legacy optional sandbox policy cwd. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireFsOpenParams { + handle_id: String, + path: PathUri, + sandbox: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FsOpenResponse { @@ -516,6 +601,17 @@ pub struct FsWriteFileParams { pub sandbox: Option, } +/// Filesystem RPC wire request with legacy optional sandbox policy cwd. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireFsWriteFileParams { + path: PathUri, + data_base64: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + follow_symlinks: Option, + sandbox: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FsWriteFileResponse {} @@ -530,6 +626,17 @@ pub struct FsCreateDirectoryParams { pub sandbox: Option, } +/// Filesystem RPC wire request with legacy optional sandbox policy cwd. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireFsCreateDirectoryParams { + path: PathUri, + recursive: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + follow_symlinks: Option, + sandbox: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FsCreateDirectoryResponse {} @@ -543,6 +650,16 @@ pub struct FsGetMetadataParams { pub sandbox: Option, } +/// Filesystem RPC wire request with legacy optional sandbox policy cwd. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireFsGetMetadataParams { + path: PathUri, + #[serde(default, skip_serializing_if = "Option::is_none")] + follow_symlinks: Option, + sandbox: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FsGetMetadataResponse { @@ -561,6 +678,14 @@ pub struct FsCanonicalizeParams { pub sandbox: Option, } +/// Filesystem RPC wire request with legacy optional sandbox policy cwd. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireFsCanonicalizeParams { + path: PathUri, + sandbox: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FsCanonicalizeResponse { @@ -574,6 +699,14 @@ pub struct FsReadDirectoryParams { pub sandbox: Option, } +/// Filesystem RPC wire request with legacy optional sandbox policy cwd. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireFsReadDirectoryParams { + path: PathUri, + sandbox: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FsReadDirectoryEntry { @@ -596,6 +729,15 @@ pub struct FsWalkParams { pub sandbox: Option, } +/// Filesystem RPC wire request with legacy optional sandbox policy cwd. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireFsWalkParams { + path: PathUri, + options: WalkOptions, + sandbox: Option, +} + pub type FsWalkResponse = WalkOutcome; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -609,6 +751,18 @@ pub struct FsRemoveParams { pub sandbox: Option, } +/// Filesystem RPC wire request with legacy optional sandbox policy cwd. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireFsRemoveParams { + path: PathUri, + recursive: Option, + force: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + follow_symlinks: Option, + sandbox: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FsRemoveResponse {} @@ -622,6 +776,16 @@ pub struct FsCopyParams { pub sandbox: Option, } +/// Filesystem RPC wire request with legacy optional sandbox policy cwd. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireFsCopyParams { + source_path: PathUri, + destination_path: PathUri, + recursive: bool, + sandbox: Option, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FsCopyResponse {} @@ -633,6 +797,13 @@ pub struct CapabilityRootsDiscoverParams { pub roots: Vec, } +/// Executor ingress for capability roots whose sandbox policy cwd may be absent. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireCapabilityRootsDiscoverParams { + roots: Vec, +} + /// One caller-selected capability root. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -646,6 +817,84 @@ pub struct CapabilityRootDiscoverRequest { pub sandbox: Option, } +/// One executor-ingress capability root with legacy optional sandbox policy cwd. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireCapabilityRootDiscoverRequest { + id: String, + path: PathUri, + sandbox: Option, +} + +// Destructuring both types makes adding a request field require updating the wire conversion. +macro_rules! impl_wire_filesystem_request { + ($($wire:ident => $request:ident { $($field:ident),+ $(,)? }),+ $(,)?) => {$( + impl From<$request> for $wire { + fn from(request: $request) -> Self { + let $request { $($field,)+ sandbox } = request; + Self { $($field,)+ sandbox: sandbox.map(Into::into) } + } + } + + impl $wire { + /// Resolves optional wire sandbox intent before it reaches an executor handler. + pub fn try_into_request( + self, + resolve: fn(WireFileSystemSandboxContext) -> Result, + ) -> Result<$request, JSONRPCErrorError> { + let Self { $($field,)+ sandbox } = self; + Ok($request { $($field,)+ sandbox: sandbox.map(resolve).transpose()? }) + } + } + )+}; +} + +impl_wire_filesystem_request! { + WireFsReadFileParams => FsReadFileParams { path, follow_symlinks }, + WireFsOpenParams => FsOpenParams { handle_id, path }, + WireFsWriteFileParams => FsWriteFileParams { path, data_base64, follow_symlinks }, + WireFsCreateDirectoryParams => FsCreateDirectoryParams { path, recursive, follow_symlinks }, + WireFsGetMetadataParams => FsGetMetadataParams { path, follow_symlinks }, + WireFsCanonicalizeParams => FsCanonicalizeParams { path }, + WireFsReadDirectoryParams => FsReadDirectoryParams { path }, + WireFsWalkParams => FsWalkParams { path, options }, + WireFsRemoveParams => FsRemoveParams { path, recursive, force, follow_symlinks }, + WireFsCopyParams => FsCopyParams { source_path, destination_path, recursive }, +} + +impl WireCapabilityRootDiscoverRequest { + /// Resolves optional wire sandbox intent before it reaches an executor handler. + pub fn try_into_request( + self, + resolve: fn( + WireFileSystemSandboxContext, + ) -> Result, + ) -> Result { + let Self { id, path, sandbox } = self; + Ok(CapabilityRootDiscoverRequest { + id, + path, + sandbox: sandbox.map(resolve).transpose()?, + }) + } +} + +impl WireCapabilityRootsDiscoverParams { + /// Resolves each root's optional wire sandbox before it reaches an executor handler. + pub fn try_into_request( + self, + resolve: fn( + WireFileSystemSandboxContext, + ) -> Result, + ) -> Result { + let mut roots = Vec::with_capacity(self.roots.len()); + for root in self.roots { + roots.push(root.try_into_request(resolve)?); + } + Ok(CapabilityRootsDiscoverParams { roots }) + } +} + /// Executor-local discovery results in request order. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -908,17 +1157,21 @@ mod base64_bytes { #[cfg(test)] mod tests { + use super::CapabilityRootDiscoverRequest; use super::EnvironmentCapabilities; use super::EnvironmentInfo; use super::ExecExitedNotification; use super::ExecMetadata; use super::ExecParams; use super::ExecResponse; + use super::FsOpenParams; use super::FsReadFileParams; use super::HttpRequestParams; use super::ProcessId; use super::ProcessSandboxType; use super::ShellInfo; + use super::WireFsOpenParams; + use super::WireFsReadFileParams; use codex_file_system::FileSystemSandboxContext; use codex_file_system::WindowsSandboxSelection; use codex_network_proxy::ManagedNetworkSandboxContext; @@ -1222,7 +1475,7 @@ mod tests { })) .expect_err("native absolute path should not deserialize as a URI"); - let sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::default(), PathUri::from_host_native_path(&native_cwd).expect("cwd URI"), ); @@ -1273,13 +1526,14 @@ mod tests { network: NetworkSandboxPolicy::Restricted, }; let mut sandbox = - FileSystemSandboxContext::from_permission_profile_with_cwd(permissions, cwd.clone()); + FileSystemSandboxContext::from_permission_profile(permissions, cwd.clone()); sandbox.user_home_dir = Some(cwd.clone()); sandbox.windows_sandbox_selection = WindowsSandboxSelection::Mxc; let serialized = serde_json::to_value(&sandbox).expect("serialize sandbox"); assert_eq!(serialized["windowsSandboxLevel"], "mxc"); + assert_eq!(serialized["cwd"], serde_json::json!(cwd.to_string())); assert_eq!( serialized["userHomeDir"], serde_json::json!(cwd.to_string()) @@ -1324,6 +1578,150 @@ mod tests { ); } + /// The filesystem RPC preserves Windows drive and UNC permission URIs on any host. + #[test] + fn filesystem_protocol_preserves_foreign_permission_path_json() { + let cwd = PathUri::parse("file:///C:/a%20b").expect("drive cwd URI"); + let unc = PathUri::parse("file://host/s/a%20b").expect("UNC path URI"); + let permissions = PermissionProfile::Managed { + file_system: ManagedFileSystemPermissions::Restricted { + entries: [cwd.clone(), unc.clone()] + .into_iter() + .map(|path| { + FileSystemSandboxEntry::new(path.into(), FileSystemAccessMode::Read) + }) + .collect(), + glob_scan_max_depth: None, + }, + network: NetworkSandboxPolicy::Restricted, + }; + let params = FsReadFileParams { + path: unc, + follow_symlinks: None, + sandbox: Some(FileSystemSandboxContext::from_permission_profile( + permissions, + cwd, + )), + }; + let serialized = serde_json::to_value(WireFsReadFileParams::from(params.clone())) + .expect("serialize filesystem wire request"); + assert_eq!( + serialized["sandbox"]["permissions"], + serde_json::json!({ + "type": "managed", + "file_system": { + "type": "restricted", + "entries": [ + {"path": {"type": "path", "path": "file:///C:/a%20b"}, "access": "read"}, + {"path": {"type": "path", "path": "file://host/s/a%20b"}, "access": "read"} + ] + }, + "network": "restricted" + }), + ); + assert_eq!( + serde_json::from_value::(serialized) + .expect("deserialize filesystem wire request") + .try_into_request(|wire| { + let cwd = wire.cwd().expect("explicit client policy cwd").clone(); + Ok(wire.into_context(cwd)) + }) + .expect("resolve filesystem request"), + params, + ); + } + + /// Executor ingress must use the full policy context instead of interpreting legacy helper fields. + #[test] + fn filesystem_protocol_prefers_explicit_policy_paths_over_legacy_fields() { + let cwd = PathUri::parse("file:///workspace/selected").expect("selected policy cwd"); + let workspace = PathUri::parse("file:///workspace/other").expect("selected workspace"); + let path = cwd.join("note.txt").expect("read path"); + let sandbox = FileSystemSandboxContext { + workspace_roots: vec![workspace], + ..FileSystemSandboxContext::from_permission_profile(PermissionProfile::Disabled, cwd) + }; + let params = FsReadFileParams { + path, + follow_symlinks: None, + sandbox: Some(sandbox), + }; + let mut json = serde_json::to_value(WireFsReadFileParams::from(params.clone())) + .expect("serialize wire read"); + json["sandbox"]["cwd"] = serde_json::json!("file:///legacy"); + json["sandbox"]["workspaceRoots"] = serde_json::json!(["file:///legacy"]); + let wire: WireFsReadFileParams = serde_json::from_value(json).expect("wire read"); + let request = wire + .try_into_request(|wire| { + let cwd = wire.cwd().expect("explicit policy cwd").clone(); + Ok(wire.into_context(cwd)) + }) + .expect("strict executor read"); + assert_eq!(request, params); + } + + /// Only filesystem RPCs need the additive policy field; capability discovery keeps its original wire cwd. + #[test] + fn filesystem_open_and_capability_discovery_keep_their_existing_cwd_contracts() { + let cwd = PathUri::parse("file:///D:/selected").expect("Windows policy cwd"); + let path = cwd.join("note.txt").expect("read path"); + let mut sandbox = FileSystemSandboxContext::from_permission_profile( + PermissionProfile::Disabled, + cwd.clone(), + ); + sandbox.windows_sandbox_selection = WindowsSandboxSelection::Mxc; + let open = FsOpenParams { + handle_id: "handle".to_owned(), + path: path.clone(), + sandbox: Some(sandbox.clone()), + }; + let capability = CapabilityRootDiscoverRequest { + id: "root".to_owned(), + path, + sandbox: Some(sandbox), + }; + let open_wire = + serde_json::to_value(WireFsOpenParams::from(open.clone())).expect("serialize open"); + let capability_wire = serde_json::to_value(&capability).expect("serialize capability"); + assert_eq!( + ( + open_wire["sandbox"].get("cwd"), + open_wire["sandbox"].get("workspaceRoots"), + open_wire["sandbox"].get("policyContext"), + open_wire["sandbox"].get("windowsSandboxLevel"), + capability_wire["sandbox"].get("cwd"), + capability_wire["sandbox"].get("workspaceRoots"), + capability_wire["sandbox"].get("policyContext"), + capability_wire["sandbox"].get("windowsSandboxLevel"), + ), + ( + None, + None, + Some(&serde_json::json!({"cwd": cwd, "workspaceRoots": [cwd]})), + Some(&serde_json::json!("mxc")), + Some(&serde_json::json!(cwd)), + Some(&serde_json::json!([cwd])), + None, + Some(&serde_json::json!("mxc")), + ) + ); + assert_eq!( + serde_json::from_value::(open_wire) + .expect("deserialize wire open") + .try_into_request(|wire| { + let cwd = wire.cwd().expect("explicit client policy cwd").clone(); + Ok(wire.into_context(cwd)) + }) + .expect("resolve open"), + open + ); + assert_eq!( + serde_json::from_value::(capability_wire) + .expect("deserialize capability"), + capability + ); + } + #[test] fn filesystem_protocol_round_trips_legacy_policy_paths_as_uris() { let native_cwd = std::env::current_dir().expect("current directory"); @@ -1339,8 +1737,7 @@ mod tests { &file_system_policy, NetworkSandboxPolicy::Restricted, ); - let sandbox = - FileSystemSandboxContext::from_permission_profile_with_cwd(permissions, cwd.clone()); + let sandbox = FileSystemSandboxContext::from_permission_profile(permissions, cwd.clone()); let serialized = serde_json::to_value(&sandbox).expect("serialize sandbox"); diff --git a/codex-rs/exec-server/BUILD.bazel b/codex-rs/exec-server/BUILD.bazel index 4fba596f48..cf8c72ae79 100644 --- a/codex-rs/exec-server/BUILD.bazel +++ b/codex-rs/exec-server/BUILD.bazel @@ -20,6 +20,8 @@ codex_rust_crate( ], extra_binaries = [ "//codex-rs/bwrap:bwrap", + "//codex-rs/windows-sandbox-rs:codex-command-runner", + "//codex-rs/windows-sandbox-rs:codex-windows-sandbox-setup", ], integration_compile_data_extra = [ "src/proto/codex.exec_server.relay.v1.rs", diff --git a/codex-rs/exec-server/Cargo.toml b/codex-rs/exec-server/Cargo.toml index bc441d9fe4..50c728b04a 100644 --- a/codex-rs/exec-server/Cargo.toml +++ b/codex-rs/exec-server/Cargo.toml @@ -83,6 +83,7 @@ windows-sys = { version = "0.52", features = [ anyhow = { workspace = true } codex-exec-server-test-support = { workspace = true } codex-test-binary-support = { workspace = true } +codex-utils-cargo-bin = { workspace = true } ctor = { workspace = true } http = { workspace = true } opentelemetry_sdk = { workspace = true } diff --git a/codex-rs/exec-server/src/capability_discovery.rs b/codex-rs/exec-server/src/capability_discovery.rs index c1c5f44883..4799db98d2 100644 --- a/codex-rs/exec-server/src/capability_discovery.rs +++ b/codex-rs/exec-server/src/capability_discovery.rs @@ -76,6 +76,13 @@ async fn discover_root( error: None, }; + if let Some(sandbox) = sandbox + && let Err(error) = sandbox.validate_file_system_paths_for_current_host() + { + discovery.error = Some(format!("failed to inspect capability root {path}: {error}")); + return discovery; + } + #[cfg(target_os = "windows")] if sandbox.is_some_and(|context| { context.should_run_in_sandbox() && !context.windows_sandbox_is_requested() diff --git a/codex-rs/exec-server/src/client.rs b/codex-rs/exec-server/src/client.rs index a8baa33fde..99d0255493 100644 --- a/codex-rs/exec-server/src/client.rs +++ b/codex-rs/exec-server/src/client.rs @@ -120,6 +120,16 @@ use crate::protocol::SignalParams; use crate::protocol::SignalResponse; use crate::protocol::TerminateParams; use crate::protocol::TerminateResponse; +use crate::protocol::WireFsCanonicalizeParams; +use crate::protocol::WireFsCopyParams; +use crate::protocol::WireFsCreateDirectoryParams; +use crate::protocol::WireFsGetMetadataParams; +use crate::protocol::WireFsOpenParams; +use crate::protocol::WireFsReadDirectoryParams; +use crate::protocol::WireFsReadFileParams; +use crate::protocol::WireFsRemoveParams; +use crate::protocol::WireFsWalkParams; +use crate::protocol::WireFsWriteFileParams; use crate::protocol::WriteParams; use crate::protocol::WriteResponse; use crate::rpc::RpcCallError; @@ -900,11 +910,13 @@ impl ExecServerClient { &self, params: FsReadFileParams, ) -> Result { - self.call(FS_READ_FILE_METHOD, ¶ms).await + self.call(FS_READ_FILE_METHOD, &WireFsReadFileParams::from(params)) + .await } pub async fn fs_open(&self, params: FsOpenParams) -> Result { - self.call(FS_OPEN_METHOD, ¶ms).await + self.call(FS_OPEN_METHOD, &WireFsOpenParams::from(params)) + .await } pub async fn fs_read_block( @@ -925,50 +937,70 @@ impl ExecServerClient { &self, params: FsWriteFileParams, ) -> Result { - self.call(FS_WRITE_FILE_METHOD, ¶ms).await + self.call(FS_WRITE_FILE_METHOD, &WireFsWriteFileParams::from(params)) + .await } pub async fn fs_create_directory( &self, params: FsCreateDirectoryParams, ) -> Result { - self.call(FS_CREATE_DIRECTORY_METHOD, ¶ms).await + self.call( + FS_CREATE_DIRECTORY_METHOD, + &WireFsCreateDirectoryParams::from(params), + ) + .await } pub async fn fs_get_metadata( &self, params: FsGetMetadataParams, ) -> Result { - self.call(FS_GET_METADATA_METHOD, ¶ms).await + self.call( + FS_GET_METADATA_METHOD, + &WireFsGetMetadataParams::from(params), + ) + .await } pub async fn fs_canonicalize( &self, params: FsCanonicalizeParams, ) -> Result { - self.call(FS_CANONICALIZE_METHOD, ¶ms).await + self.call( + FS_CANONICALIZE_METHOD, + &WireFsCanonicalizeParams::from(params), + ) + .await } pub async fn fs_read_directory( &self, params: FsReadDirectoryParams, ) -> Result { - self.call(FS_READ_DIRECTORY_METHOD, ¶ms).await + self.call( + FS_READ_DIRECTORY_METHOD, + &WireFsReadDirectoryParams::from(params), + ) + .await } pub async fn fs_walk(&self, params: FsWalkParams) -> Result { - self.call(FS_WALK_METHOD, ¶ms).await + self.call(FS_WALK_METHOD, &WireFsWalkParams::from(params)) + .await } pub async fn fs_remove( &self, params: FsRemoveParams, ) -> Result { - self.call(FS_REMOVE_METHOD, ¶ms).await + self.call(FS_REMOVE_METHOD, &WireFsRemoveParams::from(params)) + .await } pub async fn fs_copy(&self, params: FsCopyParams) -> Result { - self.call(FS_COPY_METHOD, ¶ms).await + self.call(FS_COPY_METHOD, &WireFsCopyParams::from(params)) + .await } pub(crate) async fn start_process( diff --git a/codex-rs/exec-server/src/environment.rs b/codex-rs/exec-server/src/environment.rs index 26b8825d72..bc1e68491f 100644 --- a/codex-rs/exec-server/src/environment.rs +++ b/codex-rs/exec-server/src/environment.rs @@ -1838,7 +1838,7 @@ mod tests { let source = sandbox_cwd .to_abs_path() .expect_err("sandbox cwd should not be native to this host"); - let sandbox = crate::FileSystemSandboxContext::from_permission_profile_with_cwd( + let sandbox = crate::FileSystemSandboxContext::from_permission_profile( codex_protocol::models::PermissionProfile::workspace_write(), sandbox_cwd.clone(), ); @@ -1890,6 +1890,8 @@ mod tests { &codex_protocol::permissions::FileSystemSandboxPolicy::restricted(Vec::new()), codex_protocol::permissions::NetworkSandboxPolicy::Restricted, ), + PathUri::from_host_native_path(std::env::current_dir().expect("read current dir")) + .expect("cwd URI"), ); let err = environment diff --git a/codex-rs/exec-server/src/fs_sandbox.rs b/codex-rs/exec-server/src/fs_sandbox.rs index 74a20d1a5c..945b43901b 100644 --- a/codex-rs/exec-server/src/fs_sandbox.rs +++ b/codex-rs/exec-server/src/fs_sandbox.rs @@ -20,6 +20,10 @@ use codex_sandboxing::SandboxType; use codex_utils_absolute_path::AbsolutePathBuf; #[cfg(not(target_os = "linux"))] use codex_utils_absolute_path::canonicalize_preserving_symlinks; +#[cfg(any(windows, test))] +use codex_utils_path_uri::LegacyAppPathString; +#[cfg(any(windows, test))] +use codex_utils_path_uri::PathConvention; use codex_utils_path_uri::PathUri; #[cfg(any(windows, test))] use tokio::io::AsyncBufReadExt; @@ -34,7 +38,6 @@ use crate::fs_helper::CODEX_FS_HELPER_ARG1; use crate::fs_helper::FsHelperPayload; use crate::fs_helper::FsHelperRequest; use crate::fs_helper::FsHelperResponse; -use crate::local_file_system::current_sandbox_cwd; use crate::rpc::internal_error; use crate::rpc::invalid_request; @@ -100,12 +103,13 @@ impl FileSystemSandboxRunner { .map(native_workspace_root) .collect::, _>>()?; let workspace_roots = native_workspace_roots.as_slice(); - let native_permissions: PermissionProfile = - sandbox.permissions.clone().try_into().map_err(|err| { - invalid_request(format!("invalid sandbox permission path URI: {err}")) - })?; - let native_permissions = - native_permissions.materialize_project_roots_with_workspace_roots(workspace_roots); + sandbox + .validate_file_system_paths_for_current_host() + .map_err(|err| invalid_request(err.to_string()))?; + let native_permissions = sandbox + .permissions + .clone() + .materialize_project_roots_with_workspace_roots(workspace_roots); let mut file_system_policy = native_permissions.file_system_sandbox_policy(); tracing::Span::current().record("permission_entries", file_system_policy.entries.len()); let helper_read_roots = if sandbox.use_legacy_landlock { @@ -122,6 +126,8 @@ impl FileSystemSandboxRunner { // unrelated permission roots synchronously on the executor's runtime thread. #[cfg(not(target_os = "linux"))] normalize_file_system_policy_root_aliases(&mut file_system_policy); + #[cfg(windows)] + bind_windows_cwd_relative_deny_read_globs(&mut file_system_policy, &cwd.uri)?; let network_policy = NetworkSandboxPolicy::Restricted; let permission_profile = PermissionProfile::from_runtime_permissions_with_enforcement( native_permissions.enforcement(), @@ -155,10 +161,17 @@ impl FileSystemSandboxRunner { "filesystem sandbox cannot be enforced on this executor".to_string(), )); } + // Requests use absolute paths; the helper can start at the filesystem root even if + // the policy cwd was removed. Keep its drive or share for Windows `:root` rules. + let helper_cwd = cwd + .native + .ancestors() + .last() + .ok_or_else(|| invalid_request("filesystem sandbox cwd has no root".to_string()))?; let command = SandboxCommand { program: helper.as_path().as_os_str().to_owned(), args: vec![CODEX_FS_HELPER_ARG1.to_string()], - cwd: cwd.uri.clone(), + cwd: PathUri::from_abs_path(&helper_cwd), env: self.helper_env.clone(), managed_network: None, additional_permissions: None, @@ -193,23 +206,10 @@ impl FileSystemSandboxRunner { } fn sandbox_cwd(sandbox: &FileSystemSandboxContext) -> Result { - if let Some(uri) = &sandbox.cwd { - return Ok(SandboxCwd { - native: native_sandbox_cwd(uri)?, - uri: uri.clone(), - }); - } - - if sandbox.has_cwd_dependent_permissions() { - return Err(invalid_request( - "file system sandbox context with dynamic permissions requires cwd".to_string(), - )); - } - - let native = AbsolutePathBuf::from_absolute_path(current_sandbox_cwd().map_err(io_error)?) - .map_err(|err| invalid_request(format!("current directory is not absolute: {err}")))?; - let uri = PathUri::from_abs_path(&native); - Ok(SandboxCwd { uri, native }) + Ok(SandboxCwd { + native: native_sandbox_cwd(&sandbox.cwd)?, + uri: sandbox.cwd.clone(), + }) } fn native_sandbox_cwd(cwd: &PathUri) -> Result { @@ -264,6 +264,34 @@ fn add_helper_runtime_permissions( } } +#[cfg(any(windows, test))] +fn bind_windows_cwd_relative_deny_read_globs( + file_system_policy: &mut FileSystemSandboxPolicy, + cwd: &PathUri, +) -> Result<(), JSONRPCErrorError> { + // The Windows direct-spawn wrapper reevaluates the profile using the helper cwd. + // Bind cwd-relative denials before moving the helper to the filesystem root. + for entry in &mut file_system_policy.entries { + if let FileSystemPath::GlobPattern { pattern } = &mut entry.path + && entry.access == FileSystemAccessMode::Deny + && PathConvention::Windows + .home_relative_suffix(pattern) + .is_none() + && LegacyAppPathString::from_string(pattern.as_str()) + .to_path_uri(PathConvention::Windows) + .is_err() + { + cwd.validate_glob_directory(PathConvention::Windows) + .map_err(|err| invalid_request(err.to_string()))?; + *pattern = cwd + .join(pattern.as_str()) + .map_err(|err| invalid_request(err.to_string()))? + .inferred_native_path_string(); + } + } + Ok(()) +} + #[cfg(not(target_os = "linux"))] fn normalize_file_system_policy_root_aliases(file_system_policy: &mut FileSystemSandboxPolicy) { for entry in &mut file_system_policy.entries { @@ -542,6 +570,7 @@ mod tests { use super::FileSystemSandboxRunner; use super::SandboxCwd; use super::add_helper_runtime_permissions; + use super::bind_windows_cwd_relative_deny_read_globs; use super::helper_env; use super::helper_env_from_vars; use super::helper_env_key_is_allowed; @@ -740,6 +769,147 @@ mod tests { assert_eq!(request.env.get(&path_key), Some(&path)); } + /// Removing the selected directory must not change permission anchoring or prevent launch. + #[test] + fn sandbox_exec_request_uses_filesystem_root_and_preserves_policy_cwd() { + let codex_self_exe = std::env::current_exe().expect("current exe"); + let runtime_paths = + ExecServerRuntimePaths::new(codex_self_exe.clone(), Some(codex_self_exe)) + .expect("runtime paths"); + let runner = FileSystemSandboxRunner::new(runtime_paths); + let selected = tempfile::tempdir().expect("selected directory"); + let selected_cwd = AbsolutePathBuf::from_absolute_path(selected.path()).expect("cwd"); + let root = selected_cwd.ancestors().last().expect("filesystem root"); + let policy = restricted_policy(vec![special_entry( + FileSystemSpecialPath::Root, + FileSystemAccessMode::Read, + )]); + let sandbox_context = + sandbox_context_with_cwd(&policy, PathUri::from_abs_path(&selected_cwd)); + #[cfg(windows)] + let sandbox_context = crate::FileSystemSandboxContext { + windows_sandbox_selection: codex_file_system::WindowsSandboxSelection::RestrictedToken, + ..sandbox_context + }; + selected.close().expect("remove selected directory"); + + let request = runner + .sandbox_command(&sandbox_context) + .expect("sandbox command"); + + assert_eq!( + (request.cwd, request.sandbox_policy_cwd), + ( + PathUri::from_abs_path(&root), + PathUri::from_abs_path(&selected_cwd) + ) + ); + } + + /// Tilde patterns stay home-relative when Windows sandbox commands start at another cwd. + #[test] + fn windows_cwd_relative_denial_binding_keeps_tilde_patterns_home_relative() { + let cwd = PathUri::parse("file:///C:/policy/checkout").expect("Windows policy cwd"); + let mut policy = restricted_policy( + [ + "~", + "~/", + r"~\", + "~/private/*.env", + r"~\private\*.env", + "hidden/*.env", + "~someone/private", + "D:/absolute/*.env", + ] + .into_iter() + .map(|pattern| { + FileSystemSandboxEntry::new( + FileSystemPath::GlobPattern { + pattern: pattern.to_string(), + }, + FileSystemAccessMode::Deny, + ) + }) + .collect(), + ); + + bind_windows_cwd_relative_deny_read_globs(&mut policy, &cwd).expect("bind Windows policy"); + + let patterns = policy + .entries + .into_iter() + .filter_map(|entry| match entry.path { + FileSystemPath::GlobPattern { pattern } => Some(pattern), + FileSystemPath::Path { .. } | FileSystemPath::Special { .. } => None, + }) + .collect::>(); + assert_eq!( + patterns, + [ + "~", + "~/", + r"~\", + "~/private/*.env", + r"~\private\*.env", + r"C:\policy\checkout\hidden\*.env", + r"C:\policy\checkout\~someone\private", + "D:/absolute/*.env", + ] + ); + } + + /// Windows wrapper policy checks must keep cwd-relative denials anchored to the selection. + #[cfg(windows)] + #[test] + fn sandbox_exec_request_binds_windows_relative_globs_to_policy_cwd() { + let codex_self_exe = std::env::current_exe().expect("current exe"); + let runtime_paths = + ExecServerRuntimePaths::new(codex_self_exe, /*codex_linux_sandbox_exe*/ None) + .expect("runtime paths"); + let runner = FileSystemSandboxRunner::new(runtime_paths); + let selected = tempfile::tempdir().expect("selected directory"); + let selected_cwd = AbsolutePathBuf::from_absolute_path(selected.path()).expect("cwd"); + let cwd_uri = PathUri::from_abs_path(&selected_cwd); + let pattern = "hidden/*.env"; + let absolute_pattern = cwd_uri + .join(pattern) + .expect("absolute glob") + .inferred_native_path_string(); + let policy = restricted_policy(vec![ + special_entry(FileSystemSpecialPath::Root, FileSystemAccessMode::Read), + FileSystemSandboxEntry::new( + FileSystemPath::GlobPattern { + pattern: pattern.to_string(), + }, + FileSystemAccessMode::Deny, + ), + ]); + let sandbox_context = crate::FileSystemSandboxContext { + windows_sandbox_selection: codex_file_system::WindowsSandboxSelection::Elevated, + ..sandbox_context_with_cwd(&policy, cwd_uri) + }; + selected.close().expect("remove selected directory"); + + let request = runner + .sandbox_command(&sandbox_context) + .expect("sandbox command"); + + assert_eq!( + request + .permission_profile + .file_system_sandbox_policy() + .entries + .into_iter() + .find(|entry| { matches!(entry.path, FileSystemPath::GlobPattern { .. }) }), + Some(FileSystemSandboxEntry::new( + FileSystemPath::GlobPattern { + pattern: absolute_pattern + }, + FileSystemAccessMode::Deny, + )) + ); + } + #[test] fn sandbox_cwd_uses_context_cwd() { let native_cwd = AbsolutePathBuf::from_absolute_path(std::env::temp_dir().as_path()) @@ -780,27 +950,6 @@ mod tests { ); } - #[test] - fn sandbox_cwd_rejects_cwd_dependent_profile_without_context_cwd() { - let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { - path: FileSystemPath::Special { - value: FileSystemSpecialPath::project_roots(/*subpath*/ None), - }, - access: FileSystemAccessMode::Write, - missing_path_behavior: None, - }]); - let sandbox_context = codex_file_system::FileSystemSandboxContext::from_permission_profile( - PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), - ); - - let err = sandbox_cwd(&sandbox_context).expect_err("missing cwd should be rejected"); - - assert_eq!( - err.message, - "file system sandbox context with dynamic permissions requires cwd" - ); - } - #[test] fn helper_permissions_include_only_the_helper_executable() { let codex_self_exe = std::env::current_exe().expect("current exe"); @@ -875,7 +1024,7 @@ mod tests { policy: &FileSystemSandboxPolicy, cwd: PathUri, ) -> crate::FileSystemSandboxContext { - codex_file_system::FileSystemSandboxContext::from_permission_profile_with_cwd( + codex_file_system::FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(policy, NetworkSandboxPolicy::Restricted), cwd, ) diff --git a/codex-rs/exec-server/src/local_file_system.rs b/codex-rs/exec-server/src/local_file_system.rs index 63048da72a..f4b29363f2 100644 --- a/codex-rs/exec-server/src/local_file_system.rs +++ b/codex-rs/exec-server/src/local_file_system.rs @@ -99,6 +99,9 @@ impl LocalFileSystem { &'a dyn ExecutorFileSystem, Option<&'a FileSystemSandboxContext>, )> { + if let Some(sandbox) = sandbox { + sandbox.validate_file_system_paths_for_current_host()?; + } if sandbox.is_some_and(FileSystemSandboxContext::should_run_in_sandbox) { Ok((self.sandboxed()?, sandbox)) } else { @@ -113,6 +116,9 @@ impl LocalFileSystem { path: &PathUri, sandbox: Option<&FileSystemSandboxContext>, ) -> FileSystemResult { + if let Some(sandbox) = sandbox { + sandbox.validate_file_system_paths_for_current_host()?; + } if sandbox.is_some_and(FileSystemSandboxContext::should_run_in_sandbox) { return self.sandboxed()?.open_file_for_read(path, sandbox).await; } @@ -1225,12 +1231,6 @@ pub(crate) fn resolve_existing_path(path: &Path) -> io::Result { Ok(resolved) } -pub(crate) fn current_sandbox_cwd() -> io::Result { - let cwd = std::env::current_dir() - .map_err(|err| io::Error::other(format!("failed to read current dir: {err}")))?; - resolve_existing_path(cwd.as_path()) -} - fn copy_symlink(source: &Path, target: &Path) -> io::Result<()> { let link_target = std::fs::read_link(source)?; #[cfg(unix)] @@ -1349,6 +1349,7 @@ mod walk_tests { &FileSystemSandboxPolicy::restricted(Vec::new()), NetworkSandboxPolicy::Restricted, ), + root.clone(), ); let options = WalkOptions { max_depth: 1, diff --git a/codex-rs/exec-server/src/process_sandbox.rs b/codex-rs/exec-server/src/process_sandbox.rs index 035bfa8831..5bc2b5d9fc 100644 --- a/codex-rs/exec-server/src/process_sandbox.rs +++ b/codex-rs/exec-server/src/process_sandbox.rs @@ -145,19 +145,18 @@ pub(crate) async fn prepare_exec_request_with_telemetry( windows_sandbox: None, }); }; + let runtime_paths = runtime_paths + .ok_or_else(|| invalid_params("sandbox runtime paths are not configured".to_string()))?; + sandbox_context + .validate_file_system_paths_for_current_host() + .map_err(|err| invalid_params(err.to_string()))?; let windows_sandbox_proxy_settings_mode = sandbox_context .windows_sandbox_proxy_settings_mode .unwrap_or_default(); - let runtime_paths = runtime_paths - .ok_or_else(|| invalid_params("sandbox runtime paths are not configured".to_string()))?; // TODO(jif): Transport permissions before orchestrator-local paths are materialized, // then resolve executor-local helper and workspace paths here. - let permissions: PermissionProfile = sandbox_context - .permissions - .clone() - .try_into() - .map_err(|err| invalid_params(format!("invalid sandbox permission path URI: {err}")))?; - let sandbox_policy_cwd = sandbox_context.cwd.as_ref().unwrap_or(¶ms.cwd); + let permissions = sandbox_context.permissions.clone(); + let sandbox_policy_cwd = &sandbox_context.cwd; let native_sandbox_policy_cwd = native_path(sandbox_policy_cwd, "sandbox cwd")?; let native_workspace_roots = sandbox_context .workspace_roots diff --git a/codex-rs/exec-server/src/process_sandbox_tests.rs b/codex-rs/exec-server/src/process_sandbox_tests.rs index 7e66b2e419..7f415f4dde 100644 --- a/codex-rs/exec-server/src/process_sandbox_tests.rs +++ b/codex-rs/exec-server/src/process_sandbox_tests.rs @@ -27,6 +27,8 @@ use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathUri; use pretty_assertions::assert_eq; +#[cfg(unix)] +use tempfile::tempdir; #[cfg(windows)] use test_case::test_case; use tokio::io::AsyncReadExt; @@ -65,15 +67,13 @@ async fn prepare_exec_request( #[cfg(unix)] #[tokio::test] async fn sandbox_request_wraps_native_argv_on_executor() { - let cwd: AbsolutePathBuf = std::env::current_dir() - .expect("current directory") - .try_into() - .expect("absolute cwd"); + let command_directory = tempdir().expect("command directory"); + let cwd = AbsolutePathBuf::from_absolute_path(command_directory.path()).expect("absolute cwd"); let cwd_uri = PathUri::from_abs_path(&cwd); let self_exe = std::env::current_exe().expect("current executable"); let runtime_paths = ExecServerRuntimePaths::new(self_exe.clone(), Some(self_exe)).expect("runtime paths"); - let sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::workspace_write(), cwd_uri.clone(), ); @@ -129,6 +129,37 @@ async fn sandbox_request_wraps_native_argv_on_executor() { PermissionProfile::workspace_write() .materialize_project_roots_with_workspace_roots(std::slice::from_ref(&cwd)) ); + + let policy_directory = tempdir().expect("policy directory"); + let explicit_cwd = + AbsolutePathBuf::from_absolute_path(policy_directory.path()).expect("policy cwd"); + let mut params = params.clone(); + for policy_cwd in [&cwd, &explicit_cwd] { + params.sandbox.as_mut().expect("sandbox").cwd = PathUri::from_abs_path(policy_cwd); + let prepared = prepare_exec_request( + ¶ms, + HashMap::new(), + Some(&runtime_paths), + /*network_policy_decider*/ None, + /*network_policy_audit_observer*/ None, + ) + .await + .expect("prepare sandboxed request"); + let actual_cwds = prepared + .command + .windows(4) + .find(|args| args[0] == "--sandbox-policy-cwd") + .expect("sandbox wrapper cwd arguments"); + assert_eq!( + actual_cwds, + [ + "--sandbox-policy-cwd", + policy_cwd.to_string_lossy().as_ref(), + "--command-cwd", + cwd.to_string_lossy().as_ref(), + ] + ); + } } #[cfg(target_os = "macos")] assert_eq!( @@ -162,7 +193,7 @@ async fn sandbox_request_routes_custom_arg0_to_inner_helper() { let self_exe = std::env::current_exe().expect("current executable"); let runtime_paths = ExecServerRuntimePaths::new(self_exe.clone(), Some(self_exe)).expect("runtime paths"); - let sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::workspace_write(), cwd_uri.clone(), ); @@ -224,7 +255,7 @@ fn managed_network_sandbox_request() -> (ExecParams, ExecServerRuntimePaths) { let self_exe = std::env::current_exe().expect("current executable"); let runtime_paths = ExecServerRuntimePaths::new(self_exe.clone(), Some(self_exe)).expect("runtime paths"); - let sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::workspace_write(), cwd_uri.clone(), ); @@ -617,10 +648,8 @@ async fn managed_network_honors_windows_sandbox_level(windows_sandbox_level: Win let self_exe = std::env::current_exe().expect("current executable"); let runtime_paths = ExecServerRuntimePaths::new(self_exe, None).expect("runtime paths"); let permissions = PermissionProfile::read_only(); - let mut sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( - permissions.clone(), - cwd_uri.clone(), - ); + let mut sandbox = + FileSystemSandboxContext::from_permission_profile(permissions.clone(), cwd_uri.clone()); sandbox.windows_sandbox_selection = windows_sandbox_level.into(); sandbox.windows_sandbox_proxy_settings_mode = Some(codex_sandboxing::WindowsSandboxProxySettingsMode::Preserve); diff --git a/codex-rs/exec-server/src/remote_file_stream.rs b/codex-rs/exec-server/src/remote_file_stream.rs index 107dea51d7..f71e5fd1ee 100644 --- a/codex-rs/exec-server/src/remote_file_stream.rs +++ b/codex-rs/exec-server/src/remote_file_stream.rs @@ -24,7 +24,7 @@ struct FileReadRegistration { pub(super) async fn open( client: ExecServerClient, path: PathUri, - sandbox: Option, + sandbox: Option<&FileSystemSandboxContext>, ) -> FileSystemResult { let registration = FileReadRegistration { client, @@ -37,7 +37,7 @@ pub(super) async fn open( .fs_open(FsOpenParams { handle_id: registration.handle_id.clone(), path, - sandbox, + sandbox: sandbox.cloned(), }) .await .map_err(map_remote_error)?; diff --git a/codex-rs/exec-server/src/remote_file_system.rs b/codex-rs/exec-server/src/remote_file_system.rs index d574cece8c..33d3b0be69 100644 --- a/codex-rs/exec-server/src/remote_file_system.rs +++ b/codex-rs/exec-server/src/remote_file_system.rs @@ -106,7 +106,7 @@ impl RemoteFileSystem { ) -> FileSystemResult { trace!("remote fs read_file_stream"); let client = self.client.get().await.map_err(map_remote_error)?; - file_stream::open(client, path.clone(), remote_sandbox_context(sandbox)).await + file_stream::open(client, path.clone(), sandbox).await } async fn write_file( @@ -410,9 +410,7 @@ impl ExecutorFileSystem for RemoteFileSystem { fn remote_sandbox_context( sandbox: Option<&FileSystemSandboxContext>, ) -> Option { - sandbox - .cloned() - .map(FileSystemSandboxContext::drop_cwd_if_unused) + sandbox.cloned() } fn map_remote_error(error: ExecServerError) -> io::Error { @@ -451,7 +449,7 @@ mod tests { use super::*; #[test] - fn remote_sandbox_context_drops_unused_cwd() { + fn remote_sandbox_context_preserves_cwd_for_absolute_permissions() { let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { path: FileSystemPath::Path { path: absolute_test_path("remote-root").into(), @@ -461,15 +459,14 @@ mod tests { }]); let permissions = PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted); - let sandbox_context = FileSystemSandboxContext::from_permission_profile_with_cwd( - permissions, - path_uri("host-checkout"), - ); + let cwd = path_uri("executor-checkout"); + let sandbox_context = + FileSystemSandboxContext::from_permission_profile(permissions, cwd.clone()); let remote_context = remote_sandbox_context(Some(&sandbox_context)).expect("remote sandbox context"); - assert_eq!(remote_context.cwd, None); + assert_eq!(remote_context.cwd, cwd); } #[test] @@ -485,12 +482,12 @@ mod tests { PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted); let cwd = path_uri("host-checkout"); let sandbox_context = - FileSystemSandboxContext::from_permission_profile_with_cwd(permissions, cwd.clone()); + FileSystemSandboxContext::from_permission_profile(permissions, cwd.clone()); let remote_context = remote_sandbox_context(Some(&sandbox_context)).expect("remote sandbox context"); - assert_eq!(remote_context.cwd, Some(cwd)); + assert_eq!(remote_context.cwd, cwd); } #[test] diff --git a/codex-rs/exec-server/src/remote_file_system_path_uri_tests.rs b/codex-rs/exec-server/src/remote_file_system_path_uri_tests.rs index 4956f4bfdb..813574d1b1 100644 --- a/codex-rs/exec-server/src/remote_file_system_path_uri_tests.rs +++ b/codex-rs/exec-server/src/remote_file_system_path_uri_tests.rs @@ -42,7 +42,10 @@ use crate::protocol::FsReadFileResponse; use crate::protocol::INITIALIZE_METHOD; use crate::protocol::INITIALIZED_METHOD; use crate::protocol::InitializeResponse; +use crate::protocol::WireFsGetMetadataParams; +use crate::protocol::WireFsReadFileParams; +/// Absolute policies preserve foreign selection paths without adding legacy policy directories. #[tokio::test] async fn remote_file_system_sends_path_and_sandbox_cwd_uris_without_native_conversion() { let (websocket_url, captured_params, server) = @@ -59,17 +62,20 @@ async fn remote_file_system_sends_path_and_sandbox_cwd_uris_without_native_conve PathUri::parse("file://server/share/src/main.rs").expect("valid UNC URI"), ]; let sandbox_cwd = non_native_cwd(); - let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { - path: FileSystemPath::Special { - value: FileSystemSpecialPath::project_roots(/*subpath*/ None), - }, - access: FileSystemAccessMode::Write, - missing_path_behavior: None, - }]); - let sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let workspace_root = paths[0].parent().expect("workspace root URI"); + let policy = FileSystemSandboxPolicy::restricted( + paths + .iter() + .map(|path| { + FileSystemSandboxEntry::new(path.clone().into(), FileSystemAccessMode::Read) + }) + .collect(), + ); + let mut sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), sandbox_cwd, ); + sandbox.workspace_roots = vec![workspace_root]; for path in &paths { assert_eq!( @@ -81,6 +87,7 @@ async fn remote_file_system_sends_path_and_sandbox_cwd_uris_without_native_conve ); } + let captured_params = captured_params.await.expect("captured params"); let expected_params = paths .into_iter() .map(|path| FsReadFileParams { @@ -90,12 +97,279 @@ async fn remote_file_system_sends_path_and_sandbox_cwd_uris_without_native_conve }) .collect::>(); assert_eq!( - captured_params.await.expect("captured params"), + captured_params + .iter() + .map(|(params, _)| params.clone()) + .collect::>(), expected_params ); + let policy_context = serde_json::json!({ + "cwd": sandbox.cwd, + "workspaceRoots": sandbox.workspace_roots, + }); + for (_, raw_sandbox) in captured_params { + assert_eq!( + ( + raw_sandbox.get("cwd"), + raw_sandbox.get("workspaceRoots"), + raw_sandbox.get("policyContext"), + ), + (None, None, Some(&policy_context)), + ); + } server.await.expect("recording server should succeed"); } +/// Only dynamic policies retain legacy selection fields; all policies preserve the new context. +#[tokio::test] +async fn remote_file_system_preserves_only_cwd_dependent_policy_directories() { + let cases = [ + ( + "file:///workspace/checkout", + Some("/elsewhere/*.secret"), + None, + Some("selected-root"), + ), + ( + "file:///D:/checkout", + Some(r"D:\elsewhere\*.secret"), + None, + Some("selected-root"), + ), + ( + "file://server/share/checkout", + Some(r"\\server\share\elsewhere\*.secret"), + None, + Some("selected-root"), + ), + ( + "file:///workspace/checkout", + Some("*.secret"), + Some("file:///workspace/checkout"), + Some("selected-root"), + ), + ( + "file:///D:/checkout", + Some(r"private\*.secret"), + Some("file:///D:/checkout"), + Some("selected-root"), + ), + ( + "file:///workspace/checkout", + None, + Some("file:///workspace/checkout"), + Some("selected-root"), + ), + ( + "file:///D:/checkout", + None, + Some("file:///D:/checkout"), + None, + ), + ]; + let (websocket_url, captured_params, server) = record_read_file_params(cases.len()).await; + let file_system = RemoteFileSystem::new(LazyRemoteExecServerClient::new( + ExecServerTransportParams::websocket_url( + websocket_url, + DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT, + ), + HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), + )); + let mut expected_params = Vec::new(); + let mut expected_contexts = Vec::new(); + for (cwd, pattern, legacy_cwd, selected_root) in cases { + let cwd = PathUri::parse(cwd).expect("policy cwd"); + let path = cwd.join("public.txt").expect("operation path"); + let permission_path = match pattern { + Some(pattern) => FileSystemPath::GlobPattern { + pattern: pattern.to_string(), + }, + None => FileSystemPath::Special { + value: FileSystemSpecialPath::project_roots(/*subpath*/ None), + }, + }; + let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry::new( + permission_path, + FileSystemAccessMode::Deny, + )]); + let mut sandbox = FileSystemSandboxContext::from_permission_profile( + PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), + cwd.clone(), + ); + sandbox.workspace_roots = selected_root + .map(|root| cwd.join(root).expect("selected workspace root")) + .into_iter() + .collect(); + file_system + .read_file(&path, Default::default(), Some(&sandbox)) + .await + .expect("remote read"); + let legacy_cwd = legacy_cwd + .map(|cwd| serde_json::json!(PathUri::parse(cwd).expect("legacy policy cwd"))); + let legacy_roots = if legacy_cwd.is_some() && !sandbox.workspace_roots.is_empty() { + Some(serde_json::json!(sandbox.workspace_roots)) + } else { + None + }; + expected_contexts.push(( + legacy_cwd, + legacy_roots, + Some(serde_json::json!({ + "cwd": cwd, + "workspaceRoots": sandbox.workspace_roots, + })), + )); + expected_params.push(FsReadFileParams { + path, + follow_symlinks: None, + sandbox: Some(sandbox), + }); + } + let captured_params = captured_params.await.expect("captured params"); + assert_eq!( + captured_params + .iter() + .map(|(params, _)| params.clone()) + .collect::>(), + expected_params + ); + assert_eq!( + captured_params + .iter() + .map(|(_, sandbox)| { + ( + sandbox.get("cwd").cloned(), + sandbox.get("workspaceRoots").cloned(), + sandbox.get("policyContext").cloned(), + ) + }) + .collect::>(), + expected_contexts, + ); + server.await.expect("recording server should succeed"); +} + +/// Older executors can launch with their own cwd while newer executors retain the removed cwd. +#[tokio::test] +async fn remote_file_system_can_read_after_checkout_removal_with_legacy_helper_launch() { + let temp = tempfile::TempDir::new().expect("test directory"); + let checkout = temp.path().join("checkout"); + std::fs::create_dir(&checkout).expect("checkout should exist"); + let path = temp.path().join("allowed.txt"); + std::fs::write(&path, "allowed").expect("fixture should be writable"); + let path = PathUri::from_host_native_path(path).expect("absolute file path"); + let cwd = PathUri::from_host_native_path(&checkout).expect("absolute checkout"); + std::fs::remove_dir(checkout).expect("checkout should be removed"); + let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry::new( + path.clone().into(), + FileSystemAccessMode::Read, + )]); + let sandbox = FileSystemSandboxContext::from_permission_profile( + PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), + cwd.clone(), + ); + + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("listener should bind"); + let websocket_url = format!("ws://{}", listener.local_addr().expect("listener address")); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.expect("listener should accept"); + let mut websocket = accept_async(stream) + .await + .expect("websocket handshake should succeed"); + complete_websocket_initialize(&mut websocket).await; + let JSONRPCMessage::Request(request) = read_jsonrpc_websocket(&mut websocket).await else { + panic!("expected fs/readFile request"); + }; + assert_eq!(request.method, FS_READ_FILE_METHOD); + let raw_params = request.params.expect("read params"); + let raw_sandbox = raw_params + .get("sandbox") + .expect("raw sandbox should be sent"); + let policy_context = serde_json::json!({ + "cwd": cwd, + "workspaceRoots": [cwd], + }); + assert_eq!( + ( + raw_sandbox.get("cwd"), + raw_sandbox.get("workspaceRoots"), + raw_sandbox.get("policyContext"), + ), + (None, None, Some(&policy_context)), + ); + let legacy_cwd = raw_sandbox + .get("cwd") + .cloned() + .map(serde_json::from_value::) + .transpose() + .expect("legacy sandbox cwd"); + let params = serde_json::from_value::(raw_params) + .expect("wire read params") + .try_into_request(|wire| { + let cwd = wire.cwd().expect("explicit client policy cwd").clone(); + Ok(wire.into_context(cwd)) + }) + .expect("typed read params"); + let selected_sandbox = params.sandbox.expect("sandbox should be sent"); + assert_eq!( + (selected_sandbox.cwd, selected_sandbox.workspace_roots), + (cwd.clone(), vec![cwd]), + ); + // An old executor falls back to its own cwd when it spawns the helper for this policy. + let helper_cwd = match legacy_cwd { + Some(cwd) => cwd.to_abs_path().expect("native legacy cwd").to_path_buf(), + None => std::env::current_dir().expect("legacy executor cwd"), + }; + #[cfg(unix)] + let mut command = tokio::process::Command::new("cat"); + #[cfg(windows)] + let mut command = { + let mut command = tokio::process::Command::new("cmd.exe"); + command.args(["/C", "type"]); + command + }; + let output = command + .current_dir(helper_cwd) + .arg(params.path.to_abs_path().expect("native file").as_path()) + .output() + .await + .expect("legacy helper should launch"); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + write_jsonrpc_websocket( + &mut websocket, + JSONRPCMessage::Response(JSONRPCResponse { + id: request.id, + result: serde_json::to_value(FsReadFileResponse { + data_base64: STANDARD.encode(output.stdout), + }) + .expect("read response"), + }), + ) + .await; + }); + let file_system = RemoteFileSystem::new(LazyRemoteExecServerClient::new( + ExecServerTransportParams::websocket_url( + websocket_url, + DEFAULT_REMOTE_EXEC_SERVER_CONNECT_TIMEOUT, + ), + HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault), + )); + assert_eq!( + file_system + .read_file(&path, Default::default(), Some(&sandbox)) + .await + .expect("remote read"), + b"allowed" + ); + server.await.expect("legacy server should succeed"); +} + #[tokio::test] async fn concurrent_remote_metadata_requests_share_only_in_flight_results() { let (abandoned_request_tx, abandoned_request_rx) = oneshot::channel(); @@ -390,7 +664,7 @@ async fn remote_metadata_requests_do_not_cross_path_or_sandbox_boundaries() { )); let first_path = PathUri::parse("file:///workspace/project/AGENTS.md").expect("valid path URI"); let second_path = PathUri::parse("file:///workspace/project/SKILL.md").expect("valid path URI"); - let sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions( &FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { path: FileSystemPath::Special { @@ -447,7 +721,7 @@ async fn record_read_file_params( expected_requests: usize, ) -> ( String, - oneshot::Receiver>, + oneshot::Receiver>, tokio::task::JoinHandle<()>, ) { let listener = TcpListener::bind("127.0.0.1:0") @@ -470,10 +744,19 @@ async fn record_read_file_params( } other => panic!("expected fs/readFile request, got {other:?}"), }; - let params: FsReadFileParams = - serde_json::from_value(request.params.expect("fs/readFile params should exist")) - .expect("fs/readFile params should deserialize"); - captured_params.push(params); + let raw_params = request.params.expect("fs/readFile params should exist"); + let raw_sandbox = raw_params + .get("sandbox") + .expect("fs/readFile sandbox should exist") + .clone(); + let params = serde_json::from_value::(raw_params) + .expect("fs/readFile wire params should deserialize") + .try_into_request(|wire| { + let cwd = wire.cwd().expect("explicit client policy cwd").clone(); + Ok(wire.into_context(cwd)) + }) + .expect("fs/readFile params should convert"); + captured_params.push((params, raw_sandbox)); write_jsonrpc_websocket( &mut websocket, JSONRPCMessage::Response(JSONRPCResponse { @@ -554,10 +837,15 @@ async fn record_metadata_params( )); } else { assert_eq!(request.method, FS_GET_METADATA_METHOD); - let params: FsGetMetadataParams = serde_json::from_value( + let params = serde_json::from_value::( request.params.expect("fs/getMetadata params should exist"), ) - .expect("fs/getMetadata params should deserialize"); + .expect("fs/getMetadata wire params should deserialize") + .try_into_request(|wire| { + let cwd = wire.cwd().expect("explicit client policy cwd").clone(); + Ok(wire.into_context(cwd)) + }) + .expect("fs/getMetadata params should convert"); captured_params.push(params); } let response = match response { diff --git a/codex-rs/exec-server/src/sandboxed_file_system_path_uri_tests.rs b/codex-rs/exec-server/src/sandboxed_file_system_path_uri_tests.rs index 031d89080f..f39f01e0e4 100644 --- a/codex-rs/exec-server/src/sandboxed_file_system_path_uri_tests.rs +++ b/codex-rs/exec-server/src/sandboxed_file_system_path_uri_tests.rs @@ -1,5 +1,9 @@ use codex_protocol::models::PermissionProfile; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::FileSystemSpecialPath; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_utils_path_uri::PathUri; use pretty_assertions::assert_eq; @@ -14,12 +18,14 @@ async fn sandboxed_file_system_rejects_non_native_uri_as_invalid_input() { /*codex_linux_sandbox_exe*/ None, ) .expect("runtime paths"); - let file_system = SandboxedFileSystem::new(runtime_paths); + let file_system = SandboxedFileSystem::new(runtime_paths.clone()); + let cwd = PathUri::from_host_native_path(std::env::temp_dir()).expect("native temporary cwd"); let sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions( &FileSystemSandboxPolicy::restricted(Vec::new()), NetworkSandboxPolicy::Restricted, ), + cwd.clone(), ); let error = file_system @@ -28,6 +34,34 @@ async fn sandboxed_file_system_rejects_non_native_uri_as_invalid_input() { .expect_err("non-native URI should be rejected"); assert_eq!(error.kind(), io::ErrorKind::InvalidInput); + + // A foreign permission path must not select the unsandboxed filesystem, even with a root grant. + let file_system = crate::LocalFileSystem::with_runtime_paths(runtime_paths); + let foreign = non_native_uri(); + let policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + FileSystemAccessMode::Write, + ), + FileSystemSandboxEntry::new(foreign.clone().into(), FileSystemAccessMode::Write), + ]); + let sandbox = FileSystemSandboxContext::from_permission_profile( + PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), + cwd, + ); + let readable = tempfile::NamedTempFile::new().expect("readable file"); + let error = file_system + .read_file( + &PathUri::from_host_native_path(readable.path()).expect("readable file URI"), + Default::default(), + Some(&sandbox), + ) + .await + .expect_err("foreign permission path must not allow unsandboxed access"); + assert_eq!(error.kind(), io::ErrorKind::InvalidInput); + assert!(error.to_string().contains(&foreign.to_string())); } fn non_native_uri() -> PathUri { diff --git a/codex-rs/exec-server/src/server/file_system_handler.rs b/codex-rs/exec-server/src/server/file_system_handler.rs index 8acc2a39c6..cdddddf689 100644 --- a/codex-rs/exec-server/src/server/file_system_handler.rs +++ b/codex-rs/exec-server/src/server/file_system_handler.rs @@ -79,7 +79,10 @@ impl FileSystemHandler { .first() .and_then(|root| root.sandbox.as_ref()) .filter(|sandbox| { - sandbox.should_run_in_sandbox() + sandbox + .validate_file_system_paths_for_current_host() + .is_ok() + && sandbox.should_run_in_sandbox() && (!cfg!(target_os = "windows") || sandbox.windows_sandbox_is_requested()) && params .roots diff --git a/codex-rs/exec-server/src/server/registry.rs b/codex-rs/exec-server/src/server/registry.rs index 4cd21ad85e..9eeba5bfa1 100644 --- a/codex-rs/exec-server/src/server/registry.rs +++ b/codex-rs/exec-server/src/server/registry.rs @@ -1,8 +1,11 @@ +use codex_file_system::FileSystemSandboxContext; +use codex_file_system::WireFileSystemSandboxContext; +use codex_utils_path_uri::PathUri; use opentelemetry::trace::TraceContextExt; use std::sync::Arc; +use crate::local_file_system::resolve_existing_path; use crate::protocol::CAPABILITY_ROOTS_DISCOVER_METHOD; -use crate::protocol::CapabilityRootsDiscoverParams; use crate::protocol::ENVIRONMENT_CONFIG_READ_METHOD; use crate::protocol::ENVIRONMENT_INFO_METHOD; use crate::protocol::ENVIRONMENT_STATUS_METHOD; @@ -12,7 +15,6 @@ use crate::protocol::EXEC_SIGNAL_METHOD; use crate::protocol::EXEC_TERMINATE_METHOD; use crate::protocol::EXEC_WRITE_METHOD; use crate::protocol::EnvironmentConfigReadParams; -use crate::protocol::ExecParams; use crate::protocol::FS_CANONICALIZE_METHOD; use crate::protocol::FS_CLOSE_METHOD; use crate::protocol::FS_COPY_METHOD; @@ -25,28 +27,33 @@ use crate::protocol::FS_READ_FILE_METHOD; use crate::protocol::FS_REMOVE_METHOD; use crate::protocol::FS_WALK_METHOD; use crate::protocol::FS_WRITE_FILE_METHOD; -use crate::protocol::FsCanonicalizeParams; use crate::protocol::FsCloseParams; -use crate::protocol::FsCopyParams; -use crate::protocol::FsCreateDirectoryParams; -use crate::protocol::FsGetMetadataParams; -use crate::protocol::FsOpenParams; use crate::protocol::FsReadBlockParams; -use crate::protocol::FsReadDirectoryParams; -use crate::protocol::FsReadFileParams; -use crate::protocol::FsRemoveParams; -use crate::protocol::FsWalkParams; -use crate::protocol::FsWriteFileParams; use crate::protocol::HTTP_REQUEST_METHOD; use crate::protocol::HttpRequestParams; use crate::protocol::INITIALIZE_METHOD; use crate::protocol::INITIALIZED_METHOD; use crate::protocol::InitializeParams; +use crate::protocol::JSONRPCErrorError; use crate::protocol::ReadParams; use crate::protocol::SignalParams; use crate::protocol::TerminateParams; +use crate::protocol::WireCapabilityRootsDiscoverParams; +use crate::protocol::WireExecParams; +use crate::protocol::WireFsCanonicalizeParams; +use crate::protocol::WireFsCopyParams; +use crate::protocol::WireFsCreateDirectoryParams; +use crate::protocol::WireFsGetMetadataParams; +use crate::protocol::WireFsOpenParams; +use crate::protocol::WireFsReadDirectoryParams; +use crate::protocol::WireFsReadFileParams; +use crate::protocol::WireFsRemoveParams; +use crate::protocol::WireFsWalkParams; +use crate::protocol::WireFsWriteFileParams; use crate::protocol::WriteParams; use crate::rpc::RpcRouter; +use crate::rpc::internal_error; +use crate::rpc::invalid_params; use crate::server::ExecServerHandler; pub(crate) fn build_router() -> RpcRouter { @@ -71,12 +78,12 @@ pub(crate) fn build_router() -> RpcRouter { ); router.request_with_trace( EXEC_METHOD, - |handler: Arc, params: ExecParams, trace| async move { + |handler: Arc, params: WireExecParams, trace| async move { let launch_context = trace .as_ref() .and_then(codex_otel::context_from_w3c_trace_context) .map(|context| context.span().span_context().clone()); - handler.exec(params, launch_context).await + handler.exec(params.into(), launch_context).await }, ); router.request( @@ -95,7 +102,8 @@ pub(crate) fn build_router() -> RpcRouter { ); router.request( CAPABILITY_ROOTS_DISCOVER_METHOD, - |handler: Arc, params: CapabilityRootsDiscoverParams| async move { + |handler: Arc, params: WireCapabilityRootsDiscoverParams| async move { + let params = params.try_into_request(resolve_filesystem_sandbox)?; handler.discover_capability_roots(params).await }, ); @@ -125,13 +133,15 @@ pub(crate) fn build_router() -> RpcRouter { ); router.request( FS_READ_FILE_METHOD, - |handler: Arc, params: FsReadFileParams| async move { + |handler: Arc, params: WireFsReadFileParams| async move { + let params = params.try_into_request(resolve_filesystem_sandbox)?; handler.fs_read_file(params).await }, ); router.request( FS_OPEN_METHOD, - |handler: Arc, params: FsOpenParams| async move { + |handler: Arc, params: WireFsOpenParams| async move { + let params = params.try_into_request(resolve_filesystem_sandbox)?; handler.fs_open(params).await }, ); @@ -149,51 +159,80 @@ pub(crate) fn build_router() -> RpcRouter { ); router.request( FS_WRITE_FILE_METHOD, - |handler: Arc, params: FsWriteFileParams| async move { + |handler: Arc, params: WireFsWriteFileParams| async move { + let params = params.try_into_request(resolve_filesystem_sandbox)?; handler.fs_write_file(params).await }, ); router.request( FS_CREATE_DIRECTORY_METHOD, - |handler: Arc, params: FsCreateDirectoryParams| async move { + |handler: Arc, params: WireFsCreateDirectoryParams| async move { + let params = params.try_into_request(resolve_filesystem_sandbox)?; handler.fs_create_directory(params).await }, ); router.request( FS_GET_METADATA_METHOD, - |handler: Arc, params: FsGetMetadataParams| async move { + |handler: Arc, params: WireFsGetMetadataParams| async move { + let params = params.try_into_request(resolve_filesystem_sandbox)?; handler.fs_get_metadata(params).await }, ); router.request( FS_CANONICALIZE_METHOD, - |handler: Arc, params: FsCanonicalizeParams| async move { + |handler: Arc, params: WireFsCanonicalizeParams| async move { + let params = params.try_into_request(resolve_filesystem_sandbox)?; handler.fs_canonicalize(params).await }, ); router.request( FS_READ_DIRECTORY_METHOD, - |handler: Arc, params: FsReadDirectoryParams| async move { + |handler: Arc, params: WireFsReadDirectoryParams| async move { + let params = params.try_into_request(resolve_filesystem_sandbox)?; handler.fs_read_directory(params).await }, ); router.request( FS_WALK_METHOD, - |handler: Arc, params: FsWalkParams| async move { + |handler: Arc, params: WireFsWalkParams| async move { + let params = params.try_into_request(resolve_filesystem_sandbox)?; handler.fs_walk(params).await }, ); router.request( FS_REMOVE_METHOD, - |handler: Arc, params: FsRemoveParams| async move { + |handler: Arc, params: WireFsRemoveParams| async move { + let params = params.try_into_request(resolve_filesystem_sandbox)?; handler.fs_remove(params).await }, ); router.request( FS_COPY_METHOD, - |handler: Arc, params: FsCopyParams| async move { + |handler: Arc, params: WireFsCopyParams| async move { + let params = params.try_into_request(resolve_filesystem_sandbox)?; handler.fs_copy(params).await }, ); router } + +fn resolve_filesystem_sandbox( + sandbox: WireFileSystemSandboxContext, +) -> Result { + let cwd = if let Some(cwd) = sandbox.cwd() { + cwd.clone() + } else { + if sandbox.requires_cwd() { + return Err(invalid_params( + "file system sandbox context with dynamic permissions requires cwd".to_string(), + )); + } + // Legacy filesystem clients omitted cwd only for these policies. Preserve the executor's + // own default (and Windows drive/share), rather than using the requested path. + std::env::current_dir() + .and_then(|cwd| resolve_existing_path(&cwd)) + .and_then(PathUri::from_host_native_path) + .map_err(|err| internal_error(err.to_string()))? + }; + Ok(sandbox.into_context(cwd)) +} diff --git a/codex-rs/exec-server/tests/capability_discovery.rs b/codex-rs/exec-server/tests/capability_discovery.rs index 0be51f9fbb..e811bfbbe5 100644 --- a/codex-rs/exec-server/tests/capability_discovery.rs +++ b/codex-rs/exec-server/tests/capability_discovery.rs @@ -5,6 +5,8 @@ mod fake_bwrap; #[cfg(target_os = "linux")] use anyhow::Context as _; +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD; use codex_exec_server::CAPABILITY_ROOTS_DISCOVER_METHOD; use codex_exec_server::CapabilityRootDiscovery; use codex_exec_server::CapabilityRootsDiscoverParams; @@ -14,12 +16,26 @@ use codex_exec_server::InitializeParams; use codex_exec_server::InitializeResponse; use codex_exec_server::WindowsSandboxSelection; use codex_exec_server_protocol::CapabilityRootDiscoverRequest; +use codex_exec_server_protocol::EXEC_METHOD; +#[cfg(unix)] +use codex_exec_server_protocol::EXEC_READ_METHOD; +use codex_exec_server_protocol::FS_OPEN_METHOD; +#[cfg(unix)] +use codex_exec_server_protocol::FS_READ_BLOCK_METHOD; +use codex_exec_server_protocol::FS_READ_FILE_METHOD; +#[cfg(unix)] +use codex_exec_server_protocol::FsReadBlockResponse; +use codex_exec_server_protocol::FsReadFileResponse; use codex_exec_server_protocol::JSONRPCMessage; use codex_exec_server_protocol::JSONRPCResponse; +#[cfg(unix)] +use codex_exec_server_protocol::ReadResponse; use codex_protocol::models::PermissionProfile; use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; use codex_protocol::permissions::FileSystemSandboxEntry; use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::FileSystemSpecialPath; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathUri; @@ -183,6 +199,715 @@ async fn discovers_cursor_plugin_without_reading_default_mcp_for_inline_servers( Ok(()) } +#[tokio::test] +async fn executor_legacy_missing_or_null_sandbox_cwd_keeps_absolute_requests_working() +-> anyhow::Result<()> { + let workspace = tempfile::tempdir()?; + std::fs::write(workspace.path().join("note.txt"), b"contents")?; + write_file( + &workspace.path().join("skills/demo/SKILL.md"), + "---\nname: demo\ndescription: Demo.\n---\n", + )?; + let cwd = PathUri::from_host_native_path(workspace.path())?; + let path = cwd.join("note.txt")?; + let program = std::env::current_exe()?.to_string_lossy().into_owned(); + // A process with sandbox intent needs an enforceable profile and an enabled Windows backend. + let process_policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + FileSystemAccessMode::Read, + ), + FileSystemSandboxEntry::new( + FileSystemPath::Path { path: cwd.clone() }, + FileSystemAccessMode::Write, + ), + ]); + let mut process_sandbox = FileSystemSandboxContext::from_permission_profile( + PermissionProfile::from_runtime_permissions(&process_policy, NetworkSandboxPolicy::Enabled), + cwd.clone(), + ); + process_sandbox.windows_sandbox_selection = WindowsSandboxSelection::RestrictedToken; + let sandbox = + FileSystemSandboxContext::from_permission_profile(PermissionProfile::Disabled, cwd.clone()); + let requests = [ + ( + EXEC_METHOD, + serde_json::json!({ + "processId": "sandbox-cwd", "argv": [program, "--help"], "cwd": cwd, + "env": {}, "tty": false, "sandbox": process_sandbox, + }), + "/sandbox", + ), + ( + FS_READ_FILE_METHOD, + serde_json::json!({ "path": path, "sandbox": sandbox }), + "/sandbox", + ), + ( + CAPABILITY_ROOTS_DISCOVER_METHOD, + serde_json::json!({ "roots": [{ "id": "root", "path": cwd, "sandbox": sandbox }] }), + "/roots/0/sandbox", + ), + ]; + let mut server = exec_server().await?; + initialize(&mut server).await?; + + for (method, request, sandbox_pointer) in requests { + for (index, legacy_cwd) in [None, Some(serde_json::Value::Null)] + .into_iter() + .enumerate() + { + let mut request = request.clone(); + if method == EXEC_METHOD { + request["processId"] = serde_json::json!(format!("sandbox-cwd-{index}")); + } + let sandbox = request + .pointer_mut(sandbox_pointer) + .and_then(serde_json::Value::as_object_mut) + .expect("sandbox request"); + if let Some(legacy_cwd) = legacy_cwd { + sandbox.insert("cwd".to_string(), legacy_cwd); + } else { + sandbox.remove("cwd"); + } + sandbox.remove("workspaceRoots"); + let request_id = server.send_request(method, request).await?; + let response = server + .wait_for_event(|event| match event { + JSONRPCMessage::Response(response) => response.id == request_id, + JSONRPCMessage::Error(error) => error.id == request_id, + JSONRPCMessage::Request(_) | JSONRPCMessage::Notification(_) => false, + }) + .await?; + let JSONRPCMessage::Response(response) = response else { + anyhow::bail!("expected legacy {method} to succeed, got {response:?}"); + }; + if method == FS_READ_FILE_METHOD { + let read: FsReadFileResponse = serde_json::from_value(response.result)?; + assert_eq!(STANDARD.decode(read.data_base64)?, b"contents"); + } else if method == CAPABILITY_ROOTS_DISCOVER_METHOD { + let discovery: CapabilityRootsDiscoverResponse = + serde_json::from_value(response.result)?; + assert_eq!( + discovery.roots[0] + .skills + .iter() + .map(|skill| &skill.instructions.path) + .collect::>(), + vec![&cwd.join("skills/demo/SKILL.md")?], + ); + } + } + } + + server.shutdown().await?; + Ok(()) +} + +/// Old filesystem clients cannot replace the original cwd for rules whose meaning depends on it. +#[tokio::test] +async fn executor_legacy_filesystem_rejects_missing_cwd_for_dynamic_permissions() +-> anyhow::Result<()> { + let workspace = tempfile::tempdir()?; + let cwd = PathUri::from_host_native_path(workspace.path())?; + let mut server = exec_server().await?; + initialize(&mut server).await?; + + for path in [ + FileSystemPath::Special { + value: FileSystemSpecialPath::ProjectRoots { subpath: None }, + }, + FileSystemPath::GlobPattern { + pattern: "secrets/**".to_string(), + }, + ] { + let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry::new( + path, + FileSystemAccessMode::Deny, + )]); + let sandbox = FileSystemSandboxContext::from_permission_profile( + PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), + cwd.clone(), + ); + for legacy_cwd in [None, Some(serde_json::Value::Null)] { + let mut sandbox = serde_json::to_value(&sandbox)?; + let fields = sandbox.as_object_mut().expect("sandbox object"); + if let Some(legacy_cwd) = legacy_cwd { + fields.insert("cwd".to_string(), legacy_cwd); + } else { + fields.remove("cwd"); + } + fields.remove("workspaceRoots"); + for (method, request) in [ + ( + FS_READ_FILE_METHOD, + serde_json::json!({ "path": cwd, "sandbox": sandbox }), + ), + ( + FS_OPEN_METHOD, + serde_json::json!({ "handleId": "denied", "path": cwd, "sandbox": sandbox }), + ), + ( + CAPABILITY_ROOTS_DISCOVER_METHOD, + serde_json::json!({ "roots": [{ "id": "root", "path": cwd, "sandbox": sandbox }] }), + ), + ] { + let request_id = server.send_request(method, request).await?; + let response = server + .wait_for_event(|event| match event { + JSONRPCMessage::Response(response) => response.id == request_id, + JSONRPCMessage::Error(error) => error.id == request_id, + JSONRPCMessage::Request(_) | JSONRPCMessage::Notification(_) => false, + }) + .await?; + let JSONRPCMessage::Error(error) = response else { + anyhow::bail!( + "expected legacy {method} to reject dynamic permissions, got {response:?}" + ); + }; + assert_eq!( + (error.error.code, error.error.message.as_str()), + ( + -32602, + "file system sandbox context with dynamic permissions requires cwd" + ), + "{method}", + ); + } + } + } + + server.shutdown().await?; + Ok(()) +} + +/// Providing cwd lets project roots and relative rules be enforced against the original directory. +#[cfg(unix)] +#[tokio::test] +async fn executor_legacy_filesystem_accepts_cwd_for_dynamic_permissions() -> anyhow::Result<()> { + let workspace = tempfile::tempdir()?; + write_file(&workspace.path().join("allowed.txt"), "allowed")?; + write_file(&workspace.path().join("secret.txt"), "secret")?; + let cwd = PathUri::from_host_native_path(workspace.path())?; + let policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + FileSystemAccessMode::Read, + ), + FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::ProjectRoots { subpath: None }, + }, + FileSystemAccessMode::Write, + ), + FileSystemSandboxEntry::new( + FileSystemPath::GlobPattern { + pattern: "secret*".to_string(), + }, + FileSystemAccessMode::Deny, + ), + ]); + let sandbox = FileSystemSandboxContext::from_permission_profile( + PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), + cwd.clone(), + ); + let mut server = exec_server().await?; + initialize(&mut server).await?; + let request_id = server + .send_request( + FS_READ_FILE_METHOD, + serde_json::json!({"path": cwd.join("secret.txt")?}), + ) + .await?; + let response = server + .wait_for_event(|event| match event { + JSONRPCMessage::Response(response) => response.id == request_id, + JSONRPCMessage::Error(error) => error.id == request_id, + JSONRPCMessage::Request(_) | JSONRPCMessage::Notification(_) => false, + }) + .await?; + let JSONRPCMessage::Response(response) = response else { + anyhow::bail!( + "expected the denied path to be readable without a sandbox, got {response:?}" + ); + }; + let read: FsReadFileResponse = serde_json::from_value(response.result)?; + assert_eq!(STANDARD.decode(read.data_base64)?, b"secret"); + + for (name, permitted) in [("allowed.txt", true), ("secret.txt", false)] { + let request_id = server + .send_request( + FS_READ_FILE_METHOD, + serde_json::json!({ + "path": cwd.join(name)?, "sandbox": sandbox, + }), + ) + .await?; + let response = server + .wait_for_event(|event| match event { + JSONRPCMessage::Response(response) => response.id == request_id, + JSONRPCMessage::Error(error) => error.id == request_id, + JSONRPCMessage::Request(_) | JSONRPCMessage::Notification(_) => false, + }) + .await?; + match response { + JSONRPCMessage::Response(response) if permitted => { + let read: FsReadFileResponse = serde_json::from_value(response.result)?; + assert_eq!(STANDARD.decode(read.data_base64)?, b"allowed"); + } + JSONRPCMessage::Error(error) if !permitted => { + assert_eq!(error.error.code, -32600, "{error:?}"); + assert!( + matches!( + error.error.message.as_str(), + "Permission denied (os error 13)" | "Operation not permitted (os error 1)" + ), + "expected a filesystem permission denial: {error:?}" + ); + } + response => anyhow::bail!("unexpected filesystem result for {name}: {response:?}"), + } + } + server.shutdown().await?; + Ok(()) +} + +/// A present policy context can omit cwd: legacy cwd still anchors denials, and only static +/// filesystem policies can use the executor default when both cwd fields are absent. +#[tokio::test] +async fn executor_legacy_nested_policy_context_cwd_uses_available_fallbacks() -> anyhow::Result<()> +{ + let workspace = tempfile::tempdir()?; + write_file(&workspace.path().join("allowed.txt"), "allowed")?; + write_file(&workspace.path().join("secret.txt"), "secret")?; + let cwd = PathUri::from_host_native_path(workspace.path())?; + let static_permissions = if cfg!(unix) { + PermissionProfile::read_only() + } else { + // The direct Windows test fixture has no enabled platform sandbox. + PermissionProfile::Disabled + }; + let static_sandbox = + FileSystemSandboxContext::from_permission_profile(static_permissions, cwd.clone()); + let policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + FileSystemAccessMode::Read, + ), + FileSystemSandboxEntry::new( + FileSystemPath::GlobPattern { + pattern: "secret*".to_string(), + }, + FileSystemAccessMode::Deny, + ), + ]); + let dynamic_sandbox = FileSystemSandboxContext::from_permission_profile( + PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), + cwd.clone(), + ); + let mut server = exec_server().await?; + initialize(&mut server).await?; + + for (shape, policy_context) in [ + ("missing", serde_json::json!({"workspaceRoots": [cwd]})), + ( + "null", + serde_json::json!({"cwd": null, "workspaceRoots": [cwd]}), + ), + ] { + for (case, sandbox, legacy_cwd, name, expected) in [ + ( + "static allowed without legacy cwd", + &static_sandbox, + None::<&PathUri>, + "allowed.txt", + Ok(b"allowed".as_slice()), + ), + ( + "static secret without legacy cwd", + &static_sandbox, + None, + "secret.txt", + Ok(b"secret".as_slice()), + ), + ( + "dynamic without legacy cwd", + &dynamic_sandbox, + None, + "allowed.txt", + Err(-32602), + ), + // The default Windows test backend cannot enforce read denials at runtime. + #[cfg(unix)] + ( + "dynamic allowed with legacy cwd", + &dynamic_sandbox, + Some(&cwd), + "allowed.txt", + Ok(b"allowed".as_slice()), + ), + #[cfg(unix)] + ( + "dynamic secret with legacy cwd", + &dynamic_sandbox, + Some(&cwd), + "secret.txt", + Err(-32600), + ), + ] { + let mut sandbox = serde_json::to_value(sandbox)?; + let fields = sandbox.as_object_mut().expect("sandbox object"); + fields.insert("policyContext".to_string(), policy_context.clone()); + if let Some(legacy_cwd) = legacy_cwd { + fields.insert("cwd".to_string(), serde_json::to_value(legacy_cwd)?); + } else { + fields.remove("cwd"); + } + fields.remove("workspaceRoots"); + let request_id = server + .send_request( + FS_READ_FILE_METHOD, + serde_json::json!({"path": cwd.join(name)?, "sandbox": sandbox}), + ) + .await?; + let response = server + .wait_for_event(|event| match event { + JSONRPCMessage::Response(response) => response.id == request_id, + JSONRPCMessage::Error(error) => error.id == request_id, + JSONRPCMessage::Request(_) | JSONRPCMessage::Notification(_) => false, + }) + .await?; + match (response, expected) { + (JSONRPCMessage::Response(response), Ok(contents)) => { + let read: FsReadFileResponse = serde_json::from_value(response.result)?; + assert_eq!( + STANDARD.decode(read.data_base64)?, + contents, + "{shape}: {case}" + ); + } + (JSONRPCMessage::Error(error), Err(-32602)) => assert_eq!( + (error.error.code, error.error.message.as_str()), + ( + -32602, + "file system sandbox context with dynamic permissions requires cwd" + ), + "{shape}: {case}", + ), + (JSONRPCMessage::Error(error), Err(-32600)) => { + assert_eq!(error.error.code, -32600, "{shape}: {case}: {error:?}"); + assert!( + matches!( + error.error.message.as_str(), + "Permission denied (os error 13)" + | "Operation not permitted (os error 1)" + ), + "{shape}: {case}: {error:?}", + ); + } + (response, expected) => anyhow::bail!( + "unexpected {shape} nested cwd result for {case}: expected {expected:?}, got {response:?}" + ), + } + } + } + + server.shutdown().await?; + Ok(()) +} + +#[cfg(unix)] +#[tokio::test] +async fn executor_legacy_exec_uses_process_cwd_for_relative_denials() -> anyhow::Result<()> { + let workspace = tempfile::tempdir()?; + std::fs::write(workspace.path().join("allowed.txt"), b"allowed")?; + std::fs::write(workspace.path().join("secret.txt"), b"secret")?; + let cwd = PathUri::from_host_native_path(workspace.path())?; + let policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + FileSystemAccessMode::Read, + ), + FileSystemSandboxEntry::new( + FileSystemPath::GlobPattern { + pattern: "secret*".to_string(), + }, + FileSystemAccessMode::Deny, + ), + ]); + let sandbox = FileSystemSandboxContext::from_permission_profile( + PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), + cwd.clone(), + ); + let process_env = + std::collections::HashMap::from([("PATH".to_string(), std::env::var("PATH")?)]); + #[cfg(target_os = "linux")] + let process_env = { + let mut process_env = process_env; + // Bazel-provided bubblewrap lives in runfiles, not necessarily on the process PATH. + for name in [ + "CARGO_BIN_EXE_bwrap", + "RUNFILES_DIR", + "RUNFILES_MANIFEST_FILE", + "TEST_SRCDIR", + "TEST_WORKSPACE", + ] { + if let Ok(value) = std::env::var(name) { + process_env.insert(name.to_string(), value); + } + } + process_env + }; + let mut server = exec_server().await?; + initialize(&mut server).await?; + for (index, legacy_cwd) in [None, Some(serde_json::Value::Null)] + .into_iter() + .enumerate() + { + let mut sandbox = serde_json::to_value(&sandbox)?; + let fields = sandbox.as_object_mut().expect("sandbox object"); + if let Some(legacy_cwd) = legacy_cwd { + fields.insert("cwd".to_string(), legacy_cwd); + } else { + fields.remove("cwd"); + } + let process = format!("legacy-relative-{index}"); + let request_id = server.send_request(EXEC_METHOD, serde_json::json!({ + "processId": process, "argv": ["/bin/sh", "-c", "cat allowed.txt && if cat secret.txt 2>/dev/null; then exit 9; fi"], "cwd": cwd, + "env": process_env, "tty": false, "sandbox": sandbox, + })).await?; + let start = server + .wait_for_event(|event| match event { + JSONRPCMessage::Response(response) => response.id == request_id, + JSONRPCMessage::Error(error) => error.id == request_id, + JSONRPCMessage::Request(_) | JSONRPCMessage::Notification(_) => false, + }) + .await?; + if !matches!(start, JSONRPCMessage::Response(_)) { + anyhow::bail!("expected legacy process to start, got {start:?}"); + } + let mut after_seq = None; + let mut output = Vec::new(); + let (exit_code, failure, sandbox_denied) = loop { + let request_id = server + .send_request( + EXEC_READ_METHOD, + serde_json::json!({ + "processId": process, "afterSeq": after_seq, "waitMs": 1000, + }), + ) + .await?; + let response = server + .wait_for_event(|event| match event { + JSONRPCMessage::Response(response) => response.id == request_id, + JSONRPCMessage::Error(error) => error.id == request_id, + JSONRPCMessage::Request(_) | JSONRPCMessage::Notification(_) => false, + }) + .await?; + let JSONRPCMessage::Response(response) = response else { + anyhow::bail!("expected legacy process output, got {response:?}"); + }; + let response: ReadResponse = serde_json::from_value(response.result)?; + output.extend(response.chunks.into_iter().flat_map(|chunk| chunk.chunk.0)); + after_seq = response.next_seq.checked_sub(1).or(after_seq); + if response.closed { + break ( + response.exit_code, + response.failure, + response.sandbox_denied, + ); + } + }; + assert_eq!( + (exit_code, String::from_utf8(output)?), + (Some(0), "allowed".to_string()), + "legacy process failed: {failure:?}; sandbox denied: {sandbox_denied}" + ); + } + server.shutdown().await?; + Ok(()) +} + +#[cfg(unix)] +#[tokio::test] +async fn executor_legacy_filesystem_cwd_keeps_absolute_read_allow_and_deny_rules() +-> anyhow::Result<()> { + let workspace = tempfile::tempdir()?; + let allowed = workspace.path().join("allowed"); + let denied = workspace.path().join("denied"); + for (root, name) in [(&allowed, "allowed"), (&denied, "denied")] { + write_file(&root.join("note.txt"), "contents")?; + write_file( + &root.join(format!("skills/{name}/SKILL.md")), + &format!("---\nname: {name}\ndescription: {name}.\n---\n"), + )?; + } + let allowed = PathUri::from_host_native_path(allowed)?; + let denied = PathUri::from_host_native_path(denied)?; + let policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + FileSystemAccessMode::Read, + ), + FileSystemSandboxEntry::new( + FileSystemPath::Path { + path: denied.clone(), + }, + FileSystemAccessMode::Deny, + ), + ]); + let sandbox = FileSystemSandboxContext::from_permission_profile( + PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), + PathUri::from_host_native_path(workspace.path())?, + ); + let mut server = exec_server().await?; + initialize(&mut server).await?; + + let request_id = server + .send_request( + FS_READ_FILE_METHOD, + serde_json::json!({"path": denied.join("note.txt")?}), + ) + .await?; + let response = server + .wait_for_event(|event| match event { + JSONRPCMessage::Response(response) => response.id == request_id, + JSONRPCMessage::Error(error) => error.id == request_id, + JSONRPCMessage::Request(_) | JSONRPCMessage::Notification(_) => false, + }) + .await?; + let JSONRPCMessage::Response(response) = response else { + anyhow::bail!( + "expected the denied path to be readable without a sandbox, got {response:?}" + ); + }; + let read: FsReadFileResponse = serde_json::from_value(response.result)?; + assert_eq!(STANDARD.decode(read.data_base64)?, b"contents"); + + for (index, legacy_cwd) in [None, Some(serde_json::Value::Null)] + .into_iter() + .enumerate() + { + let mut sandbox = serde_json::to_value(&sandbox)?; + let fields = sandbox.as_object_mut().expect("sandbox object"); + if let Some(legacy_cwd) = legacy_cwd { + fields.insert("cwd".to_string(), legacy_cwd); + } else { + fields.remove("cwd"); + } + fields.remove("workspaceRoots"); + for (root, permitted) in [(&allowed, true), (&denied, false)] { + let handle = format!("legacy-{index}-{permitted}"); + for (method, request) in [ + ( + FS_READ_FILE_METHOD, + serde_json::json!({ "path": root.join("note.txt")?, "sandbox": sandbox }), + ), + ( + FS_OPEN_METHOD, + serde_json::json!({ "handleId": handle, "path": root.join("note.txt")?, "sandbox": sandbox }), + ), + ] { + let request_id = server.send_request(method, request).await?; + let response = server + .wait_for_event(|event| match event { + JSONRPCMessage::Response(response) => response.id == request_id, + JSONRPCMessage::Error(error) => error.id == request_id, + JSONRPCMessage::Request(_) | JSONRPCMessage::Notification(_) => false, + }) + .await?; + match response { + JSONRPCMessage::Response(response) if permitted => { + if method == FS_READ_FILE_METHOD { + let read: FsReadFileResponse = serde_json::from_value(response.result)?; + assert_eq!(STANDARD.decode(read.data_base64)?, b"contents"); + } else { + let request_id = server.send_request(FS_READ_BLOCK_METHOD, serde_json::json!({ "handleId": handle, "offset": 0, "len": 16 })).await?; + let block = server + .wait_for_event(|event| match event { + JSONRPCMessage::Response(response) => response.id == request_id, + JSONRPCMessage::Error(error) => error.id == request_id, + JSONRPCMessage::Request(_) + | JSONRPCMessage::Notification(_) => false, + }) + .await?; + let JSONRPCMessage::Response(block) = block else { + anyhow::bail!("expected to read the legacy stream, got {block:?}"); + }; + let block: FsReadBlockResponse = serde_json::from_value(block.result)?; + assert_eq!(block.chunk.0, b"contents"); + } + } + JSONRPCMessage::Error(error) if !permitted => { + assert_eq!(error.error.code, -32600, "{method}: {error:?}"); + assert!( + matches!( + error.error.message.as_str(), + "Permission denied (os error 13)" + | "Operation not permitted (os error 1)" + ), + "expected a filesystem permission denial for {method}: {error:?}" + ); + } + response => { + anyhow::bail!("unexpected legacy {method} result for {root}: {response:?}") + } + } + } + } + let request_id = server + .send_request( + CAPABILITY_ROOTS_DISCOVER_METHOD, + serde_json::json!({ "roots": [ + { "id": "allowed", "path": allowed, "sandbox": sandbox }, + { "id": "denied", "path": denied, "sandbox": sandbox }, + ] }), + ) + .await?; + let discovery = server + .wait_for_event(|event| match event { + JSONRPCMessage::Response(response) => response.id == request_id, + JSONRPCMessage::Error(error) => error.id == request_id, + JSONRPCMessage::Request(_) | JSONRPCMessage::Notification(_) => false, + }) + .await?; + let JSONRPCMessage::Response(discovery) = discovery else { + anyhow::bail!("expected legacy capability discovery, got {discovery:?}"); + }; + let discovery: CapabilityRootsDiscoverResponse = serde_json::from_value(discovery.result)?; + assert_eq!( + discovery + .roots + .iter() + .map(|root| ( + root.id.as_str(), + root.skills + .iter() + .map(|skill| &skill.instructions.path) + .collect::>() + )) + .collect::>(), + vec![ + ("allowed", vec![&allowed.join("skills/allowed/SKILL.md")?]), + ("denied", vec![]), + ] + ); + } + + server.shutdown().await?; + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn sandboxed_discovery_batches_roots_without_combining_different_permissions() -> anyhow::Result<()> { @@ -208,7 +933,7 @@ async fn sandboxed_discovery_batches_roots_without_combining_different_permissio FileSystemAccessMode::Read, ); let policy = FileSystemSandboxPolicy::restricted(vec![read_workspace]); - let shared_sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let shared_sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), workspace_uri, ); @@ -328,7 +1053,7 @@ async fn sandboxed_discovery_batches_roots_without_combining_different_permissio FileSystemAccessMode::Read, ); let first_policy = FileSystemSandboxPolicy::restricted(vec![read_first_root]); - let first_only_sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let first_only_sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions( &first_policy, NetworkSandboxPolicy::Restricted, @@ -341,7 +1066,7 @@ async fn sandboxed_discovery_batches_roots_without_combining_different_permissio FileSystemAccessMode::Read, ); let second_policy = FileSystemSandboxPolicy::restricted(vec![read_second_root]); - let second_only_sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let second_only_sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions( &second_policy, NetworkSandboxPolicy::Restricted, @@ -441,7 +1166,7 @@ async fn sandboxed_discovery_follows_only_permitted_external_symlinks() -> anyho for (scenario, entries, has_skill, has_mcp) in cases { let policy = FileSystemSandboxPolicy::restricted(entries); - let sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), root_uri.clone(), ); diff --git a/codex-rs/exec-server/tests/exec_process.rs b/codex-rs/exec-server/tests/exec_process.rs index b4e861d50b..095cbe25e1 100644 --- a/codex-rs/exec-server/tests/exec_process.rs +++ b/codex-rs/exec-server/tests/exec_process.rs @@ -140,7 +140,7 @@ async fn codex_home_symlink_opt_out_respects_host_config_and_scope() -> Result<( PathUri::from_host_native_path(root)?.into(), FileSystemAccessMode::Write, )); - let sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions( &policy, NetworkSandboxPolicy::Restricted, @@ -345,7 +345,7 @@ async fn shell_snapshot_v2_filters_profile_exports_and_stays_in_memory( pipe_stdin: false, arg0: (shell_name == "bash-sh").then(|| "sh".to_string()), sandbox: (use_sandbox && attempt == 0).then(|| { - FileSystemSandboxContext::from_permission_profile_with_cwd( + FileSystemSandboxContext::from_permission_profile( PermissionProfile::read_only(), cwd.clone(), ) @@ -522,7 +522,7 @@ async fn shell_snapshot_v2_capture_failure_falls_back_and_retries( pipe_stdin: false, arg0: None, sandbox: use_remote.then(|| { - FileSystemSandboxContext::from_permission_profile_with_cwd( + FileSystemSandboxContext::from_permission_profile( PermissionProfile::workspace_write(), cwd, ) @@ -603,7 +603,7 @@ async fn remote_sandboxed_process_preserves_custom_arg0() -> Result<()> { missing_path_behavior: None, }, ]); - let sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), cwd.clone(), ); @@ -706,7 +706,7 @@ async fn remote_process_keeps_sandbox_helper_visible_with_restricted_reads() -> missing_path_behavior: None, }, ]); - let sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), cwd.clone(), ); @@ -777,7 +777,7 @@ async fn remote_tty_process_uses_configured_sandbox_helper_with_hostile_path() - missing_path_behavior: None, }, ]); - let sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), cwd.clone(), ); @@ -833,7 +833,7 @@ async fn remote_process_preserves_empty_workspace_roots() -> Result<()> { access: FileSystemAccessMode::Read, missing_path_behavior: None, }]); - let mut sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let mut sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), cwd.clone(), ); diff --git a/codex-rs/exec-server/tests/exec_process/windows_sandbox.rs b/codex-rs/exec-server/tests/exec_process/windows_sandbox.rs index f7e725ff9e..d001687a93 100644 --- a/codex-rs/exec-server/tests/exec_process/windows_sandbox.rs +++ b/codex-rs/exec-server/tests/exec_process/windows_sandbox.rs @@ -46,7 +46,7 @@ async fn mxc_tmpdir_uses_command_environment_over_rpc() -> Result<()> { FileSystemAccessMode::Write, ), ]); - let mut sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let mut sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted), cwd.clone(), ); diff --git a/codex-rs/exec-server/tests/file_stream.rs b/codex-rs/exec-server/tests/file_stream.rs index 9fd3201eeb..5de1b56991 100644 --- a/codex-rs/exec-server/tests/file_stream.rs +++ b/codex-rs/exec-server/tests/file_stream.rs @@ -373,12 +373,14 @@ fn read_only_sandbox(path: std::path::PathBuf) -> codex_exec_server::FileSystemS let path = AbsolutePathBuf::from_absolute_path(&path) .unwrap_or_else(|err| panic!("sandbox path should be absolute: {err}")); - FileSystemSandboxContext::from_permission_profile(PermissionProfile::from_runtime_permissions( + let cwd = PathUri::from_abs_path(&path); + let permissions = PermissionProfile::from_runtime_permissions( &FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry { path: path.into(), access: FileSystemAccessMode::Read, missing_path_behavior: None, }]), NetworkSandboxPolicy::Restricted, - )) + ); + FileSystemSandboxContext::from_permission_profile(permissions, cwd) } diff --git a/codex-rs/exec-server/tests/file_system/shared.rs b/codex-rs/exec-server/tests/file_system/shared.rs index 96dfa14349..928d65cd7a 100644 --- a/codex-rs/exec-server/tests/file_system/shared.rs +++ b/codex-rs/exec-server/tests/file_system/shared.rs @@ -48,8 +48,7 @@ fn sandbox_context_from_profile_preserves_workspace_write_read_only_subpaths() - std::fs::create_dir_all(&git_dir)?; let sandbox = workspace_write_sandbox(writable_dir.clone()); - let permissions: PermissionProfile = sandbox.permissions.try_into()?; - let policy = permissions.file_system_sandbox_policy(); + let policy = sandbox.permissions.file_system_sandbox_policy(); let cwd = absolute_path(writable_dir.clone()); let writable_roots = policy.get_writable_roots_with_cwd(cwd.as_path()); let writable_dir = absolute_path(std::fs::canonicalize(writable_dir)?); @@ -1080,21 +1079,20 @@ async fn file_system_sandboxed_write_allows_additional_write_root( Some(vec![absolute_path(writable_dir)]), )), }; - let native_permissions: PermissionProfile = sandbox.permissions.clone().try_into()?; + let permissions = &sandbox.permissions; let file_system_policy = effective_file_system_sandbox_policy( - &native_permissions.file_system_sandbox_policy(), + &permissions.file_system_sandbox_policy(), Some(&additional_permissions), ); let network_policy = effective_network_sandbox_policy( - native_permissions.network_sandbox_policy(), + permissions.network_sandbox_policy(), Some(&additional_permissions), ); sandbox.permissions = PermissionProfile::from_runtime_permissions_with_enforcement( - native_permissions.enforcement(), + permissions.enforcement(), &file_system_policy, network_policy, - ) - .into(); + ); file_system .write_file( diff --git a/codex-rs/exec-server/tests/file_system/support.rs b/codex-rs/exec-server/tests/file_system/support.rs index 34125c24ae..4db701d29e 100644 --- a/codex-rs/exec-server/tests/file_system/support.rs +++ b/codex-rs/exec-server/tests/file_system/support.rs @@ -16,7 +16,6 @@ use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::FileSystemSpecialPath; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_utils_absolute_path::AbsolutePathBuf; -#[cfg(windows)] use codex_utils_path_uri::PathUri; use crate::common::exec_server::ExecServerHarness; @@ -93,13 +92,15 @@ pub(crate) fn absolute_path(path: std::path::PathBuf) -> AbsolutePathBuf { pub(crate) fn read_only_sandbox(readable_root: std::path::PathBuf) -> FileSystemSandboxContext { let readable_root = absolute_path(readable_root); - sandbox_context(vec![FileSystemSandboxEntry { + let cwd = PathUri::from_abs_path(&readable_root); + let entries = vec![FileSystemSandboxEntry { path: FileSystemPath::Path { path: readable_root.into(), }, access: FileSystemAccessMode::Read, missing_path_behavior: None, - }]) + }]; + sandbox_context(entries, cwd) } #[cfg(not(windows))] @@ -107,13 +108,15 @@ pub(crate) fn workspace_write_sandbox( writable_root: std::path::PathBuf, ) -> FileSystemSandboxContext { let writable_root = absolute_path(writable_root); - sandbox_context(vec![FileSystemSandboxEntry { + let cwd = PathUri::from_abs_path(&writable_root); + let entries = vec![FileSystemSandboxEntry { path: FileSystemPath::Path { path: writable_root.into(), }, access: FileSystemAccessMode::Write, missing_path_behavior: None, - }]) + }]; + sandbox_context(entries, cwd) } #[cfg(windows)] @@ -137,7 +140,7 @@ pub(crate) fn workspace_write_sandbox( FileSystemAccessMode::Write, ), ]); - let mut sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let mut sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), PathUri::from_abs_path(&writable_root), ); @@ -145,7 +148,10 @@ pub(crate) fn workspace_write_sandbox( sandbox } -fn sandbox_context(mut entries: Vec) -> FileSystemSandboxContext { +fn sandbox_context( + mut entries: Vec, + cwd: PathUri, +) -> FileSystemSandboxContext { if cfg!(windows) { // Restricted-token sandboxing cannot enforce read restrictions, so leave the root // readable while exercising the requested write restrictions. @@ -161,6 +167,7 @@ fn sandbox_context(mut entries: Vec) -> FileSystemSandbo &FileSystemSandboxPolicy::restricted(entries), NetworkSandboxPolicy::Restricted, ), + cwd, ); if cfg!(windows) { sandbox.windows_sandbox_selection = WindowsSandboxSelection::RestrictedToken; diff --git a/codex-rs/exec-server/tests/file_system_unix.rs b/codex-rs/exec-server/tests/file_system_unix.rs index 4b5615611f..6e45cd2dfc 100644 --- a/codex-rs/exec-server/tests/file_system_unix.rs +++ b/codex-rs/exec-server/tests/file_system_unix.rs @@ -588,7 +588,7 @@ async fn remote_read_file_materializes_environment_workspace_roots() -> Result<( access: FileSystemAccessMode::Read, missing_path_behavior: None, }]); - let mut sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let mut sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), PathUri::from_host_native_path(tmp.path())?, ); @@ -632,7 +632,7 @@ async fn remote_read_file_preserves_empty_workspace_roots() -> Result<()> { access: FileSystemAccessMode::Read, missing_path_behavior: None, }]); - let mut sandbox = FileSystemSandboxContext::from_permission_profile_with_cwd( + let mut sandbox = FileSystemSandboxContext::from_permission_profile( PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), PathUri::from_host_native_path(tmp.path())?, ); diff --git a/codex-rs/exec-server/tests/file_system_windows.rs b/codex-rs/exec-server/tests/file_system_windows.rs index 7fe9df0f8e..7bc41bfe7c 100644 --- a/codex-rs/exec-server/tests/file_system_windows.rs +++ b/codex-rs/exec-server/tests/file_system_windows.rs @@ -14,6 +14,7 @@ use std::path::Path; use std::process::Command; use std::time::Duration; +use anyhow::Context as _; use anyhow::Result; use codex_exec_server::CreateDirectoryOptions; use codex_exec_server::FileSystemSandboxContext; @@ -22,6 +23,13 @@ use codex_exec_server::ReadFileOptions; use codex_exec_server::RemoveOptions; use codex_exec_server::WindowsSandboxSelection; use codex_exec_server::WriteFileOptions; +use codex_protocol::models::PermissionProfile; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::FileSystemSpecialPath; +use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::SandboxPolicy; use codex_sandboxing::SandboxType; use codex_utils_path_uri::PathUri; @@ -430,6 +438,118 @@ async fn file_system_remote_fs_helper_respects_windows_sandbox_write_policy( Ok(()) } +/// An elevated filesystem helper must enforce relative deny globs from the policy cwd. +#[test_case(FileSystemImplementation::Local ; "local")] +#[test_case(FileSystemImplementation::Remote ; "remote")] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[serial_test::serial(remote_exec_server)] +async fn file_system_elevated_relative_read_denial_uses_policy_cwd( + implementation: FileSystemImplementation, +) -> Result<()> { + // Both implementations re-enter this test binary; the elevated backend finds its helpers + // next to that binary, while Cargo and Bazel provide them separately. + let test_exe = std::env::current_exe()?; + let resources = test_exe + .parent() + .context("Windows test executable should have a parent directory")? + .join("codex-resources"); + if let Err(error) = std::fs::create_dir_all(&resources) + && !(error.kind() == std::io::ErrorKind::PermissionDenied && resources.is_dir()) + { + return Err(error).context("create Windows sandbox test resources"); + } + for name in ["codex-windows-sandbox-setup", "codex-command-runner"] { + let source = codex_utils_cargo_bin::cargo_bin(name)?; + let destination = resources.join(Path::new(name).with_extension("exe")); + if let Err(error) = std::fs::copy(&source, &destination) + && !(error.kind() == std::io::ErrorKind::PermissionDenied && destination.is_file()) + { + return Err(error).with_context(|| format!("stage Windows sandbox helper {name}")); + } + } + let context = create_file_system_context(implementation).await?; + let tmp = tempfile::TempDir::new()?; + let policy_cwd = tmp.path().join("checkout"); + let selected_files = policy_cwd.join("files"); + let other_files = tmp.path().join("files"); + std::fs::create_dir_all(&selected_files)?; + std::fs::create_dir(&other_files)?; + let allowed_neighbor = selected_files.join("allowed.txt"); + let denied = selected_files.join("blocked.env"); + let same_name_outside = other_files.join("blocked.env"); + std::fs::write(&allowed_neighbor, b"allowed neighbor")?; + std::fs::write(&denied, b"denied")?; + std::fs::write(&same_name_outside, b"allowed outside")?; + + let cwd = PathUri::from_host_native_path(&policy_cwd)?; + let policy = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + FileSystemAccessMode::Read, + ), + FileSystemSandboxEntry::new( + FileSystemPath::Path { + path: PathUri::from_host_native_path(tmp.path())?, + }, + FileSystemAccessMode::Write, + ), + FileSystemSandboxEntry::new( + FileSystemPath::GlobPattern { + pattern: "files/*.env".to_string(), + }, + FileSystemAccessMode::Deny, + ), + ]); + let mut sandbox = FileSystemSandboxContext::from_permission_profile( + PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted), + cwd, + ); + sandbox.windows_sandbox_selection = WindowsSandboxSelection::Elevated; + + let file_system = &context.file_system; + let allowed_neighbor = file_system + .read_file( + &PathUri::from_host_native_path(&allowed_neighbor)?, + ReadFileOptions::default(), + Some(&sandbox), + ) + .await?; + let same_name_outside = file_system + .read_file( + &PathUri::from_host_native_path(&same_name_outside)?, + ReadFileOptions::default(), + Some(&sandbox), + ) + .await?; + let denied = file_system + .read_file( + &PathUri::from_host_native_path(&denied)?, + ReadFileOptions::default(), + Some(&sandbox), + ) + .await + .expect_err("read matching the policy-cwd denial must be rejected"); + assert_eq!( + ( + allowed_neighbor.as_slice(), + same_name_outside.as_slice(), + denied.kind(), + ), + ( + b"allowed neighbor".as_slice(), + b"allowed outside".as_slice(), + std::io::ErrorKind::InvalidInput, + ) + ); + assert!( + denied.to_string().contains("Access is denied"), + "expected Windows access denial, got: {denied}" + ); + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn file_system_private_desktop_survives_helper_exits_and_separates_permissions() -> Result<()> { diff --git a/codex-rs/ext/skills/tests/executor_file_system_authority.rs b/codex-rs/ext/skills/tests/executor_file_system_authority.rs index 1f0f0e6ae6..ffdedc6e2f 100644 --- a/codex-rs/ext/skills/tests/executor_file_system_authority.rs +++ b/codex-rs/ext/skills/tests/executor_file_system_authority.rs @@ -312,6 +312,7 @@ async fn windows_executor_skill_read_requires_a_requested_sandbox() { &FileSystemSandboxPolicy::restricted(Vec::new()), NetworkSandboxPolicy::Restricted, ), + PathUri::parse("file:///C:/skill").expect("Windows resource cwd"), ); let resource = SkillResourceId::environment( "skill://windows-root/C:/skill/SKILL.md", @@ -978,7 +979,10 @@ async fn high_level_discovery_cache_separates_filesystem_permission_contexts() { .expect("update executor skill"); let sandbox_contexts = HashMap::from([( "local".to_string(), - FileSystemSandboxContext::from_permission_profile(PermissionProfile::Disabled), + FileSystemSandboxContext::from_permission_profile( + PermissionProfile::Disabled, + PathUri::from_host_native_path(&test_root).expect("skill root URI"), + ), )]); let second_snapshot = cache.snapshot(&executor_roots, &sandbox_contexts).await; let second_discovery = second_snapshot.roots()[0] diff --git a/codex-rs/file-system/src/exec_permission_profile_serde.rs b/codex-rs/file-system/src/exec_permission_profile_serde.rs new file mode 100644 index 0000000000..f0f29896b3 --- /dev/null +++ b/codex-rs/file-system/src/exec_permission_profile_serde.rs @@ -0,0 +1,22 @@ +//! Uses executor file URIs for sandbox permissions instead of the profile's legacy native paths. + +use crate::ExecPermissionProfile; +use codex_protocol::models::PermissionProfile; +use serde::Deserialize; +use serde::Deserializer; +use serde::Serialize; +use serde::Serializer; + +pub(crate) fn serialize(value: &PermissionProfile, serializer: S) -> Result +where + S: Serializer, +{ + ExecPermissionProfile::from(value.clone()).serialize(serializer) +} + +pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + ExecPermissionProfile::deserialize(deserializer).map(PermissionProfile::from) +} diff --git a/codex-rs/file-system/src/lib.rs b/codex-rs/file-system/src/lib.rs index ba825c5ce8..0abe9dba3d 100644 --- a/codex-rs/file-system/src/lib.rs +++ b/codex-rs/file-system/src/lib.rs @@ -1,3 +1,4 @@ +mod exec_permission_profile_serde; mod find_up; use bytes::Bytes; @@ -16,6 +17,7 @@ use codex_protocol::permissions::FileSystemSandboxPolicyContext; use codex_protocol::permissions::FileSystemSpecialPath; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::protocol::SandboxPolicy; +use codex_utils_path_uri::LegacyAppPathString; use codex_utils_path_uri::PathUri; pub use find_up::FindUpErrorPolicy; pub use find_up::find_nearest_ancestor_with_markers; @@ -187,18 +189,13 @@ impl From for ExecFileSystemPath { } } -impl TryFrom for FileSystemPath { - type Error = io::Error; - - fn try_from(value: ExecFileSystemPath) -> Result { - Ok(match value { - ExecFileSystemPath::Path { path } => { - path.to_abs_path()?; - Self::Path { path } - } +impl From for FileSystemPath { + fn from(value: ExecFileSystemPath) -> Self { + match value { + ExecFileSystemPath::Path { path } => Self::Path { path }, ExecFileSystemPath::GlobPattern { pattern } => Self::GlobPattern { pattern }, ExecFileSystemPath::Special { value } => Self::Special { value }, - }) + } } } @@ -220,15 +217,13 @@ impl From for ExecFileSystemSandboxEntry { } } -impl TryFrom for FileSystemSandboxEntry { - type Error = io::Error; - - fn try_from(value: ExecFileSystemSandboxEntry) -> Result { - Ok(Self { - path: value.path.try_into()?, +impl From for FileSystemSandboxEntry { + fn from(value: ExecFileSystemSandboxEntry) -> Self { + Self { + path: value.path.into(), access: value.access, missing_path_behavior: value.missing_path_behavior, - }) + } } } @@ -258,26 +253,22 @@ impl From for ExecManagedFileSystemPermissions { } } -impl TryFrom for ManagedFileSystemPermissions { - type Error = io::Error; - - fn try_from(value: ExecManagedFileSystemPermissions) -> Result { - Ok(match value { +impl From for ManagedFileSystemPermissions { + fn from(value: ExecManagedFileSystemPermissions) -> Self { + match value { ExecManagedFileSystemPermissions::Restricted { entries, glob_scan_max_depth, } => Self::Restricted { - entries: entries - .into_iter() - .map(TryInto::try_into) - .collect::>()?, + entries: entries.into_iter().map(Into::into).collect(), glob_scan_max_depth, }, ExecManagedFileSystemPermissions::Unrestricted => Self::Unrestricted, - }) + } } } +/// Executor permission profile whose explicit filesystem paths serialize as file URIs. #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum ExecPermissionProfile { @@ -307,21 +298,19 @@ impl From for ExecPermissionProfile { } } -impl TryFrom for PermissionProfile { - type Error = io::Error; - - fn try_from(value: ExecPermissionProfile) -> Result { - Ok(match value { +impl From for PermissionProfile { + fn from(value: ExecPermissionProfile) -> Self { + match value { ExecPermissionProfile::Managed { file_system, network, } => Self::Managed { - file_system: file_system.try_into()?, + file_system: file_system.into(), network, }, ExecPermissionProfile::Disabled => Self::Disabled, ExecPermissionProfile::External { network } => Self::External { network }, - }) + } } } @@ -349,12 +338,16 @@ impl From for WindowsSandboxSelection { } } +/// Filesystem sandbox policy and the selected executor paths needed to interpret it. #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FileSystemSandboxContext { - pub permissions: ExecPermissionProfile, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub cwd: Option, + /// Serializes paths as executor file URIs instead of the profile's default native paths. + #[serde(with = "exec_permission_profile_serde")] + pub permissions: PermissionProfile, + /// Working directory on the selected executor used to interpret sandbox permissions. + /// Required even for absolute permissions; a process may use a different working directory. + pub cwd: PathUri, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub workspace_roots: Vec, /// Executor-local user home used to resolve home-relative policy paths. @@ -391,23 +384,14 @@ impl FileSystemSandboxContext { &file_system_sandbox_policy, NetworkSandboxPolicy::from(&sandbox_policy), ); - Ok(Self::from_permission_profile_with_cwd(permissions, cwd)) + Ok(Self::from_permission_profile(permissions, cwd)) } - pub fn from_permission_profile(permissions: PermissionProfile) -> Self { - Self::from_permissions_and_cwd(permissions, /*cwd*/ None) - } - - pub fn from_permission_profile_with_cwd(permissions: PermissionProfile, cwd: PathUri) -> Self { - Self::from_permissions_and_cwd(permissions, Some(cwd)) - } - - fn from_permissions_and_cwd(permissions: PermissionProfile, cwd: Option) -> Self { - let workspace_roots = cwd.iter().cloned().collect(); + pub fn from_permission_profile(permissions: PermissionProfile, cwd: PathUri) -> Self { Self { - permissions: permissions.into(), + permissions, + workspace_roots: vec![cwd.clone()], cwd, - workspace_roots, user_home_dir: None, temporary_directories: None, windows_sandbox_selection: WindowsSandboxSelection::Disabled, @@ -418,11 +402,11 @@ impl FileSystemSandboxContext { } pub fn should_run_in_sandbox(&self) -> bool { - let Ok(permissions) = PermissionProfile::try_from(self.permissions.clone()) else { + if self.validate_file_system_paths_for_current_host().is_err() { // A sandbox context for another host must not select the unsandboxed filesystem. return true; - }; - let file_system_policy = permissions.file_system_sandbox_policy(); + } + let file_system_policy = self.permissions.file_system_sandbox_policy(); matches!(file_system_policy.kind, FileSystemSandboxKind::Restricted) && !file_system_policy.has_full_disk_write_access() } @@ -432,25 +416,101 @@ impl FileSystemSandboxContext { self.windows_sandbox_selection != WindowsSandboxSelection::Disabled } + /// Checks that explicit permission paths can be enforced by the current host. An + /// orchestrator can still construct this context with paths belonging to another executor. + pub fn validate_file_system_paths_for_current_host(&self) -> io::Result<()> { + if let PermissionProfile::Managed { + file_system: ManagedFileSystemPermissions::Restricted { entries, .. }, + .. + } = &self.permissions + { + for entry in entries { + if let FileSystemPath::Path { path } = &entry.path { + path.to_abs_path().map_err(|error| { + io::Error::new( + error.kind(), + format!("invalid sandbox permission path URI: {error}"), + ) + })?; + } + } + } + Ok(()) + } + /// Borrows the executor-owned paths needed to interpret filesystem policy entries. - /// - /// Returns `None` after the cwd has been omitted from a transport context. - pub fn policy_context(&self) -> Option> { - Some(FileSystemSandboxPolicyContext { - cwd: self.cwd.as_ref()?, + pub fn policy_context(&self) -> FileSystemSandboxPolicyContext<'_> { + FileSystemSandboxPolicyContext { + cwd: &self.cwd, workspace_roots: &self.workspace_roots, user_home_dir: self.user_home_dir.as_ref(), temporary_directories: self.temporary_directories.as_deref(), - }) + } } +} - pub fn has_cwd_dependent_permissions(&self) -> bool { - match &self.permissions { +/// Filesystem RPC wire context; older clients can omit the policy cwd before executor resolution. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WireFileSystemSandboxContext { + permissions: ExecPermissionProfile, + #[serde(default, skip_serializing_if = "Option::is_none")] + cwd: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + policy_context: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + workspace_roots: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + user_home_dir: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + temporary_directories: Option>, + #[serde(rename = "windowsSandboxLevel")] + windows_sandbox_selection: WindowsSandboxSelection, + #[serde(default)] + windows_sandbox_private_desktop: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + windows_sandbox_proxy_settings_mode: Option, + #[serde(default)] + use_legacy_landlock: bool, +} + +/// New filesystem clients provide these paths independently of the legacy helper launch cwd. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct WireFileSystemPolicyContext { + #[serde(default, skip_serializing_if = "Option::is_none")] + cwd: Option, + #[serde(default)] + workspace_roots: Vec, +} + +impl From for WireFileSystemSandboxContext { + fn from(sandbox: FileSystemSandboxContext) -> Self { + let FileSystemSandboxContext { + permissions, + cwd, + workspace_roots, + user_home_dir, + temporary_directories, + windows_sandbox_selection, + windows_sandbox_private_desktop, + windows_sandbox_proxy_settings_mode, + use_legacy_landlock, + } = sandbox; + let permissions = ExecPermissionProfile::from(permissions); + // Older filesystem clients sent cwd and roots only when permissions needed them; old + // executors also use that cwd to launch their helper. The explicit context is independent. + let legacy_needs_cwd = match &permissions { ExecPermissionProfile::Managed { file_system: ExecManagedFileSystemPermissions::Restricted { entries, .. }, .. } => entries.iter().any(|entry| match &entry.path { - ExecFileSystemPath::GlobPattern { pattern } => !Path::new(pattern).is_absolute(), + ExecFileSystemPath::GlobPattern { pattern } => match cwd.infer_path_convention() { + Some(convention) => LegacyAppPathString::from_string(pattern) + .to_path_uri(convention) + .is_err(), + None => true, + }, ExecFileSystemPath::Special { value: FileSystemSpecialPath::ProjectRoots { .. }, } => true, @@ -462,15 +522,73 @@ impl FileSystemSandboxContext { } | ExecPermissionProfile::Disabled | ExecPermissionProfile::External { .. } => false, + }; + Self { + permissions, + cwd: legacy_needs_cwd.then(|| cwd.clone()), + workspace_roots: if legacy_needs_cwd { + workspace_roots.clone() + } else { + Vec::new() + }, + policy_context: Some(WireFileSystemPolicyContext { + cwd: Some(cwd), + workspace_roots, + }), + user_home_dir, + temporary_directories, + windows_sandbox_selection, + windows_sandbox_private_desktop, + windows_sandbox_proxy_settings_mode, + use_legacy_landlock, + } + } +} + +impl WireFileSystemSandboxContext { + /// Returns the policy cwd supplied by the client, falling back to the legacy cwd field. + pub fn cwd(&self) -> Option<&PathUri> { + match &self.policy_context { + Some(policy_context) => policy_context.cwd.as_ref().or(self.cwd.as_ref()), + None => self.cwd.as_ref(), } } - pub fn drop_cwd_if_unused(mut self) -> Self { - if !self.has_cwd_dependent_permissions() { - self.cwd = None; - self.workspace_roots.clear(); + /// Returns whether a legacy filesystem policy needs the client's cwd to be interpreted. + pub fn requires_cwd(&self) -> bool { + let ExecPermissionProfile::Managed { + file_system: ExecManagedFileSystemPermissions::Restricted { entries, .. }, + .. + } = &self.permissions + else { + return false; + }; + + entries.iter().any(|entry| match &entry.path { + ExecFileSystemPath::GlobPattern { pattern } => !Path::new(pattern).is_absolute(), + ExecFileSystemPath::Special { + value: FileSystemSpecialPath::ProjectRoots { .. }, + } => true, + ExecFileSystemPath::Path { .. } | ExecFileSystemPath::Special { .. } => false, + }) + } + + /// Constructs the strict context after executor ingress has resolved the policy cwd. + pub fn into_context(self, cwd: PathUri) -> FileSystemSandboxContext { + FileSystemSandboxContext { + permissions: self.permissions.into(), + cwd, + workspace_roots: match self.policy_context { + Some(policy_context) => policy_context.workspace_roots, + None => self.workspace_roots, + }, + user_home_dir: self.user_home_dir, + temporary_directories: self.temporary_directories, + windows_sandbox_selection: self.windows_sandbox_selection, + windows_sandbox_private_desktop: self.windows_sandbox_private_desktop, + windows_sandbox_proxy_settings_mode: self.windows_sandbox_proxy_settings_mode, + use_legacy_landlock: self.use_legacy_landlock, } - self } }