Base: codex-main originale (prima del fork aKode)
This commit is contained in:
102
codex-rs/protocol/src/permissions/deny_read_validator.rs
Normal file
102
codex-rs/protocol/src/permissions/deny_read_validator.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
//! Core's mandatory-denial validation, shared without resolving paths on the controller.
|
||||
//! Checks raw concrete grants; policy application and sandbox enforcement remain caller-owned.
|
||||
|
||||
use super::FileSystemAccessMode;
|
||||
use super::FileSystemPath;
|
||||
use super::FileSystemSandboxEntry;
|
||||
use super::FileSystemSandboxKind;
|
||||
use super::FileSystemSandboxPolicy;
|
||||
use super::FileSystemSandboxPolicyContext;
|
||||
use super::FileSystemSpecialPath;
|
||||
use super::InvalidDenyReadGlobBehavior;
|
||||
use super::PreparedReadDenyMatcher;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
|
||||
/// Prepared mandatory rules reused when a caller replaces its selected profile.
|
||||
pub struct DenyReadValidator {
|
||||
required_entries: Vec<FileSystemSandboxEntry>,
|
||||
matcher: Option<PreparedReadDenyMatcher>,
|
||||
}
|
||||
|
||||
/// Details needed to retain the caller's existing sourced constraint diagnostics.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum DenyReadViolation {
|
||||
MissingRequiredDeny,
|
||||
ReadablePath(PathUri),
|
||||
}
|
||||
|
||||
impl DenyReadValidator {
|
||||
/// Prepares the strict matcher once, using the supplied executor facts.
|
||||
pub fn new(
|
||||
required: &FileSystemSandboxPolicy,
|
||||
context: &FileSystemSandboxPolicyContext<'_>,
|
||||
) -> Result<Self, String> {
|
||||
let matcher = has_context_read_denials(required, context)
|
||||
.then(|| {
|
||||
required
|
||||
.prepare_deny_read_matcher(context, InvalidDenyReadGlobBehavior::ReturnError)
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(Self {
|
||||
required_entries: required.entries.clone(),
|
||||
matcher,
|
||||
})
|
||||
}
|
||||
|
||||
/// Preserves Core's entry-presence and raw readable-path checks.
|
||||
///
|
||||
/// Symbolic entries are not expanded. An equally specific deny does not
|
||||
/// exempt a concrete readable grant from this validation. Native callers
|
||||
/// retain their native-path conversion boundary before passing the policy.
|
||||
pub fn validate(
|
||||
&self,
|
||||
selected: &FileSystemSandboxPolicy,
|
||||
context: &FileSystemSandboxPolicyContext<'_>,
|
||||
) -> Result<(), DenyReadViolation> {
|
||||
let missing_required_deny = self
|
||||
.required_entries
|
||||
.iter()
|
||||
.any(|entry| !selected.entries.contains(entry));
|
||||
let violating_root = selected
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|entry| entry.access.can_read())
|
||||
.find_map(|entry| {
|
||||
let FileSystemPath::Path { path } = &entry.path else {
|
||||
return None;
|
||||
};
|
||||
if path.infer_path_convention() != context.cwd.infer_path_convention() {
|
||||
return None;
|
||||
}
|
||||
self.matcher
|
||||
.as_ref()
|
||||
.is_some_and(|matcher| {
|
||||
FileSystemSandboxPolicy::matches_prepared_read_deny(path, context, matcher)
|
||||
})
|
||||
.then_some(path)
|
||||
});
|
||||
// Core reports the first conflicting path even when a required entry is missing too.
|
||||
if let Some(path) = violating_root {
|
||||
return Err(DenyReadViolation::ReadablePath(path.clone()));
|
||||
}
|
||||
if missing_required_deny {
|
||||
return Err(DenyReadViolation::MissingRequiredDeny);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn has_context_read_denials(
|
||||
policy: &FileSystemSandboxPolicy,
|
||||
context: &FileSystemSandboxPolicyContext<'_>,
|
||||
) -> bool {
|
||||
policy.kind == FileSystemSandboxKind::Restricted
|
||||
&& policy.entries.iter().any(|entry| {
|
||||
entry.access == FileSystemAccessMode::Deny
|
||||
&& !matches!(&entry.path,
|
||||
FileSystemPath::Special { value: FileSystemSpecialPath::SlashTmp }
|
||||
if context.cwd.infer_path_convention() != Some(PathConvention::Posix)
|
||||
)
|
||||
})
|
||||
}
|
||||
91
codex-rs/protocol/src/permissions/enforcement.rs
Normal file
91
codex-rs/protocol/src/permissions/enforcement.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
//! Projects filesystem permissions for each sandbox, preserving mutable paths where the backend binds them.
|
||||
|
||||
use super::FileSystemSandboxPolicy;
|
||||
use super::LocalPolicyContext;
|
||||
use super::normalize_effective_absolute_path;
|
||||
use crate::protocol::WritableRoot;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
/// How a sandbox binds filesystem roots after access and precedence are resolved.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum FileSystemPolicyProjection {
|
||||
/// Resolve roots and carveouts to their effective native paths.
|
||||
Native,
|
||||
/// Normalize trusted system aliases, leaving mutable components for the sandbox to bind.
|
||||
PreserveMutableRoots,
|
||||
/// Inherit root metadata writes from the root mount and retain literal paths for read denials.
|
||||
LinuxMounts,
|
||||
}
|
||||
|
||||
impl FileSystemPolicyProjection {
|
||||
pub(super) fn resolve_writable_path(self, path: AbsolutePathBuf) -> AbsolutePathBuf {
|
||||
match self {
|
||||
Self::Native | Self::LinuxMounts => normalize_effective_absolute_path(path),
|
||||
Self::PreserveMutableRoots => path.normalize_system_aliases().unwrap_or(path),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Filesystem permissions resolved on the host that will enforce them.
|
||||
///
|
||||
/// Roots retain policy order. Deny globs remain patterns for the sandbox to enforce or expand.
|
||||
/// Resolving these paths does not pin their targets; the sandbox still binds them at launch.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResolvedFileSystemPermissions {
|
||||
pub has_full_disk_read_access: bool,
|
||||
pub has_full_disk_write_access: bool,
|
||||
pub include_platform_defaults: bool,
|
||||
pub readable_roots: Vec<AbsolutePathBuf>,
|
||||
pub writable_roots: Vec<WritableRoot>,
|
||||
pub unreadable_roots: Vec<AbsolutePathBuf>,
|
||||
pub unreadable_globs: Vec<String>,
|
||||
pub glob_scan_max_depth: Option<usize>,
|
||||
}
|
||||
|
||||
impl FileSystemSandboxPolicy {
|
||||
/// Resolve the roots for one enforcement operation after binding executor-owned paths.
|
||||
pub fn resolve_for_enforcement(
|
||||
&self,
|
||||
cwd: &Path,
|
||||
projection: FileSystemPolicyProjection,
|
||||
) -> io::Result<ResolvedFileSystemPermissions> {
|
||||
let mut resolved = ResolvedFileSystemPermissions {
|
||||
has_full_disk_read_access: self.has_full_disk_read_access(),
|
||||
has_full_disk_write_access: self.has_full_disk_write_access(),
|
||||
include_platform_defaults: self.include_platform_defaults(),
|
||||
readable_roots: Vec::new(),
|
||||
writable_roots: Vec::new(),
|
||||
unreadable_roots: Vec::new(),
|
||||
unreadable_globs: self.get_unreadable_globs_with_cwd(cwd),
|
||||
glob_scan_max_depth: self.glob_scan_max_depth,
|
||||
};
|
||||
if resolved.has_full_disk_read_access && resolved.has_full_disk_write_access {
|
||||
return Ok(resolved);
|
||||
}
|
||||
let entries = self.resolved_entries_with_cwd(cwd);
|
||||
if entries.is_empty() {
|
||||
return Ok(resolved);
|
||||
}
|
||||
|
||||
let context = LocalPolicyContext::new(cwd);
|
||||
let matching = context
|
||||
.as_ref()
|
||||
.and_then(|context| self.prepare_local_matching(&context.as_context()).ok());
|
||||
if let Some(matching) = &matching {
|
||||
if !resolved.has_full_disk_read_access {
|
||||
resolved.readable_roots = Self::readable_roots(&entries, matching);
|
||||
}
|
||||
if !resolved.has_full_disk_write_access
|
||||
&& entries.iter().any(|entry| entry.access.can_write())
|
||||
{
|
||||
resolved.writable_roots = Self::writable_roots(cwd, &entries, matching, projection);
|
||||
}
|
||||
}
|
||||
// If the matcher couldn't be prepared, withhold grants but keep explicit denials.
|
||||
resolved.unreadable_roots =
|
||||
Self::unreadable_roots(cwd, &entries, matching.as_ref(), projection);
|
||||
Ok(resolved)
|
||||
}
|
||||
}
|
||||
260
codex-rs/protocol/src/permissions/local_aliases.rs
Normal file
260
codex-rs/protocol/src/permissions/local_aliases.rs
Normal file
@@ -0,0 +1,260 @@
|
||||
//! Prepare local policy paths in the sandbox's trusted system-alias namespace.
|
||||
//! Normalize grants and restrictions once per operation without resolving mutable symlinks.
|
||||
//! Check native macOS ASCII aliases before approving protected metadata writes.
|
||||
//! 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;
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::PROTECTED_METADATA_PATH_NAMES;
|
||||
use super::local_temporary_directories;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::borrow::Cow;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::ffi::CString;
|
||||
use std::io;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// 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. Metadata checks also account for native ASCII
|
||||
/// case aliases without changing executor-independent path comparisons.
|
||||
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 failures to establish native path equivalence.
|
||||
pub fn can_write_path(&self, path: &PathUri) -> io::Result<bool> {
|
||||
self.with_path(path, |path| -> io::Result<bool> {
|
||||
let writable = self.policy.can_write_path(path, &self.context);
|
||||
#[cfg(target_os = "macos")]
|
||||
if writable
|
||||
&& !self
|
||||
.policy
|
||||
.has_full_disk_write_access_with_context(&self.context)
|
||||
{
|
||||
let native_path = path.to_abs_path()?;
|
||||
for (root, access) in self.policy.resolved_entries(&self.context) {
|
||||
if !access.can_write() || root.is_opaque() {
|
||||
continue;
|
||||
}
|
||||
let root = root.to_abs_path()?;
|
||||
let Some(candidate) = normalize_metadata_case_alias(&native_path, &root)?
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// This second policy view may only deny an already allowed write.
|
||||
// Normalize both candidate and entries so explicit metadata grants
|
||||
// and narrower restrictions keep their precedence.
|
||||
let mut policy = self.policy.clone().into_owned();
|
||||
for entry in &mut policy.entries {
|
||||
if let FileSystemPath::Path { path } = &mut entry.path
|
||||
&& let Some(normalized) =
|
||||
normalize_metadata_case_alias(&path.to_abs_path()?, &root)?
|
||||
{
|
||||
*path = PathUri::from(normalized);
|
||||
}
|
||||
}
|
||||
if !policy.can_write_path(&PathUri::from(candidate), &self.context) {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(writable)
|
||||
})?
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
// Match only ASCII case aliases leading to protected metadata. Each differing
|
||||
// component is checked against its containing filesystem, including ancestors
|
||||
// above mount points. Mutable symlink targets are never substituted into paths.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn normalize_metadata_case_alias(
|
||||
path: &AbsolutePathBuf,
|
||||
root: &AbsolutePathBuf,
|
||||
) -> io::Result<Option<AbsolutePathBuf>> {
|
||||
let mut relative = path.components();
|
||||
let Some(Component::Normal(name)) = relative.nth(root.components().count()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(metadata_name) = PROTECTED_METADATA_PATH_NAMES
|
||||
.iter()
|
||||
.find(|metadata| name.as_bytes().eq_ignore_ascii_case(metadata.as_bytes()))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut parent = PathBuf::new();
|
||||
for (expected, actual) in root.components().zip(path.components()) {
|
||||
if expected != actual
|
||||
&& (!expected
|
||||
.as_os_str()
|
||||
.as_bytes()
|
||||
.eq_ignore_ascii_case(actual.as_os_str().as_bytes())
|
||||
|| !is_case_insensitive_filesystem(&parent)?)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
parent.push(expected.as_os_str());
|
||||
}
|
||||
// Exact metadata names still need root alias normalization even when the
|
||||
// metadata's own filesystem is case-sensitive.
|
||||
if name.as_bytes() != metadata_name.as_bytes()
|
||||
&& !is_case_insensitive_filesystem(root.as_path())?
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(root.join(*metadata_name).join(relative.as_path())))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn is_case_insensitive_filesystem(path: &Path) -> io::Result<bool> {
|
||||
// Missing paths inherit their nearest existing ancestor's semantics.
|
||||
// An unknown result must never authorize a protected metadata write.
|
||||
for ancestor in path.ancestors() {
|
||||
let path = CString::new(ancestor.as_os_str().as_bytes())?;
|
||||
// SAFETY: path is NUL-terminated and __error points to this thread's
|
||||
// errno. Reset it to distinguish an unavailable value from a failure.
|
||||
let sensitivity = unsafe {
|
||||
*libc::__error() = 0;
|
||||
libc::pathconf(path.as_ptr(), libc::_PC_CASE_SENSITIVE)
|
||||
};
|
||||
match sensitivity {
|
||||
0 => return Ok(true),
|
||||
1 => return Ok(false),
|
||||
-1 => {
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(0) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"filesystem case sensitivity is unavailable",
|
||||
));
|
||||
}
|
||||
if error.kind() != io::ErrorKind::NotFound {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
value => {
|
||||
return Err(io::Error::other(format!(
|
||||
"unexpected filesystem case sensitivity: {value}",
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"no existing metadata parent",
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "macos"))]
|
||||
#[path = "local_aliases_tests.rs"]
|
||||
mod tests;
|
||||
163
codex-rs/protocol/src/permissions/local_aliases_tests.rs
Normal file
163
codex-rs/protocol/src/permissions/local_aliases_tests.rs
Normal file
@@ -0,0 +1,163 @@
|
||||
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(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_metadata_case_aliases_respect_filesystem_and_explicit_grants() -> anyhow::Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let parent = PathUri::from_host_native_path(directory.path().canonicalize()?)?;
|
||||
let workspace = parent.join("workspace")?.to_abs_path()?;
|
||||
std::fs::create_dir(&workspace)?;
|
||||
std::fs::create_dir(workspace.join(".git"))?;
|
||||
let case_insensitive = workspace.join(".GIT").exists();
|
||||
let root = PathUri::from_host_native_path(&workspace)?;
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &root,
|
||||
workspace_roots: std::slice::from_ref(&root),
|
||||
user_home_dir: None,
|
||||
temporary_directories: None,
|
||||
};
|
||||
let policy = FileSystemSandboxPolicy::restricted(vec![
|
||||
FileSystemSandboxEntry::new(parent.clone().into(), FileSystemAccessMode::Write),
|
||||
FileSystemSandboxEntry::new(root.clone().into(), FileSystemAccessMode::Write),
|
||||
]);
|
||||
let matching = policy.prepare_local_matching(&context)?;
|
||||
for relative in [
|
||||
".GIT/config",
|
||||
".CoDeX/config.toml",
|
||||
".AGENTS/new",
|
||||
".AWS/config",
|
||||
] {
|
||||
let path = root.join(relative)?;
|
||||
assert_eq!(
|
||||
(
|
||||
matching.can_write_path(&path)?,
|
||||
policy.can_write_path(&path, &context),
|
||||
),
|
||||
(!case_insensitive, true),
|
||||
"local aliases must not change executor-independent matching: {relative}",
|
||||
);
|
||||
}
|
||||
let root_alias = parent.join("WORKSPACE")?;
|
||||
for relative in [".GIT/config", ".git/config", ".CoDeX/config.toml"] {
|
||||
let path = root_alias.join(relative)?;
|
||||
assert_eq!(
|
||||
(
|
||||
matching.can_write_path(&path)?,
|
||||
policy.can_write_path(&path, &context),
|
||||
),
|
||||
(!case_insensitive, true),
|
||||
"a broader grant must not bypass metadata protection via a root alias: {relative}",
|
||||
);
|
||||
}
|
||||
for name in [".git", ".GIT"] {
|
||||
let mut explicitly_writable = policy.clone();
|
||||
explicitly_writable
|
||||
.entries
|
||||
.push(FileSystemSandboxEntry::new(
|
||||
root.join(name)?.into(),
|
||||
FileSystemAccessMode::Write,
|
||||
));
|
||||
let matching = explicitly_writable.prepare_local_matching(&context)?;
|
||||
for spelling in [&root, &root_alias] {
|
||||
assert!(
|
||||
matching.can_write_path(&spelling.join(".GIT/config")?)?,
|
||||
"explicit metadata grant must remain effective: {name}",
|
||||
);
|
||||
}
|
||||
}
|
||||
for (grant, restriction, candidate) in [
|
||||
(".git", ".GIT/private", ".git/private"),
|
||||
(".GIT", ".git/private", ".GIT/private"),
|
||||
] {
|
||||
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Deny] {
|
||||
let mut restricted = policy.clone();
|
||||
restricted.entries.extend([
|
||||
FileSystemSandboxEntry::new(root.join(grant)?.into(), FileSystemAccessMode::Write),
|
||||
FileSystemSandboxEntry::new(root.join(restriction)?.into(), access),
|
||||
]);
|
||||
assert_eq!(
|
||||
restricted
|
||||
.prepare_local_matching(&context)?
|
||||
.can_write_path(&root.join(candidate)?)?,
|
||||
!case_insensitive,
|
||||
"narrower metadata restrictions must retain precedence: {restriction}",
|
||||
);
|
||||
}
|
||||
}
|
||||
let missing_root = root.join("missing")?;
|
||||
let missing_policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry::new(
|
||||
missing_root.clone().into(),
|
||||
FileSystemAccessMode::Write,
|
||||
)]);
|
||||
assert_eq!(
|
||||
missing_policy
|
||||
.prepare_local_matching(&context)?
|
||||
.can_write_path(&missing_root.join(".GIT/config")?)?,
|
||||
!case_insensitive,
|
||||
);
|
||||
assert!(matching.can_write_path(&root.join("nested/.GIT/config")?)?);
|
||||
Ok(())
|
||||
}
|
||||
266
codex-rs/protocol/src/permissions/target.rs
Normal file
266
codex-rs/protocol/src/permissions/target.rs
Normal file
@@ -0,0 +1,266 @@
|
||||
//! Executor-context policy operations that never consult controller paths or environment.
|
||||
|
||||
use super::FileSystemAccessMode;
|
||||
use super::FileSystemPath;
|
||||
use super::FileSystemSandboxEntry;
|
||||
use super::FileSystemSandboxKind;
|
||||
use super::FileSystemSandboxPolicy;
|
||||
use super::FileSystemSandboxPolicyContext;
|
||||
use super::FileSystemSpecialPath;
|
||||
use super::InvalidDenyReadGlobBehavior;
|
||||
use super::PROJECT_ROOTS_GLOB_PATTERN_PREFIX;
|
||||
use super::PROTECTED_METADATA_PATH_NAMES;
|
||||
use super::ReadDenyMatcher;
|
||||
use super::deny_read_validator::DenyReadValidator;
|
||||
use super::deny_read_validator::has_context_read_denials;
|
||||
use super::file_system_root;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::collections::HashSet;
|
||||
|
||||
const INVALID_PATH: &str = "managed filesystem denial cannot be materialized safely";
|
||||
const SHADOWED: &str = "managed filesystem denial is shadowed by a selected profile grant";
|
||||
|
||||
impl ReadDenyMatcher {
|
||||
/// Builds a strict matcher using only the supplied execution-host paths.
|
||||
pub fn try_new_with_context(
|
||||
policy: &FileSystemSandboxPolicy,
|
||||
context: &FileSystemSandboxPolicyContext<'_>,
|
||||
) -> Result<Option<Self>, String> {
|
||||
if !has_context_read_denials(policy, context) {
|
||||
return Ok(None);
|
||||
}
|
||||
validate_context_paths(policy, context)?;
|
||||
let prepared =
|
||||
policy.prepare_deny_read_matcher(context, InvalidDenyReadGlobBehavior::ReturnError)?;
|
||||
Ok(Some(Self {
|
||||
native_cwd: None,
|
||||
user_home_dir: None,
|
||||
temporary_directories: Vec::new(),
|
||||
prepared,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl FileSystemSandboxPolicy {
|
||||
/// Grants root and root-metadata write for an approved command unless explicitly denied.
|
||||
/// If a retained denial cannot be resolved or denies the root, keep the original policy.
|
||||
pub fn for_approved_command(&self, context: &FileSystemSandboxPolicyContext<'_>) -> Self {
|
||||
if self.kind != FileSystemSandboxKind::Restricted {
|
||||
return self.clone();
|
||||
}
|
||||
let mut approved = Self::restricted(vec![FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
FileSystemAccessMode::Write,
|
||||
)]);
|
||||
approved.preserve_deny_read_restrictions_from(self);
|
||||
if context.workspace_roots.is_empty()
|
||||
&& approved.entries.iter().any(|entry| {
|
||||
matches!(
|
||||
&entry.path,
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::ProjectRoots { .. }
|
||||
}
|
||||
) || matches!(
|
||||
&entry.path,
|
||||
FileSystemPath::GlobPattern { pattern }
|
||||
if pattern.starts_with(PROJECT_ROOTS_GLOB_PATTERN_PREFIX)
|
||||
)
|
||||
})
|
||||
{
|
||||
return self.clone();
|
||||
}
|
||||
let Some(mut approved) =
|
||||
approved.try_materialize_project_roots_with_path_uris(context.workspace_roots)
|
||||
else {
|
||||
return self.clone();
|
||||
};
|
||||
let Some(root) = file_system_root(context) else {
|
||||
return self.clone();
|
||||
};
|
||||
let Ok(matcher) = ReadDenyMatcher::try_new_with_context(&approved, context) else {
|
||||
return self.clone();
|
||||
};
|
||||
if !approved.resolve_access(&root, context).can_write()
|
||||
|| matcher
|
||||
.as_ref()
|
||||
.is_some_and(|matcher| matcher.is_read_denied_uri(&root, context))
|
||||
{
|
||||
return self.clone();
|
||||
}
|
||||
for name in PROTECTED_METADATA_PATH_NAMES {
|
||||
let Ok(path) = root.join_descendant(name) else {
|
||||
return self.clone();
|
||||
};
|
||||
if !matcher
|
||||
.as_ref()
|
||||
.is_some_and(|matcher| matcher.is_read_denied_uri(&path, context))
|
||||
{
|
||||
approved.entries.push(FileSystemSandboxEntry::new(
|
||||
path.into(),
|
||||
FileSystemAccessMode::Write,
|
||||
));
|
||||
}
|
||||
}
|
||||
approved
|
||||
}
|
||||
|
||||
/// Checks exact-root read access using paths owned by the execution host.
|
||||
/// Deny glob enforcement is checked separately with [`ReadDenyMatcher`].
|
||||
pub fn can_read_path(
|
||||
&self,
|
||||
path: &PathUri,
|
||||
context: &FileSystemSandboxPolicyContext<'_>,
|
||||
) -> bool {
|
||||
self.resolve_access(path, context).can_read()
|
||||
}
|
||||
|
||||
/// Preserves workspace-root symbols and adds their executor-owned concrete paths.
|
||||
/// Legacy home-relative workspace denials clear all grants when their target is unknown.
|
||||
pub fn with_materialized_project_roots_for_path_uris(mut self, roots: &[PathUri]) -> Self {
|
||||
let Some(materialized) = self
|
||||
.clone()
|
||||
.try_materialize_project_roots_with_path_uris(roots)
|
||||
else {
|
||||
return Self::restricted(Vec::new());
|
||||
};
|
||||
for entry in materialized.entries {
|
||||
if !self.entries.contains(&entry) {
|
||||
self.entries.push(entry);
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Builds workspace-write defaults without inspecting the execution host's filesystem.
|
||||
pub fn workspace_write_with_path_uris(
|
||||
roots: &[PathUri],
|
||||
exclude_tmpdir_env_var: bool,
|
||||
exclude_slash_tmp: bool,
|
||||
) -> Self {
|
||||
Self::workspace_write(&[], exclude_tmpdir_env_var, exclude_slash_tmp)
|
||||
.with_materialized_project_roots_for_path_uris(roots)
|
||||
}
|
||||
|
||||
/// Returns explicitly denied roots using only the selected executor's paths.
|
||||
/// A filesystem-root denial is omitted so it does not obscure narrower readable paths.
|
||||
/// Fails rather than omit a denied temporary directory the executor did not report.
|
||||
pub fn get_unreadable_roots_with_context(
|
||||
&self,
|
||||
context: &FileSystemSandboxPolicyContext<'_>,
|
||||
) -> Result<Vec<PathUri>, String> {
|
||||
if !matches!(self.kind, FileSystemSandboxKind::Restricted) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if context.temporary_directories.is_none()
|
||||
&& self.entries.iter().any(|entry| {
|
||||
entry.access == FileSystemAccessMode::Deny
|
||||
&& matches!(
|
||||
&entry.path,
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Tmpdir
|
||||
}
|
||||
)
|
||||
})
|
||||
{
|
||||
return Err("executor did not report its denied temporary directories".into());
|
||||
}
|
||||
let filesystem_root = file_system_root(context);
|
||||
let mut seen = HashSet::new();
|
||||
Ok(self
|
||||
.resolved_entries(context)
|
||||
.into_iter()
|
||||
.filter(|(path, access)| {
|
||||
*access == FileSystemAccessMode::Deny
|
||||
&& !filesystem_root
|
||||
.as_ref()
|
||||
.is_some_and(|root| path.starts_with(root) && root.starts_with(path))
|
||||
&& seen.insert(path.clone())
|
||||
})
|
||||
.map(|(path, _)| path)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Resolves deny glob text using the execution host's convention and home.
|
||||
pub fn get_unreadable_globs_with_context(
|
||||
&self,
|
||||
context: &FileSystemSandboxPolicyContext<'_>,
|
||||
) -> Result<Vec<String>, String> {
|
||||
self.deny_read_globs(context)
|
||||
}
|
||||
|
||||
/// Checks the existing Core rules for required entries and readable concrete paths.
|
||||
///
|
||||
/// Sandbox-mode selection and native glob expansion remain caller-owned.
|
||||
pub fn validate_managed_deny_read(
|
||||
&self,
|
||||
required: &Self,
|
||||
context: &FileSystemSandboxPolicyContext<'_>,
|
||||
) -> Result<(), String> {
|
||||
DenyReadValidator::new(required, context)?
|
||||
.validate(self, context)
|
||||
.map_err(|_| SHADOWED.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_context_paths(
|
||||
policy: &FileSystemSandboxPolicy,
|
||||
context: &FileSystemSandboxPolicyContext<'_>,
|
||||
) -> Result<(), String> {
|
||||
let convention = context.cwd.infer_path_convention().ok_or(INVALID_PATH)?;
|
||||
let valid = |path: &PathUri| {
|
||||
path.infer_path_convention() == Some(convention) && path.lexical_depth().is_some()
|
||||
};
|
||||
if !valid(context.cwd) || context.workspace_roots.iter().any(|path| !valid(path)) {
|
||||
return Err(INVALID_PATH.into());
|
||||
}
|
||||
for entry in &policy.entries {
|
||||
match &entry.path {
|
||||
FileSystemPath::Path { path } if !valid(path) => return Err(INVALID_PATH.into()),
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Tmpdir,
|
||||
} => {
|
||||
let directories = context.temporary_directories.ok_or(
|
||||
"executor temporary-directory metadata is unavailable for managed filesystem denials",
|
||||
)?;
|
||||
if directories.iter().any(|path| !valid(path)) {
|
||||
return Err(
|
||||
"executor temporary-directory metadata cannot be materialized safely"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
FileSystemPath::Special {
|
||||
value:
|
||||
FileSystemSpecialPath::ProjectRoots {
|
||||
subpath: Some(subpath),
|
||||
},
|
||||
} if context
|
||||
.workspace_roots
|
||||
.iter()
|
||||
.any(|root| root.join(subpath).is_err()) =>
|
||||
{
|
||||
return Err(INVALID_PATH.into());
|
||||
}
|
||||
FileSystemPath::GlobPattern { pattern }
|
||||
if (pattern.starts_with("~/")
|
||||
|| convention == PathConvention::Windows && pattern.starts_with("~\\"))
|
||||
&& !context.user_home_dir.is_some_and(valid) =>
|
||||
{
|
||||
return Err(INVALID_PATH.into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "target_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "target_approved_materialization_tests.rs"]
|
||||
mod approved_materialization_tests;
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Approved commands widen filesystem access without weakening explicit read denials.
|
||||
|
||||
use super::*;
|
||||
use crate::permissions::FileSystemAccessMode::Deny;
|
||||
use crate::permissions::FileSystemAccessMode::Read;
|
||||
use crate::permissions::FileSystemAccessMode::Write;
|
||||
use crate::permissions::PROTECTED_METADATA_PATH_NAMES;
|
||||
use crate::permissions::RawFileSystemSandboxPolicy;
|
||||
use crate::permissions::project_roots_glob_pattern;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
|
||||
fn uri(input: &str) -> PathUri {
|
||||
PathUri::parse(input).unwrap()
|
||||
}
|
||||
|
||||
fn entry(path: impl Into<FileSystemPath>, access: FileSystemAccessMode) -> FileSystemSandboxEntry {
|
||||
FileSystemSandboxEntry::new(path.into(), access)
|
||||
}
|
||||
|
||||
fn workspace(subpath: &str) -> FileSystemPath {
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::project_roots(Some(subpath.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn glob(pattern: String) -> FileSystemPath {
|
||||
FileSystemPath::GlobPattern { pattern }
|
||||
}
|
||||
|
||||
fn context<'a>(cwd: &'a PathUri, roots: &'a [PathUri]) -> FileSystemSandboxPolicyContext<'a> {
|
||||
FileSystemSandboxPolicyContext {
|
||||
cwd,
|
||||
workspace_roots: roots,
|
||||
user_home_dir: None,
|
||||
temporary_directories: Some(&[]),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approved_command_grants_root_metadata_unless_explicitly_denied() {
|
||||
for path in [
|
||||
"file:///work/repo",
|
||||
"file:///C:/work/repo",
|
||||
"file://server/share/repo",
|
||||
] {
|
||||
let cwd = uri(path);
|
||||
let context = context(&cwd, std::slice::from_ref(&cwd));
|
||||
let root = file_system_root(&context).unwrap();
|
||||
let private = cwd.join("private").unwrap();
|
||||
let pattern = project_roots_glob_pattern(Path::new("**/*.env"));
|
||||
let mut policy = FileSystemSandboxPolicy::read_only();
|
||||
policy.entries.extend([
|
||||
entry(cwd.clone(), Write),
|
||||
entry(workspace("private"), Deny),
|
||||
entry(private.join("public").unwrap(), Read),
|
||||
entry(private.join("writable").unwrap(), Write),
|
||||
entry(glob(pattern), Deny),
|
||||
]);
|
||||
let approved = policy.for_approved_command(&context);
|
||||
let mut expected = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
Write,
|
||||
),
|
||||
entry(private, Deny),
|
||||
entry(
|
||||
glob(cwd.join("**/*.env").unwrap().inferred_native_path_string()),
|
||||
Deny,
|
||||
),
|
||||
]);
|
||||
expected.entries.extend(
|
||||
PROTECTED_METADATA_PATH_NAMES
|
||||
.iter()
|
||||
.map(|name| entry(root.join_descendant(name).unwrap(), Write)),
|
||||
);
|
||||
assert_eq!(approved, expected);
|
||||
let raw = RawFileSystemSandboxPolicy::try_from(approved.clone()).unwrap();
|
||||
let wire: RawFileSystemSandboxPolicy =
|
||||
serde_json::from_value(serde_json::to_value(raw).unwrap()).unwrap();
|
||||
assert_eq!(FileSystemSandboxPolicy::try_from(wire).unwrap(), approved);
|
||||
for name in PROTECTED_METADATA_PATH_NAMES {
|
||||
assert!(approved.can_write_path(&root.join_descendant(name).unwrap(), &context));
|
||||
}
|
||||
assert!(approved.can_write_path(&cwd.join(".git/FETCH_HEAD").unwrap(), &context));
|
||||
let matcher = ReadDenyMatcher::try_new_with_context(&approved, &context)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
for denied in [
|
||||
"private/public/file",
|
||||
"private/writable/file",
|
||||
"nested/secret.env",
|
||||
] {
|
||||
assert!(
|
||||
matcher.is_read_denied_uri(&cwd.join(denied).unwrap(), &context),
|
||||
"{path}: {denied}"
|
||||
);
|
||||
}
|
||||
|
||||
let root_path = |name| root.join_descendant(name).unwrap();
|
||||
let ordinary = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(root.clone(), Write),
|
||||
entry(root_path(".git"), Deny),
|
||||
entry(
|
||||
glob(root_path(".agent?").inferred_native_path_string()),
|
||||
Deny,
|
||||
),
|
||||
entry(root_path(".codex/private"), Deny),
|
||||
entry(
|
||||
glob(root_path(".codex/*.env").inferred_native_path_string()),
|
||||
Deny,
|
||||
),
|
||||
]);
|
||||
let approved = ordinary.for_approved_command(&context);
|
||||
let metadata_paths = [".git", ".agents", ".codex"].map(root_path);
|
||||
assert_eq!(
|
||||
metadata_paths
|
||||
.each_ref()
|
||||
.map(|path| ordinary.can_write_path(path, &context)),
|
||||
[false, false, false],
|
||||
);
|
||||
assert_eq!(
|
||||
metadata_paths
|
||||
.each_ref()
|
||||
.map(|path| approved.can_write_path(path, &context)),
|
||||
[false, false, true],
|
||||
);
|
||||
assert!(approved.can_write_path(&root_path(".codex/public"), &context));
|
||||
assert!(!approved.can_write_path(&root_path(".codex/private/file"), &context));
|
||||
let matcher = ReadDenyMatcher::try_new_with_context(&approved, &context)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
[
|
||||
".git",
|
||||
".agents",
|
||||
".codex/private/file",
|
||||
".codex/secret.env",
|
||||
".codex/public"
|
||||
]
|
||||
.map(|path| matcher.is_read_denied_uri(&root_path(path), &context)),
|
||||
[true, true, true, true, false],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn linux_root_metadata_writes_inherit_the_root_without_reopening_other_paths() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let cwd = temp.path().canonicalize().unwrap();
|
||||
let root = uri("file:///");
|
||||
let mut policy = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(root.clone(), Write),
|
||||
entry(
|
||||
PathUri::from_host_native_path(cwd.join("private")).unwrap(),
|
||||
Deny,
|
||||
),
|
||||
]);
|
||||
let roots = policy.get_writable_roots_with_cwd_inheriting_root_metadata(&cwd);
|
||||
assert_eq!(
|
||||
roots[0].protected_metadata_names,
|
||||
PROTECTED_METADATA_PATH_NAMES
|
||||
.iter()
|
||||
.map(std::string::ToString::to_string)
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
|
||||
let metadata = PROTECTED_METADATA_PATH_NAMES
|
||||
.iter()
|
||||
.map(|name| entry(root.join_descendant(name).unwrap(), Write))
|
||||
.collect::<Vec<_>>();
|
||||
policy.entries.extend(metadata.clone());
|
||||
let roots = policy.get_writable_roots_with_cwd_inheriting_root_metadata(&cwd);
|
||||
assert_eq!(
|
||||
roots
|
||||
.iter()
|
||||
.map(|root| root.root.as_path())
|
||||
.collect::<Vec<_>>(),
|
||||
[Path::new("/")],
|
||||
);
|
||||
assert!(roots[0].protected_metadata_names.is_empty());
|
||||
|
||||
let standalone = FileSystemSandboxPolicy::restricted(metadata);
|
||||
assert_eq!(
|
||||
standalone.get_writable_roots_with_cwd_inheriting_root_metadata(&cwd),
|
||||
standalone.get_writable_roots_with_cwd(&cwd),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approved_command_discards_other_volume_grants_before_materialization() {
|
||||
let cwd = uri("file:///C:/run");
|
||||
let workspace_root = uri("file:///C:/work");
|
||||
let context = context(&cwd, std::slice::from_ref(&workspace_root));
|
||||
let mut policy = FileSystemSandboxPolicy::read_only();
|
||||
policy.entries.extend([
|
||||
entry(workspace(r"D:\vault"), Read),
|
||||
entry(uri("file:///D:/scoped"), Write),
|
||||
entry(workspace("private"), Deny),
|
||||
]);
|
||||
let approved = policy.for_approved_command(&context);
|
||||
assert_eq!(
|
||||
[
|
||||
"file:///C:/work/public",
|
||||
"file:///C:/work/private/file",
|
||||
"file:///D:/scoped"
|
||||
]
|
||||
.map(|path| approved.resolve_access(&uri(path), &context)),
|
||||
[Write, Deny, Deny],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approved_command_declines_root_or_unresolvable_denials() {
|
||||
for path in ["file:///work/repo", "file:///C:/work/repo"] {
|
||||
let cwd = uri(path);
|
||||
let known = context(&cwd, std::slice::from_ref(&cwd));
|
||||
let root = file_system_root(&known).unwrap();
|
||||
for (context, denied) in [
|
||||
(
|
||||
known,
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
),
|
||||
(known, root.clone().into()),
|
||||
(known, glob(root.inferred_native_path_string())),
|
||||
(known, glob("secrets/[z-a]".into())),
|
||||
(known, workspace("~/private")),
|
||||
(context(&cwd, &[]), workspace("private")),
|
||||
(
|
||||
context(&cwd, &[]),
|
||||
glob(project_roots_glob_pattern(Path::new("**/*.env"))),
|
||||
),
|
||||
] {
|
||||
let mut policy = FileSystemSandboxPolicy::read_only();
|
||||
policy
|
||||
.entries
|
||||
.extend([entry(denied, Deny), entry(cwd.clone(), Write)]);
|
||||
assert_eq!(policy.for_approved_command(&context), policy);
|
||||
}
|
||||
}
|
||||
}
|
||||
449
codex-rs/protocol/src/permissions/target_tests.rs
Normal file
449
codex-rs/protocol/src/permissions/target_tests.rs
Normal file
@@ -0,0 +1,449 @@
|
||||
//! Regression coverage for remote path matching and managed-denial enforcement.
|
||||
|
||||
use super::*;
|
||||
use crate::permissions::FileSystemAccessMode;
|
||||
use crate::permissions::FileSystemSandboxEntry;
|
||||
use crate::permissions::PROTECTED_METADATA_PATH_NAMES;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn uri(input: &str) -> PathUri {
|
||||
PathUri::parse(input).unwrap()
|
||||
}
|
||||
|
||||
fn deny(path: FileSystemPath) -> FileSystemSandboxEntry {
|
||||
FileSystemSandboxEntry::new(path, FileSystemAccessMode::Deny)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_denials_use_target_paths_and_native_glob_semantics() {
|
||||
for base in [
|
||||
"file:///work/repo",
|
||||
"file:///Users/agent/repo",
|
||||
"file:///C:/work/repo",
|
||||
"file://server/share/repo",
|
||||
] {
|
||||
let cwd = uri(base);
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &cwd,
|
||||
workspace_roots: std::slice::from_ref(&cwd),
|
||||
user_home_dir: Some(&cwd),
|
||||
temporary_directories: Some(&[]),
|
||||
};
|
||||
let policy = FileSystemSandboxPolicy::restricted(vec![
|
||||
deny(FileSystemPath::Path {
|
||||
path: cwd.join("private").unwrap(),
|
||||
}),
|
||||
deny(FileSystemPath::GlobPattern {
|
||||
pattern: "~/secrets/*.key".into(),
|
||||
}),
|
||||
deny(FileSystemPath::GlobPattern {
|
||||
pattern: "nested/**/*.env".into(),
|
||||
}),
|
||||
]);
|
||||
let matcher = ReadDenyMatcher::try_new_with_context(&policy, &context)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
policy.get_unreadable_roots_with_context(&context),
|
||||
Ok(vec![cwd.join("private").unwrap()]),
|
||||
);
|
||||
for (path, expected) in [
|
||||
("private", true),
|
||||
("private/file", true),
|
||||
("private-other/file", false),
|
||||
("secrets/token.key", true),
|
||||
("secrets/nested/token.key", false),
|
||||
("nested/.env", true),
|
||||
("nested/deep/token.env", true),
|
||||
("public/file", false),
|
||||
] {
|
||||
assert_eq!(
|
||||
matcher.is_read_denied_uri(&cwd.join(path).unwrap(), &context),
|
||||
expected,
|
||||
"{base}: {path}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
matcher.is_read_denied_uri(&cwd.join("PRIVATE/file").unwrap(), &context),
|
||||
cwd.infer_path_convention() == Some(PathConvention::Windows),
|
||||
);
|
||||
assert!(matcher.is_read_denied_uri(&uri("file:///C:/foreign%2Fpath"), &context));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_denials_reject_concrete_read_and_write_grants() {
|
||||
for base in [
|
||||
"file:///work/repo",
|
||||
"file:///C:/work/repo",
|
||||
"file://server/share/repo",
|
||||
] {
|
||||
let cwd = uri(base);
|
||||
let private = cwd.join("private").unwrap();
|
||||
let required = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::Path {
|
||||
path: private.clone(),
|
||||
})]);
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &cwd,
|
||||
workspace_roots: std::slice::from_ref(&cwd),
|
||||
user_home_dir: None,
|
||||
temporary_directories: Some(&[]),
|
||||
};
|
||||
let mut policy = FileSystemSandboxPolicy::workspace_write_with_path_uris(
|
||||
&[],
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ true,
|
||||
);
|
||||
policy.entries.extend(required.entries.clone());
|
||||
assert_eq!(
|
||||
policy.validate_managed_deny_read(&required, &context),
|
||||
Ok(())
|
||||
);
|
||||
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Write] {
|
||||
let mut carveout = policy.clone();
|
||||
carveout.entries.push(FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Path {
|
||||
path: private.join("carveout").unwrap(),
|
||||
},
|
||||
access,
|
||||
));
|
||||
assert_eq!(
|
||||
carveout.validate_managed_deny_read(&required, &context),
|
||||
Err(SHADOWED.into())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_denials_preserve_native_metadata_read_rejections() {
|
||||
for base in [
|
||||
"file:///executor/home",
|
||||
"file:///C:/Users/executor",
|
||||
"file://server/share/executor",
|
||||
] {
|
||||
let extra_root = uri(base);
|
||||
let cwd = extra_root.join("workspace").unwrap();
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &cwd,
|
||||
workspace_roots: std::slice::from_ref(&cwd),
|
||||
user_home_dir: Some(&extra_root),
|
||||
temporary_directories: Some(&[]),
|
||||
};
|
||||
let legacy = FileSystemSandboxPolicy::workspace_write_with_path_uris(
|
||||
std::slice::from_ref(&extra_root),
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ true,
|
||||
);
|
||||
for name in [".codex", ".git"] {
|
||||
let denied_root = extra_root.join(name).unwrap();
|
||||
let child = denied_root.join("reopened").unwrap();
|
||||
for (path, expected_root_access) in [
|
||||
(
|
||||
FileSystemPath::Path {
|
||||
path: denied_root.clone(),
|
||||
},
|
||||
FileSystemAccessMode::Deny,
|
||||
),
|
||||
(
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: denied_root.join("*").unwrap().inferred_native_path_string(),
|
||||
},
|
||||
FileSystemAccessMode::Read,
|
||||
),
|
||||
] {
|
||||
let required = FileSystemSandboxPolicy::restricted(vec![deny(path)]);
|
||||
let mut policy = legacy.clone();
|
||||
policy.preserve_deny_read_restrictions_from(&required);
|
||||
assert_eq!(
|
||||
(
|
||||
policy.resolve_access(&denied_root, &context),
|
||||
policy.validate_managed_deny_read(&required, &context),
|
||||
),
|
||||
(
|
||||
expected_root_access,
|
||||
if expected_root_access == FileSystemAccessMode::Deny {
|
||||
Err(SHADOWED.into())
|
||||
} else {
|
||||
Ok(())
|
||||
},
|
||||
),
|
||||
"{base}: {name}",
|
||||
);
|
||||
let matcher = ReadDenyMatcher::try_new_with_context(&required, &context)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(matcher.is_read_denied_uri(&child, &context));
|
||||
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Write] {
|
||||
let mut reopened = policy.clone();
|
||||
reopened.entries.push(FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Path {
|
||||
path: child.clone(),
|
||||
},
|
||||
access,
|
||||
));
|
||||
assert_eq!(
|
||||
reopened.validate_managed_deny_read(&required, &context),
|
||||
Err(SHADOWED.into()),
|
||||
"{base}: {name}: {access}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_or_unresolvable_denials_fail_closed() {
|
||||
let cwd = uri("file:///work/repo");
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &cwd,
|
||||
workspace_roots: &[],
|
||||
user_home_dir: None,
|
||||
temporary_directories: Some(&[]),
|
||||
};
|
||||
for pattern in ["~/secrets/**", "secrets/[z-a]"] {
|
||||
let policy = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::GlobPattern {
|
||||
pattern: pattern.into(),
|
||||
})]);
|
||||
assert!(ReadDenyMatcher::try_new_with_context(&policy, &context).is_err());
|
||||
}
|
||||
let policy = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::Path {
|
||||
path: uri("file:///C:/private"),
|
||||
})]);
|
||||
assert!(ReadDenyMatcher::try_new_with_context(&policy, &context).is_err());
|
||||
let policy = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Tmpdir,
|
||||
})]);
|
||||
assert!(
|
||||
policy
|
||||
.get_unreadable_roots_with_context(&FileSystemSandboxPolicyContext {
|
||||
temporary_directories: None,
|
||||
..context
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slash_tmp_denials_follow_the_executor_convention() {
|
||||
let policy = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::SlashTmp,
|
||||
})]);
|
||||
for (base, active) in [("file:///work", true), ("file:///C:/work", false)] {
|
||||
let cwd = uri(base);
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &cwd,
|
||||
workspace_roots: &[],
|
||||
user_home_dir: None,
|
||||
temporary_directories: None,
|
||||
};
|
||||
let matcher = ReadDenyMatcher::try_new_with_context(&policy, &context).unwrap();
|
||||
assert_eq!(matcher.is_some(), active);
|
||||
if let Some(matcher) = matcher {
|
||||
assert!(matcher.is_read_denied_uri(&cwd.join("/tmp/file").unwrap(), &context));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Full-disk read policy shares the native check and ignores `:slash_tmp` only on Windows.
|
||||
#[test]
|
||||
fn full_disk_read_policy_uses_the_executor_convention() {
|
||||
use FileSystemAccessMode::Read;
|
||||
use FileSystemAccessMode::Write;
|
||||
use FileSystemSpecialPath::Minimal;
|
||||
use FileSystemSpecialPath::Root;
|
||||
use FileSystemSpecialPath::SlashTmp;
|
||||
use FileSystemSpecialPath::Tmpdir;
|
||||
|
||||
for (root_access, denial, posix, windows, unknown) in [
|
||||
(Read, None, true, true, true),
|
||||
(Read, Some(SlashTmp), false, true, false),
|
||||
(Read, Some(Tmpdir), false, false, false),
|
||||
(Write, Some(Minimal), false, false, false),
|
||||
(Write, Some(Root), false, false, false),
|
||||
] {
|
||||
let mut entries = vec![FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special { value: Root },
|
||||
root_access,
|
||||
)];
|
||||
if let Some(value) = denial {
|
||||
entries.push(deny(FileSystemPath::Special { value }));
|
||||
}
|
||||
let policy = FileSystemSandboxPolicy::restricted(entries);
|
||||
for (convention, expected) in [
|
||||
(Some(PathConvention::Posix), posix),
|
||||
(Some(PathConvention::Windows), windows),
|
||||
(None, unknown),
|
||||
] {
|
||||
assert_eq!(
|
||||
policy.has_full_disk_read_access_for_convention(convention),
|
||||
expected,
|
||||
"policy={policy:?}, convention={convention:?}",
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
policy.has_full_disk_read_access(),
|
||||
policy.has_full_disk_read_access_for_convention(Some(PathConvention::native())),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_workspace_write_keeps_metadata_protected() {
|
||||
let cwd = uri("file:///C:/repo");
|
||||
let extra = uri("file:///D:/extra");
|
||||
let policy = FileSystemSandboxPolicy::workspace_write_with_path_uris(
|
||||
std::slice::from_ref(&extra),
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ true,
|
||||
);
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &cwd,
|
||||
workspace_roots: std::slice::from_ref(&cwd),
|
||||
user_home_dir: None,
|
||||
temporary_directories: Some(&[]),
|
||||
};
|
||||
for name in PROTECTED_METADATA_PATH_NAMES {
|
||||
assert!(
|
||||
policy
|
||||
.entries
|
||||
.contains(&FileSystemSandboxEntry::skip_missing_path(
|
||||
FileSystemPath::Path {
|
||||
path: extra.join(name).unwrap()
|
||||
},
|
||||
FileSystemAccessMode::Read,
|
||||
))
|
||||
);
|
||||
}
|
||||
for root in [cwd.clone(), extra] {
|
||||
assert!(policy.can_write_path(&root.join("file").unwrap(), &context));
|
||||
for name in PROTECTED_METADATA_PATH_NAMES {
|
||||
let path = root.join(name).unwrap().join("file").unwrap();
|
||||
assert!(policy.can_read_path(&path, &context));
|
||||
assert!(!policy.can_write_path(&path, &context));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_globs_reject_metacharacters_in_home_and_cwd_facts() {
|
||||
for prefix in ["file:///home", "file:///C:/Users"] {
|
||||
let parent = uri(prefix);
|
||||
let directory = parent.join("sam[1]").unwrap();
|
||||
for (pattern, cwd, home) in [
|
||||
("~/private/*.key", &parent, Some(&directory)),
|
||||
("private/*.key", &directory, None),
|
||||
] {
|
||||
let policy =
|
||||
FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::GlobPattern {
|
||||
pattern: pattern.into(),
|
||||
})]);
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd,
|
||||
workspace_roots: std::slice::from_ref(&directory),
|
||||
user_home_dir: home,
|
||||
temporary_directories: None,
|
||||
};
|
||||
assert!(ReadDenyMatcher::try_new_with_context(&policy, &context).is_err());
|
||||
let matcher = ReadDenyMatcher::from_context(&policy, &context).unwrap();
|
||||
assert!(
|
||||
matcher.is_read_denied_uri(&directory.join("private/a.key").unwrap(), &context)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_globs_fail_closed_on_literal_root_metacharacters_on_every_host() {
|
||||
for prefix in ["file:///home", "file:///C:/Users"] {
|
||||
let root = uri(prefix).join("sam[1]").unwrap();
|
||||
let policy = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::GlobPattern {
|
||||
pattern: crate::permissions::project_roots_glob_pattern(std::path::Path::new(
|
||||
"private/*.key",
|
||||
)),
|
||||
})]);
|
||||
let materialized = policy
|
||||
.clone()
|
||||
.materialize_project_roots_with_path_uris(std::slice::from_ref(&root));
|
||||
assert_eq!(
|
||||
materialized,
|
||||
FileSystemSandboxPolicy::restricted(vec![deny(root.clone().into())]),
|
||||
);
|
||||
if let Ok(native_root) = root.to_abs_path() {
|
||||
assert_eq!(
|
||||
policy.materialize_project_roots_with_workspace_roots(&[native_root]),
|
||||
materialized,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materializing_legacy_home_relative_workspace_denials_removes_all_grants() {
|
||||
for (root, home) in [
|
||||
("file:///work/repo", "file:///home/sam"),
|
||||
("file:///C:/work/repo", "file:///D:/Users/sam"),
|
||||
] {
|
||||
let root = uri(root);
|
||||
let home = uri(home);
|
||||
let convention = root.infer_path_convention().unwrap();
|
||||
for subpath in ["~", "~/private/*.env", r"~\private", r"~\private\*.env"] {
|
||||
if convention.home_relative_suffix(subpath).is_none() {
|
||||
continue;
|
||||
}
|
||||
let denied_path = if subpath.contains('*') {
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: crate::permissions::project_roots_glob_pattern(std::path::Path::new(
|
||||
subpath,
|
||||
)),
|
||||
}
|
||||
} else {
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::ProjectRoots {
|
||||
subpath: Some(subpath.into()),
|
||||
},
|
||||
}
|
||||
};
|
||||
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(home.clone().into(), FileSystemAccessMode::Write),
|
||||
deny(denied_path),
|
||||
]);
|
||||
let mut materialized = vec![
|
||||
policy
|
||||
.clone()
|
||||
.materialize_project_roots_with_path_uris(std::slice::from_ref(&root)),
|
||||
policy
|
||||
.clone()
|
||||
.with_materialized_project_roots_for_path_uris(std::slice::from_ref(&root)),
|
||||
];
|
||||
if let Ok(native_root) = root.to_abs_path() {
|
||||
materialized.push(
|
||||
policy
|
||||
.clone()
|
||||
.materialize_project_roots_with_workspace_roots(std::slice::from_ref(
|
||||
&native_root,
|
||||
)),
|
||||
);
|
||||
materialized.push(policy.with_materialized_project_roots_for_workspace_roots(
|
||||
std::slice::from_ref(&native_root),
|
||||
));
|
||||
}
|
||||
for policy in materialized {
|
||||
assert_eq!(policy, FileSystemSandboxPolicy::restricted(Vec::new()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
44
codex-rs/protocol/src/permissions/windows_glob.rs
Normal file
44
codex-rs/protocol/src/permissions/windows_glob.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
//! Windows deny-glob scan bounds shared by policy validation and native ACL expansion.
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
|
||||
/// Literal scan root and maximum traversal depth for a Windows deny glob.
|
||||
pub struct WindowsDenyReadGlobScan<'a> {
|
||||
pub root: &'a str,
|
||||
pub pattern_suffix: &'a str,
|
||||
pub max_depth: Option<usize>,
|
||||
}
|
||||
|
||||
/// Plans lexical scan bounds without accessing the controller's filesystem.
|
||||
pub fn windows_deny_read_glob_scan(
|
||||
pattern: &str,
|
||||
configured_max_depth: Option<usize>,
|
||||
) -> WindowsDenyReadGlobScan<'_> {
|
||||
let first_glob = pattern.find(['*', '?', '[']).unwrap_or(pattern.len());
|
||||
let literal_prefix = &pattern[..first_glob];
|
||||
let (root, pattern_suffix) = match literal_prefix.rfind(['/', '\\']) {
|
||||
Some(index) => {
|
||||
let drive_root = index > 0 && literal_prefix.as_bytes()[index - 1] == b':';
|
||||
let end = if index == 0 || drive_root {
|
||||
index + 1
|
||||
} else {
|
||||
index
|
||||
};
|
||||
(&literal_prefix[..end], &pattern[index + 1..])
|
||||
}
|
||||
None => (".", pattern),
|
||||
};
|
||||
let components = PathConvention::Windows
|
||||
.path_segments(pattern_suffix)
|
||||
.filter(|component| !component.is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
let max_depth = if components.contains(&"**") {
|
||||
configured_max_depth
|
||||
} else {
|
||||
Some(configured_max_depth.map_or(components.len(), |depth| depth.min(components.len())))
|
||||
};
|
||||
WindowsDenyReadGlobScan {
|
||||
root,
|
||||
pattern_suffix,
|
||||
max_depth,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user