Fix macOS system-alias matching in patch permission checks (#47879)

## Why

Local `apply_patch` permission checks can treat a macOS system alias and its canonical spelling as different locations, sending writes covered by temporary-directory grants for unnecessary approval.

## What changed

- Normalize trusted top-level aliases in local policy roots and patch targets, reusing a prepared matcher for permission requests and patch safety checks.
- Share alias normalization with Seatbelt and the macOS executor sandbox while preserving mutable symlinks and missing descendants.
- Preserve read-only and deny precedence, protected metadata restrictions, and remote URI matching. Propagate normalization failures from fallible permission checks.

## Testing

Add macOS regressions for multi-file patches with missing parent directories through both direct `apply_patch` calls and shell interception, asserting automatic approval and file contents. Add unit coverage for alias restriction precedence, mutable symlink preservation, missing descendants, and remote permission isolation.

GitOrigin-RevId: 0822ff951eaab728cb1ad91281745fa1b8809f15
This commit is contained in:
felixxia-oai
2026-09-24 16:36:57 +00:00
committed by copyberry
parent 4021746a15
commit 6f51c65958
17 changed files with 792 additions and 304 deletions
+7 -10
View File
@@ -1,5 +1,5 @@
use crate::function_tool::FunctionCallError;
use crate::safety::PatchSandboxRoute;
use crate::safety::PatchPolicyMatcher;
use crate::safety::SafetyCheck;
use crate::safety::assess_patch_safety;
use crate::session::step_context::StepContext;
@@ -7,9 +7,7 @@ use crate::session::turn_context::TurnEnvironment;
use crate::tools::sandboxing::ExecApprovalRequirement;
use codex_apply_patch::ApplyPatchAction;
use codex_apply_patch::ApplyPatchFileChange;
use codex_protocol::permissions::FileSystemSandboxPolicyContext;
use codex_protocol::protocol::FileChange;
use codex_protocol::protocol::FileSystemSandboxPolicy;
use codex_utils_path_uri::PathUri;
use std::collections::HashMap;
use std::path::PathBuf;
@@ -24,19 +22,18 @@ pub(crate) struct ApplyPatchRuntimeInvocation {
pub(crate) fn prepare_apply_patch(
step_context: &StepContext,
turn_environment: &TurnEnvironment,
file_system_sandbox_policy: &FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
sandbox_route: PatchSandboxRoute,
matching: &PatchPolicyMatcher<'_>,
action: ApplyPatchAction,
) -> Result<ApplyPatchRuntimeInvocation, FunctionCallError> {
match assess_patch_safety(
&action,
step_context.settings.approval_policy(),
turn_environment.permission_profile(),
file_system_sandbox_policy,
context,
sandbox_route,
) {
matching,
)
.map_err(|error| {
FunctionCallError::RespondToModel(format!("failed to check patch permissions: {error}"))
})? {
SafetyCheck::AutoApprove => Ok(ApplyPatchRuntimeInvocation {
action,
auto_approved: true,
+4 -3
View File
@@ -1,4 +1,5 @@
use super::*;
use crate::safety::PatchSandboxRoute;
use crate::session::tests::make_session_and_context;
use crate::session::tests::update_selected_settings_for_test;
use codex_protocol::models::PermissionProfile;
@@ -64,9 +65,9 @@ async fn prepare_apply_patch_uses_action_policy_before_turn_policy() {
let prepared = prepare_apply_patch(
&step,
&environment,
&file_system_policy,
&context,
PatchSandboxRoute::Platform(codex_protocol::config_types::WindowsSandboxLevel::Disabled),
&PatchSandboxRoute::Platform(codex_protocol::config_types::WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_policy, &context)
.expect("prepare patch matching"),
action,
)
.expect("issuing action policy should request approval");
+69 -29
View File
@@ -4,9 +4,11 @@ use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSandboxPolicyContext;
use codex_protocol::permissions::LocalFileSystemPolicyMatcher;
use codex_protocol::protocol::AskForApproval;
use codex_sandboxing::get_platform_sandbox;
use codex_utils_path_uri::PathUri;
use std::io;
const PATCH_REJECTED_OUTSIDE_PROJECT_REASON: &str =
"writing outside of the project; rejected by user approval settings";
@@ -26,18 +28,52 @@ pub(crate) enum PatchSandboxRoute {
Platform(WindowsSandboxLevel),
}
/// Keeps configured permissions and prepared local matching separate for one patch.
pub(crate) struct PatchPolicyMatcher<'a> {
configured_policy: &'a FileSystemSandboxPolicy,
pub(crate) context: FileSystemSandboxPolicyContext<'a>,
pub(crate) sandbox_route: PatchSandboxRoute,
local_matching: Option<LocalFileSystemPolicyMatcher<'a>>,
}
impl PatchSandboxRoute {
pub(crate) fn prepare_matching<'a>(
self,
configured_policy: &'a FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'a>,
) -> io::Result<PatchPolicyMatcher<'a>> {
let local_matching = match self {
Self::Platform(_) => Some(configured_policy.prepare_local_matching(context)?),
Self::ExecutorManaged => None,
};
Ok(PatchPolicyMatcher {
configured_policy,
context: *context,
sandbox_route: self,
local_matching,
})
}
}
impl PatchPolicyMatcher<'_> {
pub(crate) fn can_write_path(&self, path: &PathUri) -> io::Result<bool> {
match &self.local_matching {
Some(matching) => matching.can_write_path(path),
None => Ok(self.configured_policy.can_write_path(path, &self.context)),
}
}
}
pub fn assess_patch_safety(
action: &ApplyPatchAction,
policy: AskForApproval,
permission_profile: &PermissionProfile,
file_system_sandbox_policy: &FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
sandbox_route: PatchSandboxRoute,
) -> SafetyCheck {
matching: &PatchPolicyMatcher<'_>,
) -> io::Result<SafetyCheck> {
if action.is_empty() {
return SafetyCheck::Reject {
return Ok(SafetyCheck::Reject {
reason: "empty patch".to_string(),
};
});
}
match policy {
@@ -47,7 +83,7 @@ pub fn assess_patch_safety(
// TODO(ragona): I'm not sure this is actually correct? I believe in this case
// we want to continue to the writable paths check before asking the user.
AskForApproval::UnlessTrusted => {
return SafetyCheck::AskUser;
return Ok(SafetyCheck::AskUser);
}
}
@@ -56,7 +92,7 @@ pub fn assess_patch_safety(
policy,
AskForApproval::Granular(granular_config) if !granular_config.sandbox_approval
);
let sandbox_available = match sandbox_route {
let sandbox_available = match matching.sandbox_route {
PatchSandboxRoute::ExecutorManaged => true,
PatchSandboxRoute::Platform(windows_sandbox_level) => {
get_platform_sandbox(windows_sandbox_level != WindowsSandboxLevel::Disabled).is_some()
@@ -67,20 +103,24 @@ pub fn assess_patch_safety(
// possible that paths in the patch are hard links to files outside the
// writable roots, so we should still run `apply_patch` in a sandbox in that case.
// Disabled and External profiles intentionally do not apply an outer sandbox.
if is_write_patch_constrained_to_writable_paths(action, file_system_sandbox_policy, context)
if is_write_patch_constrained_to_writable_paths(action, matching)?
&& (matches!(
permission_profile,
PermissionProfile::Disabled | PermissionProfile::External { .. }
) || sandbox_available)
{
SafetyCheck::AutoApprove
Ok(SafetyCheck::AutoApprove)
} else if rejects_sandbox_approval {
SafetyCheck::Reject {
reason: patch_rejection_reason(permission_profile, file_system_sandbox_policy, context)
.to_string(),
}
Ok(SafetyCheck::Reject {
reason: patch_rejection_reason(
permission_profile,
matching.configured_policy,
&matching.context,
)
.to_string(),
})
} else {
SafetyCheck::AskUser
Ok(SafetyCheck::AskUser)
}
}
@@ -105,38 +145,38 @@ fn patch_rejection_reason(
fn is_write_patch_constrained_to_writable_paths(
action: &ApplyPatchAction,
file_system_sandbox_policy: &FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
) -> bool {
matching: &PatchPolicyMatcher<'_>,
) -> io::Result<bool> {
// A full-disk policy permits every patch target, so no per-path writable-root check can
// further constrain the result.
if file_system_sandbox_policy.has_full_disk_write_access_with_context(context) {
return true;
if matching
.configured_policy
.has_full_disk_write_access_with_context(&matching.context)
{
return Ok(true);
}
let is_path_writable =
|path: &PathUri| file_system_sandbox_policy.can_write_path(path, context);
for (path, change) in action.changes() {
match change {
ApplyPatchFileChange::Add { .. } | ApplyPatchFileChange::Delete { .. } => {
if !is_path_writable(path) {
return false;
if !matching.can_write_path(path)? {
return Ok(false);
}
}
ApplyPatchFileChange::Update { move_path, .. } => {
if !is_path_writable(path) {
return false;
if !matching.can_write_path(path)? {
return Ok(false);
}
if let Some(dest) = move_path
&& !is_path_writable(dest)
&& !matching.can_write_path(dest)?
{
return false;
return Ok(false);
}
}
}
}
true
Ok(true)
}
#[cfg(test)]
+147 -78
View File
@@ -22,6 +22,31 @@ fn local_context(cwd: &PathUri) -> FileSystemSandboxPolicyContext<'_> {
}
}
#[cfg(target_os = "macos")]
#[test]
fn local_system_aliases_do_not_change_remote_patch_permissions() -> std::io::Result<()> {
let directory = tempfile::tempdir_in("/tmp")?;
let cwd = PathUri::from_host_native_path(directory.path())?;
let target =
PathUri::from_host_native_path(directory.path().canonicalize()?.join("missing/file"))?;
let action = ApplyPatchAction::new_add_for_test(&target, String::new());
let permissions = PermissionProfile::workspace_write();
let policy = permissions.file_system_sandbox_policy();
assert_eq!(
assess_patch_safety(
&action,
AskForApproval::OnRequest,
&permissions,
&PatchSandboxRoute::ExecutorManaged
.prepare_matching(&policy, &local_context(&cwd))
.expect("prepare patch matching"),
)
.expect("assess patch safety"),
SafetyCheck::AskUser,
);
Ok(())
}
#[test]
fn windows_patch_matching_is_uri_native() {
let cwd = PathUri::parse("file:///C:/workspace").expect("Windows cwd");
@@ -37,18 +62,25 @@ fn windows_patch_matching_is_uri_native() {
String::new(),
);
assert!(!is_write_patch_constrained_to_writable_paths(
&outside, &policy, &context,
));
assert!(
!is_write_patch_constrained_to_writable_paths(
&outside,
&PatchSandboxRoute::ExecutorManaged
.prepare_matching(&policy, &context)
.expect("prepare patch matching"),
)
.expect("check writable paths")
);
assert_eq!(
assess_patch_safety(
&inside,
AskForApproval::Never,
&permission_profile,
&policy,
&context,
PatchSandboxRoute::ExecutorManaged,
),
&PatchSandboxRoute::ExecutorManaged
.prepare_matching(&policy, &context)
.expect("prepare patch matching"),
)
.expect("assess patch safety"),
SafetyCheck::AutoApprove,
);
}
@@ -85,10 +117,11 @@ fn full_disk_write_uses_executor_path_convention() {
&policy,
NetworkSandboxPolicy::Restricted
),
&policy,
&context,
PatchSandboxRoute::ExecutorManaged,
),
&PatchSandboxRoute::ExecutorManaged
.prepare_matching(&policy, &context)
.expect("prepare patch matching"),
)
.expect("assess patch safety"),
if full_disk_write {
SafetyCheck::AutoApprove
} else {
@@ -141,17 +174,25 @@ fn test_writable_roots_constraint() {
/*exclude_slash_tmp*/ true,
);
assert!(is_write_patch_constrained_to_writable_paths(
&add_inside,
&workspace_only_file_system_policy,
&local_context(&cwd_uri),
));
assert!(
is_write_patch_constrained_to_writable_paths(
&add_inside,
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&workspace_only_file_system_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("check writable paths")
);
assert!(!is_write_patch_constrained_to_writable_paths(
&add_outside,
&workspace_only_file_system_policy,
&local_context(&cwd_uri),
));
assert!(
!is_write_patch_constrained_to_writable_paths(
&add_outside,
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&workspace_only_file_system_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("check writable paths")
);
// With the parent dir explicitly added as a writable root, the
// outside write should be permitted.
@@ -160,11 +201,15 @@ fn test_writable_roots_constraint() {
/*exclude_tmpdir_env_var*/ true,
/*exclude_slash_tmp*/ true,
);
assert!(is_write_patch_constrained_to_writable_paths(
&add_outside,
&file_system_policy_with_parent,
&local_context(&cwd_uri),
));
assert!(
is_write_patch_constrained_to_writable_paths(
&add_outside,
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_policy_with_parent, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("check writable paths")
);
}
#[test]
@@ -188,10 +233,11 @@ fn external_sandbox_auto_approves_in_on_request() {
&add_inside,
AskForApproval::OnRequest,
&permission_profile,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
),
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("assess patch safety"),
SafetyCheck::AutoApprove
);
}
@@ -218,10 +264,11 @@ fn granular_with_all_flags_true_matches_on_request_for_out_of_root_patch() {
&add_outside,
AskForApproval::OnRequest,
&permission_profile,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled),
),
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("assess patch safety"),
SafetyCheck::AskUser,
);
assert_eq!(
@@ -235,10 +282,11 @@ fn granular_with_all_flags_true_matches_on_request_for_out_of_root_patch() {
mcp_elicitations: true,
}),
&permission_profile,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled),
),
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("assess patch safety"),
SafetyCheck::AskUser,
);
}
@@ -271,10 +319,11 @@ fn granular_sandbox_approval_false_rejects_out_of_root_patch() {
mcp_elicitations: true,
}),
&permission_profile,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled),
),
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("assess patch safety"),
SafetyCheck::Reject {
reason: PATCH_REJECTED_OUTSIDE_PROJECT_REASON.to_string(),
},
@@ -292,20 +341,25 @@ fn read_only_policy_rejects_patch_with_read_only_reason() {
let permission_profile = PermissionProfile::read_only();
let file_system_sandbox_policy = permission_profile.file_system_sandbox_policy();
assert!(!is_write_patch_constrained_to_writable_paths(
&action,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
));
assert!(
!is_write_patch_constrained_to_writable_paths(
&action,
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("check writable paths")
);
assert_eq!(
assess_patch_safety(
&action,
AskForApproval::Never,
&permission_profile,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled),
),
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("assess patch safety"),
SafetyCheck::Reject {
reason: PATCH_REJECTED_READ_ONLY_REASON.to_string(),
},
@@ -342,20 +396,25 @@ fn explicit_unreadable_paths_prevent_auto_approval_for_external_sandbox() {
},
]);
assert!(!is_write_patch_constrained_to_writable_paths(
&action,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
));
assert!(
!is_write_patch_constrained_to_writable_paths(
&action,
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("check writable paths")
);
assert_eq!(
assess_patch_safety(
&action,
AskForApproval::OnRequest,
&permission_profile,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled),
),
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("assess patch safety"),
SafetyCheck::AskUser,
);
}
@@ -392,20 +451,25 @@ fn explicit_read_only_subpaths_prevent_auto_approval_for_external_sandbox() {
},
]);
assert!(!is_write_patch_constrained_to_writable_paths(
&action,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
));
assert!(
!is_write_patch_constrained_to_writable_paths(
&action,
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("check writable paths")
);
assert_eq!(
assess_patch_safety(
&action,
AskForApproval::OnRequest,
&permission_profile,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled),
),
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("assess patch safety"),
SafetyCheck::AskUser,
);
}
@@ -435,20 +499,25 @@ fn missing_project_dot_codex_config_requires_approval() {
missing_path_behavior: None,
});
assert!(!is_write_patch_constrained_to_writable_paths(
&action,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
));
assert!(
!is_write_patch_constrained_to_writable_paths(
&action,
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("check writable paths")
);
assert_eq!(
assess_patch_safety(
&action,
AskForApproval::OnRequest,
&permission_profile,
&file_system_sandbox_policy,
&local_context(&cwd_uri),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled),
),
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&file_system_sandbox_policy, &local_context(&cwd_uri))
.expect("prepare patch matching"),
)
.expect("assess patch safety"),
SafetyCheck::AskUser,
);
}
+74 -89
View File
@@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
@@ -9,6 +10,7 @@ use tokio_util::sync::CancellationToken;
use crate::apply_patch;
use crate::apply_patch::convert_apply_patch_to_protocol;
use crate::function_tool::FunctionCallError;
use crate::safety::PatchPolicyMatcher;
use crate::safety::PatchSandboxRoute;
use crate::session::session::Session;
use crate::session::step_context::StepContext;
@@ -47,7 +49,6 @@ use codex_exec_server::ExecutorFileSystem;
use codex_features::Feature;
use codex_protocol::models::AdditionalPermissionProfile;
use codex_protocol::models::FileSystemPermissions;
use codex_protocol::permissions::FileSystemSandboxPolicyContext;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::FileChange;
use codex_protocol::protocol::PatchApplyUpdatedEvent;
@@ -238,46 +239,52 @@ fn file_paths_for_action(action: &ApplyPatchAction) -> Vec<PathUri> {
fn write_permissions_for_paths(
file_paths: &[PathUri],
file_system_sandbox_policy: &codex_protocol::permissions::FileSystemSandboxPolicy,
context: &FileSystemSandboxPolicyContext<'_>,
sandbox_route: PatchSandboxRoute,
) -> Option<AdditionalPermissionProfile> {
let mut write_paths = file_paths
.iter()
matching: &PatchPolicyMatcher<'_>,
) -> io::Result<Option<AdditionalPermissionProfile>> {
let sandbox_route = matching.sandbox_route;
let context = &matching.context;
let mut write_paths = Vec::new();
for path in file_paths {
// Skip already-writable targets before deriving parent permissions.
// Otherwise, a writable directory could grant access to its parent.
.filter(|path| !file_system_sandbox_policy.can_write_path(path, context))
.map(|path| {
path.parent()
.or_else(|| match sandbox_route {
PatchSandboxRoute::Platform(_) => {
// Host path rules can recover parents of opaque local paths.
// `to_abs_path` verifies that the target round-trips losslessly.
path.to_abs_path().ok()?.parent().map(PathUri::from)
}
PatchSandboxRoute::ExecutorManaged => None,
})
.unwrap_or_else(|| path.clone())
})
.filter(|path| !file_system_sandbox_policy.can_write_path(path, context))
.collect::<Vec<_>>();
if matching.can_write_path(path)? {
continue;
}
let parent = path
.parent()
.or_else(|| match sandbox_route {
PatchSandboxRoute::Platform(_) => {
// Host path rules can recover parents of opaque local paths.
// `to_abs_path` verifies that the target round-trips losslessly.
path.to_abs_path().ok()?.parent().map(PathUri::from)
}
PatchSandboxRoute::ExecutorManaged => None,
})
.unwrap_or_else(|| path.clone());
if !matching.can_write_path(&parent)? {
write_paths.push(parent);
}
}
write_paths.sort_by_key(PathUri::to_string);
write_paths.dedup();
let permissions = (!write_paths.is_empty()).then_some(AdditionalPermissionProfile {
if write_paths.is_empty() {
return Ok(None);
}
let permissions = AdditionalPermissionProfile {
file_system: Some(FileSystemPermissions::from_read_write_path_uris(
Some(vec![]),
Some(write_paths),
)),
..Default::default()
})?;
};
match sandbox_route {
Ok(match sandbox_route {
PatchSandboxRoute::Platform(_) => normalize_additional_permissions(permissions).ok(),
PatchSandboxRoute::ExecutorManaged => {
normalize_additional_permissions_with_context(permissions, context).ok()
}
}
})
}
/// Extracts the raw patch text used as the command-shaped hook input for apply_patch.
@@ -288,57 +295,6 @@ fn apply_patch_payload_command(payload: &ToolPayload) -> Option<String> {
}
}
async fn effective_patch_permissions(
session: &Session,
environment: &TurnEnvironment,
action: &ApplyPatchAction,
context: &FileSystemSandboxPolicyContext<'_>,
sandbox_route: PatchSandboxRoute,
) -> (
Vec<PathUri>,
crate::tools::handlers::EffectiveAdditionalPermissions,
codex_protocol::permissions::FileSystemSandboxPolicy,
) {
let environment_id = environment.selection.environment_id.as_str();
let file_paths = file_paths_for_action(action);
let granted_permissions = merge_permission_profiles(
session
.granted_session_permissions(environment_id)
.await
.as_ref(),
session
.granted_turn_permissions(environment_id)
.await
.as_ref(),
);
let base_file_system_sandbox_policy = environment
.permission_profile()
.file_system_sandbox_policy();
let file_system_sandbox_policy = effective_file_system_sandbox_policy(
&base_file_system_sandbox_policy,
granted_permissions.as_ref(),
);
let effective_additional_permissions = apply_granted_turn_permissions(
session,
environment,
context.cwd,
crate::sandboxing::SandboxPermissions::UseDefault,
write_permissions_for_paths(
&file_paths,
&file_system_sandbox_policy,
context,
sandbox_route,
),
)
.await;
(
file_paths,
effective_additional_permissions,
file_system_sandbox_policy,
)
}
impl ToolExecutor<ToolInvocation> for ApplyPatchHandler {
fn tool_name(&self) -> ToolName {
ToolName::plain("apply_patch")
@@ -562,21 +518,50 @@ async fn execute_verified_patch(
turn_environment.config().windows_sandbox_level,
))
};
let (file_paths, effective_additional_permissions, file_system_sandbox_policy) =
effective_patch_permissions(
tool_ctx.session.as_ref(),
&turn_environment,
&action,
&policy_context,
sandbox_route,
)
.await;
let environment_id = turn_environment.selection.environment_id.as_str();
let file_paths = file_paths_for_action(&action);
let granted_permissions = merge_permission_profiles(
tool_ctx
.session
.granted_session_permissions(environment_id)
.await
.as_ref(),
tool_ctx
.session
.granted_turn_permissions(environment_id)
.await
.as_ref(),
);
let base_file_system_sandbox_policy = turn_environment
.permission_profile()
.file_system_sandbox_policy();
let file_system_sandbox_policy = effective_file_system_sandbox_policy(
&base_file_system_sandbox_policy,
granted_permissions.as_ref(),
);
let matching = sandbox_route
.prepare_matching(&file_system_sandbox_policy, &policy_context)
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
"failed to prepare patch permissions: {error}"
))
})?;
let additional_permissions =
write_permissions_for_paths(&file_paths, &matching).map_err(|error| {
FunctionCallError::RespondToModel(format!("failed to check patch permissions: {error}"))
})?;
let effective_additional_permissions = apply_granted_turn_permissions(
tool_ctx.session.as_ref(),
&turn_environment,
&cwd,
crate::sandboxing::SandboxPermissions::UseDefault,
additional_permissions,
)
.await;
let apply = apply_patch::prepare_apply_patch(
&tool_ctx.step_context,
&turn_environment,
&file_system_sandbox_policy,
&policy_context,
sandbox_route,
&matching,
action,
)?;
let changes = convert_apply_patch_to_protocol(&apply.action);
@@ -295,10 +295,11 @@ fn write_permissions_for_paths_skip_dirs_already_writable_under_workspace_root()
let permissions = write_permissions_for_paths(
&[file_path.into()],
&sandbox_policy,
&local_context(&cwd.into()),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled),
);
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&sandbox_policy, &local_context(&cwd.into()))
.expect("prepare patch matching"),
)
.expect("derive write permissions");
assert_eq!(permissions, None);
}
@@ -321,10 +322,11 @@ fn write_permissions_for_paths_keep_dirs_outside_workspace_root() {
let permissions = write_permissions_for_paths(
&[file_path.into()],
&sandbox_policy,
&local_context(&cwd_abs.into()),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled),
);
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&sandbox_policy, &local_context(&cwd_abs.into()))
.expect("prepare patch matching"),
)
.expect("derive write permissions");
let expected_outside = outside.abs();
assert_eq!(
@@ -348,10 +350,11 @@ fn write_permissions_for_paths_do_not_widen_workspace_root_target() {
);
let permissions = write_permissions_for_paths(
&[cwd.clone().into()],
&sandbox_policy,
&local_context(&cwd.into()),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled),
);
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&sandbox_policy, &local_context(&cwd.into()))
.expect("prepare patch matching"),
)
.expect("derive write permissions");
assert_eq!(permissions, None);
}
@@ -368,10 +371,11 @@ fn write_permissions_for_paths_do_not_regrant_an_already_writable_parent() {
let permissions = write_permissions_for_paths(
&[file_path.into()],
&sandbox_policy,
&local_context(&cwd.into()),
PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled),
);
&PatchSandboxRoute::Platform(WindowsSandboxLevel::Disabled)
.prepare_matching(&sandbox_policy, &local_context(&cwd.into()))
.expect("prepare patch matching"),
)
.expect("derive write permissions");
assert_eq!(permissions, None);
}
@@ -390,10 +394,11 @@ fn write_permissions_for_windows_paths_uses_executor_uris() {
assert_eq!(
write_permissions_for_paths(
&[outside],
&policy,
&context,
PatchSandboxRoute::ExecutorManaged,
&PatchSandboxRoute::ExecutorManaged
.prepare_matching(&policy, &context)
.expect("prepare patch matching"),
)
.expect("derive write permissions")
.and_then(|profile| profile.file_system)
.map(|permissions| permissions.entries),
Some(vec![FileSystemSandboxEntry::new(
@@ -0,0 +1,111 @@
//! Local system aliases must admit whole patches before ordinary sandboxed execution.
use anyhow::Result;
use codex_core::TurnInputRequest;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::user_input::UserInput;
use core_test_support::responses::ev_apply_patch_custom_tool_call;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_exec_command_call;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::mount_sse_sequence;
use core_test_support::responses::sse;
use core_test_support::responses::start_mock_server;
use core_test_support::skip_if_no_network;
use core_test_support::skip_if_remote;
use core_test_support::test_codex::test_codex;
use core_test_support::wait_for_event;
use pretty_assertions::assert_eq;
use test_case::test_case;
#[test_case(false; "freeform")]
#[test_case(true; "shell interception")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn system_alias_patch_creates_multiple_files_and_missing_parents_without_review(
shell: bool,
) -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_remote!(Ok(()), "exercises native macOS system aliases");
let directory = tempfile::tempdir_in("/tmp")?;
let target = directory
.path()
.canonicalize()?
.join("missing/nested/evidence.json");
let second = directory.path().join("notes.txt");
let contents = "x".repeat(/*n*/ 300_000);
let patch = format!(
"*** Begin Patch\n*** Add File: {}\n+{contents}\n*** Add File: {}\n+notes\n*** End Patch",
target.display(),
second.display(),
);
let server = start_mock_server().await;
let test = test_codex()
.with_config(|config| {
config.approvals_reviewer = ApprovalsReviewer::AutoReview;
config
.permissions
.approval_policy
.set(AskForApproval::OnRequest)
.expect("allow review in the regression");
config
.permissions
.set_permission_profile(PermissionProfile::workspace_write())
.expect("enable the default temporary-directory grants");
})
.build_with_auto_env(&server)
.await?;
let call = if shell {
ev_exec_command_call("patch", &format!("apply_patch <<'PATCH'\n{patch}\nPATCH"))
} else {
ev_apply_patch_custom_tool_call("patch", &patch)
};
let response = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("patch"),
call,
ev_completed("patch"),
]),
sse(vec![
ev_assistant_message("done", "done"),
ev_completed("done"),
]),
],
)
.await;
test.codex
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
text: "Save both evidence files".into(),
text_elements: vec![],
}]))
.await?;
let mut auto_approved = None;
loop {
match wait_for_event(&test.codex, |_| true).await {
EventMsg::PatchApplyBegin(begin) => auto_approved = Some(begin.auto_approved),
EventMsg::ApplyPatchApprovalRequest(event) => {
panic!("unexpected approval: {}", event.call_id)
}
EventMsg::GuardianAssessment(_) => {
panic!("permitted temp patch should not reach Guardian")
}
EventMsg::TurnComplete(_) => break,
_ => {}
}
}
assert_eq!(auto_approved, Some(true));
assert_eq!(
(
std::fs::read_to_string(target)?,
std::fs::read_to_string(second)?
),
(format!("{contents}\n"), "notes\n".to_string()),
);
assert_eq!(response.requests().len(), 2);
Ok(())
}
+2
View File
@@ -44,6 +44,8 @@ mod agents_md;
mod app_tool_exposure;
mod apply_patch_cli;
mod apply_patch_serialization;
#[cfg(target_os = "macos")]
mod apply_patch_system_aliases;
#[cfg(not(target_os = "windows"))]
mod approvals;
mod audio_truncation;
+20 -5
View File
@@ -18,7 +18,7 @@ use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxTransformRequest;
use codex_sandboxing::SandboxType;
use codex_utils_absolute_path::AbsolutePathBuf;
#[cfg(not(target_os = "linux"))]
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
use codex_utils_absolute_path::canonicalize_preserving_symlinks;
#[cfg(any(windows, test))]
use codex_utils_path_uri::LegacyAppPathString;
@@ -130,7 +130,7 @@ impl FileSystemSandboxRunner {
// Linux resolves aliases in the sandbox helper. Doing it here also probes
// 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);
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;
@@ -296,19 +296,34 @@ fn bind_windows_cwd_relative_deny_read_globs(
}
#[cfg(not(target_os = "linux"))]
fn normalize_file_system_policy_root_aliases(file_system_policy: &mut FileSystemSandboxPolicy) {
fn normalize_file_system_policy_root_aliases(
file_system_policy: &mut FileSystemSandboxPolicy,
) -> Result<(), JSONRPCErrorError> {
for entry in &mut file_system_policy.entries {
// Alias normalization uses this executor's filesystem; leave foreign
// or opaque PathUris unchanged.
if let FileSystemPath::Path { path } = &mut entry.path
&& let Ok(native_path) = path.to_abs_path()
{
*path = normalize_top_level_alias(native_path).into();
#[cfg(target_os = "macos")]
{
*path = native_path
.normalize_system_aliases()
.map_err(|error| {
invalid_request(format!("failed to normalize {path}: {error}"))
})?
.into();
}
#[cfg(not(target_os = "macos"))]
{
*path = normalize_top_level_alias(native_path).into();
}
}
}
Ok(())
}
#[cfg(not(target_os = "linux"))]
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn normalize_top_level_alias(path: AbsolutePathBuf) -> AbsolutePathBuf {
let raw_path = path.to_path_buf();
for ancestor in raw_path.ancestors() {
@@ -1,6 +1,7 @@
use std::path::Path;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
@@ -14,6 +15,7 @@ use crate::permissions::FileSystemAccessMode::Write;
use crate::permissions::FileSystemPath;
use crate::permissions::FileSystemSandboxEntry;
use crate::permissions::FileSystemSandboxPolicy;
use crate::permissions::FileSystemSandboxPolicyContext;
use crate::permissions::FileSystemSpecialPath;
use crate::permissions::FileSystemSpecialPath::Minimal;
use crate::permissions::FileSystemSpecialPath::Tmpdir;
@@ -115,11 +117,22 @@ fn effective_workspace_intersection_preserves_network_metadata_and_temp() {
let result = intersection(&authority, &requested, &project);
let policy = result.file_system_sandbox_policy();
// Keep :tmpdir independent of the workspace fixtures, which themselves live
// under the host's temporary directory.
let scratch = TempDir::new().expect("temporary directory grant");
let scratch_root = canonical(&scratch);
let cwd = PathUri::from_abs_path(&root);
let temporary_directories = [PathUri::from_abs_path(&scratch_root)];
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: std::slice::from_ref(&cwd),
user_home_dir: None,
temporary_directories: Some(&temporary_directories),
};
assert_eq!(
[&root, &project]
.map(|path| policy
.resolve_access_for_local_path_with_cwd(path.as_path(), root.as_path())),
[Read, Write]
[&root, &project, &scratch_root]
.map(|path| policy.resolve_access(&PathUri::from_abs_path(path), &context)),
[Read, Write, Write]
);
assert_eq!(result.network_sandbox_policy(), Restricted);
assert!(policy.entries.contains(&special(Tmpdir, Write)));
+55 -43
View File
@@ -25,11 +25,15 @@ use crate::protocol::SandboxPolicy;
use crate::protocol::WritableRoot;
mod deny_read_validator;
mod local_aliases;
mod target;
mod windows_glob;
use local_aliases::LocalPolicyContext;
pub use deny_read_validator::DenyReadValidator;
pub use deny_read_validator::DenyReadViolation;
pub use local_aliases::LocalFileSystemPolicyMatcher;
pub use windows_glob::WindowsDenyReadGlobScan;
pub use windows_glob::windows_deny_read_glob_scan;
@@ -248,7 +252,7 @@ impl WritableRootPathResolution {
fn resolve(self, path: AbsolutePathBuf) -> AbsolutePathBuf {
match self {
Self::Effective => normalize_effective_absolute_path(path),
Self::PreserveMutableComponents => normalize_trusted_top_level_alias(path),
Self::PreserveMutableComponents => path.normalize_system_aliases().unwrap_or(path),
}
}
}
@@ -968,7 +972,9 @@ impl FileSystemSandboxPolicy {
cwd: &Path,
) -> FileSystemAccessMode {
with_local_policy_context(path, cwd, |path, context| {
self.resolve_access(path, context)
self.prepare_local_matching(context)
.map(|matching| matching.resolve_access(path))
.unwrap_or(FileSystemAccessMode::Deny)
})
.unwrap_or(FileSystemAccessMode::Deny)
}
@@ -982,7 +988,9 @@ impl FileSystemSandboxPolicy {
/// Native-path compatibility adapter for local executor boundaries.
pub fn can_write_local_path_with_cwd(&self, path: &Path, cwd: &Path) -> bool {
with_local_policy_context(path, cwd, |path, context| {
self.can_write_path(path, context)
self.prepare_local_matching(context)
.and_then(|matching| matching.can_write_path(path))
.unwrap_or(false)
})
.unwrap_or(false)
}
@@ -1439,12 +1447,22 @@ impl FileSystemSandboxPolicy {
if self.has_full_disk_read_access() {
return Vec::new();
}
let Some(local_context) = LocalPolicyContext::new(cwd) else {
return Vec::new();
};
let Ok(matching) = self.prepare_local_matching(&local_context.as_context()) else {
return Vec::new();
};
dedup_absolute_paths(
self.resolved_entries_with_cwd(cwd)
.into_iter()
.filter(|entry| entry.access.can_read())
.filter(|entry| self.can_read_local_path_with_cwd(entry.path.as_path(), cwd))
.filter(|entry| {
matching
.resolve_access(&PathUri::from_abs_path(&entry.path))
.can_read()
})
.map(|entry| entry.path)
.collect(),
/*normalize_effective_paths*/ true,
@@ -1514,13 +1532,21 @@ impl FileSystemSandboxPolicy {
{
return Vec::new();
}
let Some(local_context) = LocalPolicyContext::new(cwd) else {
return Vec::new();
};
let Ok(matching) = self.prepare_local_matching(&local_context.as_context()) else {
return Vec::new();
};
// Resolve precedence and filesystem aliases once per entry, rather than repeating
// that work for every writable root while collecting its read-only carveouts.
let effective_entries: Vec<&ResolvedFileSystemEntry> = resolved_entries
.iter()
.filter(|entry| {
entry.access.can_write()
== self.can_write_local_path_with_cwd(entry.path.as_path(), cwd)
== matching
.can_write_path(&PathUri::from_abs_path(&entry.path))
.unwrap_or(false)
})
.collect();
if !effective_entries
@@ -1568,7 +1594,7 @@ impl FileSystemSandboxPolicy {
.map(|entry| &entry.entry.path)
.collect();
let protected_metadata_names =
protected_metadata_names_for_writable_root(self, &root, &raw_writable_roots, cwd);
protected_metadata_names_for_writable_root(&matching, &root, &raw_writable_roots);
let protect_missing_dot_codex = effective_cwd.as_ref() == Some(&root);
let mut read_only_subpaths: Vec<AbsolutePathBuf> =
default_read_only_subpaths_for_writable_root(&root, protect_missing_dot_codex)
@@ -1657,12 +1683,22 @@ impl FileSystemSandboxPolicy {
let root = AbsolutePathBuf::from_absolute_path(cwd)
.ok()
.map(|cwd| absolute_root_path_for_cwd(&cwd));
let local_context = LocalPolicyContext::new(cwd);
let matching = local_context
.as_ref()
.and_then(|context| self.prepare_local_matching(&context.as_context()).ok());
dedup_absolute_paths(
self.resolved_entries_with_cwd(cwd)
.iter()
.filter(|entry| entry.access == FileSystemAccessMode::Deny)
.filter(|entry| !self.can_read_local_path_with_cwd(entry.path.as_path(), cwd))
.filter(|entry| {
!matching.as_ref().is_some_and(|matching| {
matching
.resolve_access(&PathUri::from_abs_path(&entry.path))
.can_read()
})
})
// Restricted policies already deny reads outside explicit allow roots,
// so materializing the filesystem root here would erase narrower
// readable carveouts when downstream sandboxes apply deny masks last.
@@ -1983,16 +2019,8 @@ fn with_local_policy_context<T>(
) -> Option<T> {
let cwd = AbsolutePathBuf::from_absolute_path(cwd).ok()?;
let path = PathUri::from(resolve_candidate_path(path, cwd.as_path())?);
let cwd = PathUri::from(cwd);
let user_home_dir = PathUri::from_host_native_path("~").ok();
let temporary_directories = local_temporary_directories();
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: std::slice::from_ref(&cwd),
user_home_dir: user_home_dir.as_ref(),
temporary_directories: Some(&temporary_directories),
};
Some(evaluate(&path, &context))
let context = LocalPolicyContext::new(cwd.as_path())?;
Some(evaluate(&path, &context.as_context()))
}
pub fn file_system_root(context: &FileSystemSandboxPolicyContext<'_>) -> Option<PathUri> {
@@ -2210,27 +2238,6 @@ fn normalize_effective_absolute_path(path: AbsolutePathBuf) -> AbsolutePathBuf {
path
}
fn normalize_trusted_top_level_alias(path: AbsolutePathBuf) -> AbsolutePathBuf {
let Some(top_level) = path.as_path().ancestors().find(|ancestor| {
ancestor.parent().is_some() && ancestor.parent().and_then(Path::parent).is_none()
}) else {
return path;
};
let Ok(metadata) = std::fs::symlink_metadata(top_level) else {
return path;
};
if !metadata.file_type().is_symlink() {
return path;
}
let Ok(canonical_top_level) = top_level.canonicalize() else {
return path;
};
let Ok(suffix) = path.as_path().strip_prefix(top_level) else {
return path;
};
AbsolutePathBuf::from_absolute_path(canonical_top_level.join(suffix)).unwrap_or(path)
}
pub(crate) fn default_read_only_subpaths_for_writable_root(
writable_root: &AbsolutePathBuf,
protect_missing_dot_codex: bool,
@@ -2392,10 +2399,9 @@ fn has_explicit_resolved_path_entry(
}
fn protected_metadata_names_for_writable_root(
policy: &FileSystemSandboxPolicy,
matching: &LocalFileSystemPolicyMatcher<'_>,
root: &AbsolutePathBuf,
raw_writable_roots: &[&AbsolutePathBuf],
cwd: &Path,
) -> Vec<String> {
let mut protected_names = Vec::new();
for metadata_name in PROTECTED_METADATA_PATH_NAMES {
@@ -2407,7 +2413,9 @@ fn protected_metadata_names_for_writable_root(
);
if metadata_paths.iter().all(|metadata_path| {
!policy.can_write_local_path_with_cwd(metadata_path.as_path(), cwd)
!matching
.can_write_path(&PathUri::from_abs_path(metadata_path))
.unwrap_or(false)
}) {
protected_names.push((*metadata_name).to_string());
}
@@ -3114,8 +3122,12 @@ mod tests {
AbsolutePathBuf::from_absolute_path(writable_root).expect("absolute writable root");
let outside_root =
AbsolutePathBuf::from_absolute_path(outside_root).expect("absolute outside root");
let expected_writable_root = normalize_trusted_top_level_alias(writable_root.clone());
let expected_outside_root = normalize_trusted_top_level_alias(outside_root);
let expected_writable_root = writable_root
.normalize_system_aliases()
.expect("normalize writable root");
let expected_outside_root = outside_root
.normalize_system_aliases()
.expect("normalize outside root");
let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry::new(
writable_root.into(),
FileSystemAccessMode::Write,
@@ -0,0 +1,131 @@
//! Prepare local policy paths in the sandbox's trusted system-alias namespace.
//! Normalize grants and restrictions once per operation without resolving mutable symlinks.
//! Borrow unchanged policies and return normalization failures to fallible callers.
use super::FileSystemAccessMode;
use super::FileSystemPath;
use super::FileSystemSandboxEntry;
use super::FileSystemSandboxPolicy;
use super::FileSystemSandboxPolicyContext;
use super::FileSystemSpecialPath;
use super::local_temporary_directories;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use std::borrow::Cow;
use std::io;
use std::path::Path;
/// Owns native environment bindings so one matcher can serve a whole root calculation.
pub(super) struct LocalPolicyContext {
cwd: PathUri,
user_home_dir: Option<PathUri>,
temporary_directories: Vec<PathUri>,
}
impl LocalPolicyContext {
pub(super) fn new(cwd: &Path) -> Option<Self> {
Some(Self {
cwd: PathUri::from(AbsolutePathBuf::from_absolute_path(cwd).ok()?),
user_home_dir: PathUri::from_host_native_path("~").ok(),
temporary_directories: local_temporary_directories(),
})
}
pub(super) fn as_context(&self) -> FileSystemSandboxPolicyContext<'_> {
FileSystemSandboxPolicyContext {
cwd: &self.cwd,
workspace_roots: std::slice::from_ref(&self.cwd),
user_home_dir: self.user_home_dir.as_ref(),
temporary_directories: Some(&self.temporary_directories),
}
}
}
/// An operation-scoped view of a configured policy with local roots resolved.
/// Reuse it for each target in the operation; prepare again when policy or
/// environment bindings change. Only target paths are normalized during matching.
pub struct LocalFileSystemPolicyMatcher<'a> {
policy: Cow<'a, FileSystemSandboxPolicy>,
context: FileSystemSandboxPolicyContext<'a>,
}
impl FileSystemSandboxPolicy {
/// Prepare local permission matching, resolving trusted aliases on macOS.
/// Borrows the configured policy on platforms that do not need normalization.
/// Remote paths must use `can_write_path` instead: the controller's
/// filesystem cannot establish aliases on another host.
pub fn prepare_local_matching<'a>(
&'a self,
context: &FileSystemSandboxPolicyContext<'a>,
) -> io::Result<LocalFileSystemPolicyMatcher<'a>> {
let mut policy = Cow::Borrowed(self);
if cfg!(target_os = "macos") {
let policy = policy.to_mut();
// Preserve non-path entries, including globs that constrain full-disk
// grants. Materialize symbolic roots using the selected environment.
policy.entries.retain(|entry| {
matches!(
entry.path,
FileSystemPath::GlobPattern { .. }
| FileSystemPath::Special {
value: FileSystemSpecialPath::Root
| FileSystemSpecialPath::Minimal
| FileSystemSpecialPath::Unknown { .. }
}
)
});
for (root, access) in self.resolved_entries(context) {
if root.is_opaque() {
continue;
}
let normalized =
root.to_abs_path()?
.normalize_system_aliases()
.map_err(|error| {
io::Error::new(
error.kind(),
format!("failed to normalize {root}: {error}"),
)
})?;
policy
.entries
.push(FileSystemSandboxEntry::new(normalized.into(), access));
}
}
Ok(LocalFileSystemPolicyMatcher {
policy,
context: *context,
})
}
}
impl LocalFileSystemPolicyMatcher<'_> {
/// Check write access, preserving any failure to normalize the target path.
pub fn can_write_path(&self, path: &PathUri) -> io::Result<bool> {
self.with_path(path, |path| self.policy.can_write_path(path, &self.context))
}
pub(super) fn resolve_access(&self, path: &PathUri) -> FileSystemAccessMode {
self.with_path(path, |path| self.policy.resolve_access(path, &self.context))
.unwrap_or(FileSystemAccessMode::Deny)
}
fn with_path<T>(&self, path: &PathUri, evaluate: impl FnOnce(&PathUri) -> T) -> io::Result<T> {
let path = if cfg!(target_os = "macos") {
Cow::Owned(PathUri::from(
path.to_abs_path()?
.normalize_system_aliases()
.map_err(|error| {
io::Error::new(error.kind(), format!("failed to normalize {path}: {error}"))
})?,
))
} else {
Cow::Borrowed(path)
};
Ok(evaluate(&path))
}
}
#[cfg(all(test, target_os = "macos"))]
#[path = "local_aliases_tests.rs"]
mod tests;
@@ -0,0 +1,65 @@
use super::*;
use crate::permissions::FileSystemAccessMode;
use pretty_assertions::assert_eq;
#[test]
fn local_aliases_keep_read_only_and_deny_overrides() -> anyhow::Result<()> {
let directory = tempfile::tempdir_in("/tmp")?;
let logical = PathUri::from_host_native_path(directory.path())?;
let physical = PathUri::from_host_native_path(directory.path().canonicalize()?)?;
let context = FileSystemSandboxPolicyContext {
cwd: &physical,
workspace_roots: std::slice::from_ref(&physical),
user_home_dir: None,
temporary_directories: None,
};
for writable in [&logical, &physical] {
for restricted in [&logical, &physical] {
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Deny] {
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
writable.clone().into(),
FileSystemAccessMode::Write,
),
FileSystemSandboxEntry::new(restricted.join("protected")?.into(), access),
]);
let matching = policy.prepare_local_matching(&context)?;
for spelling in [&logical, &physical] {
let protected = spelling.join("protected/missing/file")?;
assert_eq!(
(
matching.can_write_path(&spelling.join("missing/file")?)?,
matching.can_write_path(&protected)?,
policy.resolve_access_for_local_path_with_cwd(
protected.to_abs_path()?.as_path(),
directory.path(),
),
matching.can_write_path(&spelling.join(".codex/config.toml")?)?,
),
(true, false, access, false),
);
}
}
}
}
Ok(())
}
#[test]
fn equivalent_alias_entries_keep_restrictive_precedence() -> anyhow::Result<()> {
let directory = tempfile::tempdir_in("/tmp")?;
let logical = PathUri::from_host_native_path(directory.path())?;
let physical = PathUri::from_host_native_path(directory.path().canonicalize()?)?;
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(physical.clone().into(), FileSystemAccessMode::Write),
FileSystemSandboxEntry::new(logical.into(), FileSystemAccessMode::Deny),
]);
assert_eq!(
policy.resolve_access_for_local_path_with_cwd(
physical.join("missing")?.to_abs_path()?.as_path(),
directory.path(),
),
FileSystemAccessMode::Deny,
);
Ok(())
}
+1 -24
View File
@@ -423,30 +423,7 @@ fn nested_symlink_component(path: &Path) -> Option<&Path> {
fn normalize_top_level_alias_for_sandbox(
path: AbsolutePathBuf,
) -> Result<AbsolutePathBuf, SeatbeltPreparationError> {
let Some(top_level) = path.as_path().ancestors().find(|ancestor| {
ancestor.parent().is_some() && ancestor.parent().and_then(Path::parent).is_none()
}) else {
return Ok(path);
};
if !std::fs::symlink_metadata(top_level).is_ok_and(|metadata| metadata.file_type().is_symlink())
{
return Ok(path);
}
let canonical_top_level = top_level.canonicalize().map_err(|err| {
SeatbeltPreparationError::FileSystem(format!(
"failed to normalize top-level alias {} for Seatbelt: {err}",
top_level.display()
))
})?;
let suffix = path.as_path().strip_prefix(top_level).map_err(|err| {
SeatbeltPreparationError::FileSystem(format!(
"failed to preserve path {} after normalizing {}: {err}",
path.display(),
top_level.display()
))
})?;
AbsolutePathBuf::from_absolute_path(canonical_top_level.join(suffix)).map_err(|err| {
path.normalize_system_aliases().map_err(|err| {
SeatbeltPreparationError::FileSystem(format!(
"failed to normalize top-level alias for path {}: {err}",
path.display()
+1
View File
@@ -12,6 +12,7 @@ use std::path::PathBuf;
use ts_rs::TS;
mod absolutize;
mod system_aliases;
/// A path that is guaranteed to be absolute and normalized (though it is not
/// guaranteed to be canonicalized or exist on the filesystem).
@@ -0,0 +1,35 @@
//! Normalize aliases rooted directly in the trusted filesystem root.
//! Never resolve mutable components below that root, including missing descendants.
use crate::AbsolutePathBuf;
use std::io;
use std::path::Path;
impl AbsolutePathBuf {
/// Resolve a top-level system alias, such as macOS `/tmp -> /private/tmp`.
/// All remaining components keep their logical spelling, even if they are
/// symlinks or do not exist. Only call this on the host that owns the path.
pub fn normalize_system_aliases(&self) -> io::Result<Self> {
let Some(top_level) = self.as_path().ancestors().find(|ancestor| {
ancestor.parent().is_some() && ancestor.parent().and_then(Path::parent).is_none()
}) else {
return Ok(self.clone());
};
match std::fs::symlink_metadata(top_level) {
Ok(metadata) if metadata.file_type().is_symlink() => {}
Ok(_) => return Ok(self.clone()),
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(self.clone()),
Err(error) => return Err(error),
}
let canonical_top_level = dunce::canonicalize(top_level)?;
let suffix = self
.as_path()
.strip_prefix(top_level)
.map_err(io::Error::other)?;
Self::from_absolute_path(canonical_top_level.join(suffix))
}
}
#[cfg(test)]
#[path = "system_aliases_tests.rs"]
mod tests;
@@ -0,0 +1,29 @@
use crate::AbsolutePathBuf;
use pretty_assertions::assert_eq;
#[cfg(target_os = "macos")]
#[test]
fn system_aliases_preserve_mutable_symlinks_and_missing_descendants() -> std::io::Result<()> {
let directory = tempfile::tempdir_in("/tmp")?;
let outside = tempfile::tempdir()?;
let logical = AbsolutePathBuf::from_absolute_path(directory.path())?;
let physical = logical.canonicalize()?;
std::os::unix::fs::symlink(outside.path(), logical.join("mutable"))?;
for suffix in ["", "missing/child", "mutable", "mutable/missing/child"] {
assert_eq!(
logical.join(suffix).normalize_system_aliases()?,
physical.join(suffix),
);
}
Ok(())
}
#[test]
fn ordinary_paths_keep_missing_descendants() -> std::io::Result<()> {
let directory = tempfile::tempdir()?;
let physical = AbsolutePathBuf::from_absolute_path(directory.path())?.canonicalize()?;
let missing = physical.join("missing/child");
assert_eq!(missing.normalize_system_aliases()?, missing);
Ok(())
}