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
@@ -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(())
}