Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Harden unsandboxed patch filesystem access (#39659)

pakrym-oaie3e5ad28470f
diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock
index b780e2d1ec..471c342ff9 100644
--- a/codex-rs/Cargo.lock
+++ b/codex-rs/Cargo.lock
@@ -2713,6 +2713,7 @@ version = "0.0.0"
dependencies = [
"codex-connectors",
"codex-core-plugins",
+ "codex-file-system",
"codex-plugin",
"codex-utils-path-uri",
"serde_json",
diff --git a/codex-rs/app-server/src/request_processors/fs_processor.rs b/codex-rs/app-server/src/request_processors/fs_processor.rs
index c18300b1c1..5767af6124 100644
--- a/codex-rs/app-server/src/request_processors/fs_processor.rs
+++ b/codex-rs/app-server/src/request_processors/fs_processor.rs
@@ -68,7 +68,7 @@ impl FsRequestProcessor {
let path = PathUri::from_abs_path(&params.path);
let bytes = self
.file_system()?
- .read_file(&path, /*sandbox*/ None)
+ .read_file(&path, Default::default(), /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
Ok(FsReadFileResponse {
@@ -87,7 +87,7 @@ impl FsRequestProcessor {
})?;
let path = PathUri::from_abs_path(&params.path);
self.file_system()?
- .write_file(&path, bytes, /*sandbox*/ None)
+ .write_file(&path, bytes, Default::default(), /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
Ok(FsWriteFileResponse {})
@@ -103,6 +103,7 @@ impl FsRequestProcessor {
&path,
CreateDirectoryOptions {
recursive: params.recursive.unwrap_or(true),
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -118,7 +119,7 @@ impl FsRequestProcessor {
let path = PathUri::from_abs_path(&params.path);
let metadata = self
.file_system()?
- .get_metadata(&path, /*sandbox*/ None)
+ .get_metadata(&path, Default::default(), /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
Ok(FsGetMetadataResponse {
@@ -163,6 +164,7 @@ impl FsRequestProcessor {
RemoveOptions {
recursive: params.recursive.unwrap_or(true),
force: params.force.unwrap_or(true),
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
diff --git a/codex-rs/app-server/tests/suite/v2/executor_skills.rs b/codex-rs/app-server/tests/suite/v2/executor_skills.rs
index 018a0585da..2d138526d5 100644
--- a/codex-rs/app-server/tests/suite/v2/executor_skills.rs
+++ b/codex-rs/app-server/tests/suite/v2/executor_skills.rs
@@ -169,7 +169,10 @@ stream_max_retries = 0
file_system
.create_directory(
directory,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -194,7 +197,7 @@ stream_max_retries = 0
file_system.write_file(
&manifest_path,
br#"{"name":"demo-plugin"}"#.to_vec(),
- /*sandbox*/ None,
+ Default::default(), /*sandbox*/ None,
),
file_system.write_file(
&skill_path,
@@ -202,7 +205,7 @@ stream_max_retries = 0
"---\nname: deploy\ndescription: Deploy through the executor.\n---\n\n# Deploy\n\n{SKILL_MARKER}\n\nRead references/details.md.\n"
)
.into_bytes(),
- /*sandbox*/ None,
+ Default::default(), /*sandbox*/ None,
),
file_system.write_file(
&openai_yaml_path,
@@ -210,12 +213,12 @@ stream_max_retries = 0
"policy:\n allow_implicit_invocation: {allow_implicit_invocation}\n"
)
.into_bytes(),
- /*sandbox*/ None,
+ Default::default(), /*sandbox*/ None,
),
file_system.write_file(
&reference_path,
reference_contents.into_bytes(),
- /*sandbox*/ None,
+ Default::default(), /*sandbox*/ None,
),
)?;
#[cfg(unix)]
@@ -255,7 +258,10 @@ stream_max_retries = 0
file_system
.create_directory(
&skill_dir,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -267,6 +273,7 @@ stream_max_retries = 0
"x".repeat(1_025)
)
.into_bytes(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
diff --git a/codex-rs/app-server/tests/suite/v2/selected_environment.rs b/codex-rs/app-server/tests/suite/v2/selected_environment.rs
index cf653f25ad..d07ce4f048 100644
--- a/codex-rs/app-server/tests/suite/v2/selected_environment.rs
+++ b/codex-rs/app-server/tests/suite/v2/selected_environment.rs
@@ -112,6 +112,7 @@ async fn thread_start_reports_selected_environment_instruction_source() -> Resul
.write_file(
&agents_source,
AGENTS_INSTRUCTIONS.as_bytes().to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -250,7 +251,12 @@ async fn command_execution_notifications_preserve_selected_environment_paths() -
environment
.environment()
.get_filesystem()
- .write_file(&path, b"fn main() {}\n".to_vec(), /*sandbox*/ None)
+ .write_file(
+ &path,
+ b"fn main() {}\n".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await?;
(
path.inferred_native_path_string(),
diff --git a/codex-rs/app-server/tests/suite/v2/skills_list.rs b/codex-rs/app-server/tests/suite/v2/skills_list.rs
index 48d9ff46ae..26d135af21 100644
--- a/codex-rs/app-server/tests/suite/v2/skills_list.rs
+++ b/codex-rs/app-server/tests/suite/v2/skills_list.rs
@@ -841,7 +841,10 @@ enabled = true
file_system
.create_directory(
directory,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -850,6 +853,7 @@ enabled = true
.write_file(
&skill_dir.join("SKILL.md")?,
format!("---\nname: {name}\ndescription: {name}\n---\n").into_bytes(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -938,7 +942,10 @@ enabled = true
file_system
.create_directory(
&cwd.join(".git")?,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
diff --git a/codex-rs/apply-patch/src/file_update.rs b/codex-rs/apply-patch/src/file_update.rs
index d700570264..08bb0ebefe 100644
--- a/codex-rs/apply-patch/src/file_update.rs
+++ b/codex-rs/apply-patch/src/file_update.rs
@@ -1,5 +1,6 @@
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::FileSystemSandboxContext;
+use codex_exec_server::ReadFileOptions;
use codex_utils_path_uri::PathUri;
use similar::TextDiff;
@@ -27,17 +28,21 @@ pub(crate) async fn derive_new_contents_from_chunks(
chunks: &[UpdateFileChunk],
update_file_mode: ApplyPatchFileUpdateMode,
fs: &dyn ExecutorFileSystem,
+ follow_symlinks: bool,
sandbox: Option<&FileSystemSandboxContext>,
) -> std::result::Result<AppliedPatch, ApplyPatchError> {
- let original_contents = fs.read_file_text(path, sandbox).await.map_err(|err| {
- ApplyPatchError::IoError(IoError {
- context: format!(
- "Failed to read file to update {}",
- path.inferred_native_path_string()
- ),
- source: err,
- })
- })?;
+ let original_contents = fs
+ .read_file_text(path, ReadFileOptions { follow_symlinks }, sandbox)
+ .await
+ .map_err(|err| {
+ ApplyPatchError::IoError(IoError {
+ context: format!(
+ "Failed to read file to update {}",
+ path.inferred_native_path_string()
+ ),
+ source: err,
+ })
+ })?;
let path_text = path.inferred_native_path_string();
let new_contents = match update_file_mode {
@@ -311,7 +316,15 @@ async fn unified_diff_from_chunks_with_context_and_mode(
let AppliedPatch {
original_contents,
new_contents,
- } = derive_new_contents_from_chunks(path, chunks, update_file_mode, fs, sandbox).await?;
+ } = derive_new_contents_from_chunks(
+ path,
+ chunks,
+ update_file_mode,
+ fs,
+ /*follow_symlinks*/ true,
+ sandbox,
+ )
+ .await?;
let text_diff = TextDiff::from_lines(&original_contents, &new_contents);
let unified_diff = text_diff.unified_diff().context_radius(context).to_string();
Ok(ApplyPatchFileUpdate {
diff --git a/codex-rs/apply-patch/src/invocation.rs b/codex-rs/apply-patch/src/invocation.rs
index 41ee8b539a..5b805c30c6 100644
--- a/codex-rs/apply-patch/src/invocation.rs
+++ b/codex-rs/apply-patch/src/invocation.rs
@@ -244,12 +244,18 @@ async fn try_verify_apply_patch_args(
changes.insert(path, ApplyPatchFileChange::Add { content: contents });
}
Hunk::DeleteFile { .. } => {
- let content = fs.read_file_text(&path, sandbox).await.map_err(|source| {
- ApplyPatchError::IoError(IoError {
- context: format!("Failed to read {}", path.inferred_native_path_string()),
- source,
- })
- })?;
+ let content = fs
+ .read_file_text(&path, Default::default(), sandbox)
+ .await
+ .map_err(|source| {
+ ApplyPatchError::IoError(IoError {
+ context: format!(
+ "Failed to read {}",
+ path.inferred_native_path_string()
+ ),
+ source,
+ })
+ })?;
changes.insert(path, ApplyPatchFileChange::Delete { content });
}
Hunk::UpdateFile {
diff --git a/codex-rs/apply-patch/src/lib.rs b/codex-rs/apply-patch/src/lib.rs
index 5b5fac0683..0ee7a4e7ec 100644
--- a/codex-rs/apply-patch/src/lib.rs
+++ b/codex-rs/apply-patch/src/lib.rs
@@ -15,7 +15,10 @@ use anyhow::Result;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::FileSystemSandboxContext;
+use codex_exec_server::GetMetadataOptions;
+use codex_exec_server::ReadFileOptions;
use codex_exec_server::RemoveOptions;
+use codex_exec_server::WriteFileOptions;
use codex_utils_path_uri::PathUri;
use codex_utils_path_uri::PathUriParseError;
pub use parser::Hunk;
@@ -66,6 +69,23 @@ pub enum ApplyPatchFileUpdateMode {
PreserveLineEndings,
}
+/// Policy for one patch application. Standalone callers follow symlinks by default.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct ApplyPatchOptions {
+ pub update_file_mode: ApplyPatchFileUpdateMode,
+ /// Whether filesystem operations may resolve symlinks in any path component.
+ pub follow_symlinks: bool,
+}
+
+impl Default for ApplyPatchOptions {
+ fn default() -> Self {
+ Self {
+ update_file_mode: ApplyPatchFileUpdateMode::default(),
+ follow_symlinks: true,
+ }
+ }
+}
+
/// Reads the update mode selected for an arg0-dispatched `apply_patch` process.
#[doc(hidden)]
pub fn apply_patch_file_update_mode_from_env() -> ApplyPatchFileUpdateMode {
@@ -324,9 +344,9 @@ pub async fn apply_patch(
fs: &dyn ExecutorFileSystem,
sandbox: Option<&FileSystemSandboxContext>,
) -> Result<AppliedPatchDelta, ApplyPatchFailure> {
- apply_patch_with_mode(
+ apply_patch_with_options(
patch,
- ApplyPatchFileUpdateMode::default(),
+ ApplyPatchOptions::default(),
cwd,
stdout,
stderr,
@@ -336,11 +356,11 @@ pub async fn apply_patch(
.await
}
-/// Applies the patch using the selected file-update mode and prints the result
+/// Applies the patch using the selected options and prints the result
/// to stdout/stderr.
-pub async fn apply_patch_with_mode(
+pub async fn apply_patch_with_options(
patch: &str,
- update_file_mode: ApplyPatchFileUpdateMode,
+ options: ApplyPatchOptions,
cwd: &PathUri,
stdout: &mut impl std::io::Write,
stderr: &mut impl std::io::Write,
@@ -374,7 +394,7 @@ pub async fn apply_patch_with_mode(
}
};
- apply_hunks_with_mode(&hunks, update_file_mode, cwd, stdout, stderr, fs, sandbox).await
+ apply_hunks_with_options(&hunks, options, cwd, stdout, stderr, fs, sandbox).await
}
/// Applies hunks and continues to update stdout/stderr
@@ -386,9 +406,9 @@ pub async fn apply_hunks(
fs: &dyn ExecutorFileSystem,
sandbox: Option<&FileSystemSandboxContext>,
) -> Result<AppliedPatchDelta, ApplyPatchFailure> {
- apply_hunks_with_mode(
+ apply_hunks_with_options(
hunks,
- ApplyPatchFileUpdateMode::default(),
+ ApplyPatchOptions::default(),
cwd,
stdout,
stderr,
@@ -400,9 +420,9 @@ pub async fn apply_hunks(
/// Applies hunks using the selected file-update mode and continues to update
/// stdout/stderr.
-async fn apply_hunks_with_mode(
+async fn apply_hunks_with_options(
hunks: &[Hunk],
- update_file_mode: ApplyPatchFileUpdateMode,
+ options: ApplyPatchOptions,
cwd: &PathUri,
stdout: &mut impl std::io::Write,
stderr: &mut impl std::io::Write,
@@ -410,7 +430,7 @@ async fn apply_hunks_with_mode(
sandbox: Option<&FileSystemSandboxContext>,
) -> Result<AppliedPatchDelta, ApplyPatchFailure> {
let mut delta = AppliedPatchDelta::empty();
- match apply_hunks_to_files(hunks, update_file_mode, cwd, fs, sandbox, &mut delta).await {
+ match apply_hunks_to_files(hunks, options, cwd, fs, sandbox, &mut delta).await {
Ok(affected_paths) => {
print_summary(&affected_paths, stdout).map_err(|error| {
ApplyPatchFailure::new(ApplyPatchError::from(error), delta.clone())
@@ -449,12 +469,16 @@ pub struct AffectedPaths {
/// Returns an error if the patch could not be applied.
async fn apply_hunks_to_files(
hunks: &[Hunk],
- update_file_mode: ApplyPatchFileUpdateMode,
+ options: ApplyPatchOptions,
cwd: &PathUri,
fs: &dyn ExecutorFileSystem,
sandbox: Option<&FileSystemSandboxContext>,
delta: &mut AppliedPatchDelta,
) -> anyhow::Result<AffectedPaths> {
+ let ApplyPatchOptions {
+ update_file_mode,
+ follow_symlinks,
+ } = options;
if hunks.is_empty() {
anyhow::bail!("No files were modified.");
}
@@ -482,14 +506,20 @@ async fn apply_hunks_to_files(
let path_uri = hunk.resolve_path(cwd)?;
match hunk {
Hunk::AddFile { contents, .. } => {
- let overwritten_content =
- read_optional_file_text_for_delta(&path_uri, fs, sandbox, &mut delta.exact)
- .await;
+ let overwritten_content = read_optional_file_text_for_delta(
+ &path_uri,
+ fs,
+ follow_symlinks,
+ sandbox,
+ &mut delta.exact,
+ )
+ .await;
try_write!(
write_file_with_missing_parent_retry(
fs,
&path_uri,
contents.clone().into_bytes(),
+ follow_symlinks,
sandbox,
)
.await
@@ -504,12 +534,22 @@ async fn apply_hunks_to_files(
added.push(affected_path);
}
Hunk::DeleteFile { .. } => {
- note_existing_path_delta_support(&path_uri, fs, sandbox, &mut delta.exact).await;
- let deleted_content = fs.read_file_text(&path_uri, sandbox).await.ok();
+ note_existing_path_delta_support(
+ &path_uri,
+ fs,
+ follow_symlinks,
+ sandbox,
+ &mut delta.exact,
+ )
+ .await;
+ let deleted_content = fs
+ .read_file_text(&path_uri, ReadFileOptions { follow_symlinks }, sandbox)
+ .await
+ .ok();
if deleted_content.is_none() {
delta.exact = false;
}
- ensure_not_directory(&path_uri, fs, sandbox)
+ ensure_not_directory(&path_uri, fs, follow_symlinks, sandbox)
.await
.with_context(|| {
format!(
@@ -523,6 +563,7 @@ async fn apply_hunks_to_files(
RemoveOptions {
recursive: false,
force: false,
+ follow_symlinks,
},
sandbox,
)
@@ -538,6 +579,7 @@ async fn apply_hunks_to_files(
&path_uri,
deleted_content.as_deref(),
fs,
+ follow_symlinks,
sandbox,
)
.await;
@@ -554,7 +596,14 @@ async fn apply_hunks_to_files(
Hunk::UpdateFile {
move_path, chunks, ..
} => {
- note_existing_path_delta_support(&path_uri, fs, sandbox, &mut delta.exact).await;
+ note_existing_path_delta_support(
+ &path_uri,
+ fs,
+ follow_symlinks,
+ sandbox,
+ &mut delta.exact,
+ )
+ .await;
let AppliedPatch {
original_contents,
new_contents,
@@ -563,19 +612,26 @@ async fn apply_hunks_to_files(
chunks,
update_file_mode,
fs,
+ follow_symlinks,
sandbox,
)
.await?;
if let Some(dest) = move_path {
let dest_uri = cwd.join(&dest.to_string_lossy())?;
- let overwritten_move_content =
- read_optional_file_text_for_delta(&dest_uri, fs, sandbox, &mut delta.exact)
- .await;
+ let overwritten_move_content = read_optional_file_text_for_delta(
+ &dest_uri,
+ fs,
+ follow_symlinks,
+ sandbox,
+ &mut delta.exact,
+ )
+ .await;
try_write!(
write_file_with_missing_parent_retry(
fs,
&dest_uri,
new_contents.clone().into_bytes(),
+ follow_symlinks,
sandbox,
)
.await
@@ -588,7 +644,7 @@ async fn apply_hunks_to_files(
overwritten_content: overwritten_move_content.clone(),
},
});
- ensure_not_directory(&path_uri, fs, sandbox)
+ ensure_not_directory(&path_uri, fs, follow_symlinks, sandbox)
.await
.with_context(|| {
format!(
@@ -602,6 +658,7 @@ async fn apply_hunks_to_files(
RemoveOptions {
recursive: false,
force: false,
+ follow_symlinks,
},
sandbox,
)
@@ -617,6 +674,7 @@ async fn apply_hunks_to_files(
&path_uri,
Some(&original_contents),
fs,
+ follow_symlinks,
sandbox,
)
.await;
@@ -634,12 +692,17 @@ async fn apply_hunks_to_files(
modified.push(affected_path);
} else {
try_write!(
- fs.write_file(&path_uri, new_contents.clone().into_bytes(), sandbox)
- .await
- .with_context(|| format!(
- "Failed to write file {}",
- path_uri.inferred_native_path_string()
- ))
+ fs.write_file(
+ &path_uri,
+ new_contents.clone().into_bytes(),
+ WriteFileOptions { follow_symlinks },
+ sandbox,
+ )
+ .await
+ .with_context(|| format!(
+ "Failed to write file {}",
+ path_uri.inferred_native_path_string()
+ ))
);
delta.changes.push(AppliedPatchChange {
path: path_uri,
@@ -665,9 +728,12 @@ async fn apply_hunks_to_files(
async fn ensure_not_directory(
path: &PathUri,
fs: &dyn ExecutorFileSystem,
+ follow_symlinks: bool,
sandbox: Option<&FileSystemSandboxContext>,
) -> io::Result<()> {
- let metadata = fs.get_metadata(path, sandbox).await?;
+ let metadata = fs
+ .get_metadata(path, GetMetadataOptions { follow_symlinks }, sandbox)
+ .await?;
if metadata.is_directory {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
@@ -681,11 +747,12 @@ async fn remove_failure_was_side_effect_free(
path: &PathUri,
expected_content: Option<&str>,
fs: &dyn ExecutorFileSystem,
+ follow_symlinks: bool,
sandbox: Option<&FileSystemSandboxContext>,
) -> bool {
match expected_content {
Some(expected_content) => fs
- .read_file_text(path, sandbox)
+ .read_file_text(path, ReadFileOptions { follow_symlinks }, sandbox)
.await
.is_ok_and(|content| content == expected_content),
None => false,
@@ -695,11 +762,15 @@ async fn remove_failure_was_side_effect_free(
async fn read_optional_file_text_for_delta(
path: &PathUri,
fs: &dyn ExecutorFileSystem,
+ follow_symlinks: bool,
sandbox: Option<&FileSystemSandboxContext>,
exact: &mut bool,
) -> Option<String> {
- note_existing_path_delta_support(path, fs, sandbox, exact).await;
- match fs.read_file_text(path, sandbox).await {
+ note_existing_path_delta_support(path, fs, follow_symlinks, sandbox, exact).await;
+ match fs
+ .read_file_text(path, ReadFileOptions { follow_symlinks }, sandbox)
+ .await
+ {
Ok(content) => Some(content),
Err(source) if source.kind() == io::ErrorKind::NotFound => None,
Err(_) => {
@@ -712,10 +783,14 @@ async fn read_optional_file_text_for_delta(
async fn note_existing_path_delta_support(
path: &PathUri,
fs: &dyn ExecutorFileSystem,
+ follow_symlinks: bool,
sandbox: Option<&FileSystemSandboxContext>,
exact: &mut bool,
) {
- match fs.get_metadata(path, sandbox).await {
+ match fs
+ .get_metadata(path, GetMetadataOptions { follow_symlinks }, sandbox)
+ .await
+ {
Ok(metadata) if metadata.is_file && !metadata.is_symlink => {}
Ok(_) => *exact = false,
Err(source) if source.kind() == io::ErrorKind::NotFound => {}
@@ -727,29 +802,50 @@ async fn write_file_with_missing_parent_retry(
fs: &dyn ExecutorFileSystem,
path: &PathUri,
contents: Vec<u8>,
+ follow_symlinks: bool,
sandbox: Option<&FileSystemSandboxContext>,
) -> anyhow::Result<()> {
- match fs.write_file(path, contents.clone(), sandbox).await {
+ match fs
+ .write_file(
+ path,
+ contents.clone(),
+ WriteFileOptions { follow_symlinks },
+ sandbox,
+ )
+ .await
+ {
Ok(()) => Ok(()),
Err(err) if err.kind() == io::ErrorKind::NotFound => {
if let Some(parent) = path.parent() {
- fs.create_directory(&parent, CreateDirectoryOptions { recursive: true }, sandbox)
- .await
- .with_context(|| {
- format!(
- "Failed to create parent directories for {}",
- path.inferred_native_path_string()
- )
- })?;
- }
- fs.write_file(path, contents, sandbox)
+ fs.create_directory(
+ &parent,
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks,
+ },
+ sandbox,
+ )
.await
.with_context(|| {
format!(
- "Failed to write file {}",
+ "Failed to create parent directories for {}",
path.inferred_native_path_string()
)
})?;
+ }
+ fs.write_file(
+ path,
+ contents,
+ WriteFileOptions { follow_symlinks },
+ sandbox,
+ )
+ .await
+ .with_context(|| {
+ format!(
+ "Failed to write file {}",
+ path.inferred_native_path_string()
+ )
+ })?;
Ok(())
}
Err(err) => Err(err).with_context(|| {
diff --git a/codex-rs/apply-patch/src/standalone_executable.rs b/codex-rs/apply-patch/src/standalone_executable.rs
index c977fb74c2..7f2627beca 100644
--- a/codex-rs/apply-patch/src/standalone_executable.rs
+++ b/codex-rs/apply-patch/src/standalone_executable.rs
@@ -68,9 +68,12 @@ pub fn run_main() -> i32 {
// TODO(anp): Discover the standalone executable cwd as PathUri directly.
let cwd = codex_utils_path_uri::PathUri::from_abs_path(&cwd);
let update_file_mode = crate::apply_patch_file_update_mode_from_env();
- match runtime.block_on(crate::apply_patch_with_mode(
+ match runtime.block_on(crate::apply_patch_with_options(
&patch_arg,
- update_file_mode,
+ crate::ApplyPatchOptions {
+ update_file_mode,
+ ..Default::default()
+ },
&cwd,
&mut stdout,
&mut stderr,
diff --git a/codex-rs/apply-patch/tests/suite/mod.rs b/codex-rs/apply-patch/tests/suite/mod.rs
index 7d54de85ad..6c827e70b3 100644
--- a/codex-rs/apply-patch/tests/suite/mod.rs
+++ b/codex-rs/apply-patch/tests/suite/mod.rs
@@ -1,4 +1,6 @@
mod cli;
+#[cfg(unix)]
+mod no_follow;
mod scenarios;
#[cfg(not(target_os = "windows"))]
mod tool;
diff --git a/codex-rs/apply-patch/tests/suite/no_follow.rs b/codex-rs/apply-patch/tests/suite/no_follow.rs
new file mode 100644
index 0000000000..d2b05bfe1e
--- /dev/null
+++ b/codex-rs/apply-patch/tests/suite/no_follow.rs
@@ -0,0 +1,153 @@
+use codex_apply_patch::ApplyPatchOptions;
+use codex_apply_patch::MaybeApplyPatchVerified;
+use codex_apply_patch::apply_patch_with_options;
+use codex_apply_patch::parse_patch;
+use codex_apply_patch::verify_apply_patch_args;
+use codex_exec_server::LOCAL_FS;
+use codex_utils_path_uri::PathUri;
+use pretty_assertions::assert_eq;
+use std::fs;
+use std::os::unix::fs::symlink;
+
+#[tokio::test]
+async fn no_follow_rejects_leaf_and_ancestor_links_for_every_patch_operation() -> anyhow::Result<()>
+{
+ for path in ["link.txt", "linked/victim.txt"] {
+ for body in [
+ format!("*** Add File: {path}\n+changed"),
+ format!("*** Update File: {path}\n@@\n-original\n+changed"),
+ format!("*** Delete File: {path}"),
+ format!("*** Update File: {path}\n*** Move to: moved.txt\n@@\n-original\n+changed"),
+ format!("*** Update File: source.txt\n*** Move to: {path}\n@@\n-original\n+changed"),
+ "*** Add File: linked/new/nested.txt\n+changed".to_string(),
+ "*** Update File: source.txt\n*** Move to: linked/new/nested.txt\n@@\n-original\n+changed".to_string(),
+ ] {
+ let temp = tempfile::tempdir()?;
+ // macOS's temporary directory can itself contain a /var symlink.
+ let root = temp.path().canonicalize()?;
+ let work = root.join("work");
+ let outside = root.join("outside");
+ fs::create_dir(&work)?;
+ fs::create_dir(&outside)?;
+ fs::write(outside.join("victim.txt"), "original\n")?;
+ fs::write(work.join("source.txt"), "original\n")?;
+ symlink(outside.join("victim.txt"), work.join("link.txt"))?;
+ symlink(&outside, work.join("linked"))?;
+
+ let patch = format!("*** Begin Patch\n{body}\n*** End Patch");
+ let failure = apply_patch_with_options(
+ &patch,
+ ApplyPatchOptions {
+ follow_symlinks: false,
+ ..Default::default()
+ },
+ &PathUri::from_host_native_path(&work)?,
+ &mut Vec::new(),
+ &mut Vec::new(),
+ LOCAL_FS.as_ref(),
+ /*sandbox*/ None,
+ )
+ .await
+ .expect_err(&body);
+
+ assert!(failure.delta().is_empty(), "{body}");
+ assert_eq!(fs::read_to_string(outside.join("victim.txt"))?, "original\n");
+ assert_eq!(fs::read_to_string(work.join("source.txt"))?, "original\n");
+ assert!(!outside.join("new").exists(), "{body}");
+ assert!(!work.join("moved.txt").exists(), "{body}");
+ assert!(fs::symlink_metadata(work.join("link.txt"))?.is_symlink());
+ }
+ }
+ Ok(())
+}
+
+#[tokio::test]
+async fn no_follow_rechecks_paths_after_verification() -> anyhow::Result<()> {
+ let temp = tempfile::tempdir()?;
+ let root = temp.path().canonicalize()?;
+ fs::create_dir(root.join("approved"))?;
+ fs::create_dir(root.join("outside"))?;
+ fs::write(root.join("approved/file.txt"), "original\n")?;
+ fs::write(root.join("outside/file.txt"), "original\n")?;
+ let cwd = PathUri::from_host_native_path(&root)?;
+ let patch = "*** Begin Patch\n*** Update File: approved/file.txt\n@@\n-original\n+changed\n*** End Patch";
+ let MaybeApplyPatchVerified::Body(action) = verify_apply_patch_args(
+ parse_patch(patch)?,
+ &cwd,
+ LOCAL_FS.as_ref(),
+ /*sandbox*/ None,
+ )
+ .await
+ else {
+ panic!("regular-file patch should verify");
+ };
+ fs::rename(root.join("approved"), root.join("original"))?;
+ symlink(root.join("outside"), root.join("approved"))?;
+
+ apply_patch_with_options(
+ &action.patch,
+ ApplyPatchOptions {
+ follow_symlinks: false,
+ ..Default::default()
+ },
+ &cwd,
+ &mut Vec::new(),
+ &mut Vec::new(),
+ LOCAL_FS.as_ref(),
+ /*sandbox*/ None,
+ )
+ .await
+ .expect_err("swapped ancestor must not be followed");
+ assert_eq!(
+ fs::read_to_string(root.join("outside/file.txt"))?,
+ "original\n"
+ );
+ assert_eq!(
+ fs::read_to_string(root.join("original/file.txt"))?,
+ "original\n"
+ );
+ Ok(())
+}
+
+#[tokio::test]
+async fn no_follow_applies_regular_files_and_default_still_follows_links() -> anyhow::Result<()> {
+ let temp = tempfile::tempdir()?;
+ let root = temp.path().canonicalize()?;
+ let cwd = PathUri::from_host_native_path(&root)?;
+ let patch = "*** Begin Patch\n*** Add File: new/file.txt\n+original\n*** Update File: new/file.txt\n*** Move to: moved/file.txt\n@@\n-original\n+changed\n*** Add File: remove.txt\n+remove\n*** Delete File: remove.txt\n*** End Patch";
+ apply_patch_with_options(
+ patch,
+ ApplyPatchOptions {
+ follow_symlinks: false,
+ ..Default::default()
+ },
+ &cwd,
+ &mut Vec::new(),
+ &mut Vec::new(),
+ LOCAL_FS.as_ref(),
+ /*sandbox*/ None,
+ )
+ .await?;
+ assert_eq!(
+ fs::read_to_string(root.join("moved/file.txt"))?,
+ "changed\n"
+ );
+ assert!(!root.join("new/file.txt").exists());
+ assert!(!root.join("remove.txt").exists());
+
+ symlink(root.join("moved/file.txt"), root.join("link.txt"))?;
+ codex_apply_patch::apply_patch(
+ "*** Begin Patch\n*** Update File: link.txt\n@@\n-changed\n+followed\n*** End Patch",
+ &cwd,
+ &mut Vec::new(),
+ &mut Vec::new(),
+ LOCAL_FS.as_ref(),
+ /*sandbox*/ None,
+ )
+ .await?;
+ assert_eq!(
+ fs::read_to_string(root.join("moved/file.txt"))?,
+ "followed\n"
+ );
+ Ok(())
+}
diff --git a/codex-rs/arg0/src/lib.rs b/codex-rs/arg0/src/lib.rs
index 50ec7cff18..f44dc145b1 100644
--- a/codex-rs/arg0/src/lib.rs
+++ b/codex-rs/arg0/src/lib.rs
@@ -130,9 +130,12 @@ pub fn arg0_dispatch() -> Option<Arg0PathEntryGuard> {
};
let cwd = cwd.into();
let update_file_mode = codex_apply_patch::apply_patch_file_update_mode_from_env();
- match runtime.block_on(codex_apply_patch::apply_patch_with_mode(
+ match runtime.block_on(codex_apply_patch::apply_patch_with_options(
&patch_arg,
- update_file_mode,
+ codex_apply_patch::ApplyPatchOptions {
+ update_file_mode,
+ ..Default::default()
+ },
&cwd,
&mut stdout,
&mut stderr,
diff --git a/codex-rs/config/src/loader/layer_io.rs b/codex-rs/config/src/loader/layer_io.rs
index d704961274..1f6bf6b92d 100644
--- a/codex-rs/config/src/loader/layer_io.rs
+++ b/codex-rs/config/src/loader/layer_io.rs
@@ -8,6 +8,8 @@ use crate::diagnostics::io_error_from_config_error;
use crate::state::LoaderOverrides;
use crate::strict_config::config_error_from_ignored_toml_value_fields;
use codex_file_system::ExecutorFileSystem;
+#[cfg(windows)]
+use codex_file_system::GetMetadataOptions;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_absolute_path::AbsolutePathBufGuard;
use codex_utils_path_uri::PathUri;
@@ -72,7 +74,14 @@ pub(super) async fn load_config_layers_internal(
#[cfg(windows)]
let startup_warnings = if ignore_default_managed_config {
let path_uri = PathUri::from_abs_path(&managed_config_path);
- match fs.get_metadata(&path_uri, /*sandbox*/ None).await {
+ match fs
+ .get_metadata(
+ &path_uri,
+ GetMetadataOptions::default(),
+ /*sandbox*/ None,
+ )
+ .await
+ {
Ok(_) => vec![format!(
"Ignoring deprecated managed config file at {}; CODEX_HOME/managed_config.toml is no longer supported on Windows. Use %ProgramData%\\OpenAI\\Codex\\requirements.toml for enforced settings or config.toml for defaults.",
managed_config_path.as_path().display()
@@ -144,7 +153,10 @@ pub(super) async fn read_config_from_path(
strict_config: bool,
) -> io::Result<Option<TomlValue>> {
let path_uri = PathUri::from_abs_path(path);
- match fs.read_file_text(&path_uri, /*sandbox*/ None).await {
+ match fs
+ .read_file_text(&path_uri, Default::default(), /*sandbox*/ None)
+ .await
+ {
Ok(contents) => match toml::from_str::<TomlValue>(&contents) {
Ok(value) => {
if strict_config {
diff --git a/codex-rs/config/src/loader/mod.rs b/codex-rs/config/src/loader/mod.rs
index 85f4352665..31cd64e75b 100644
--- a/codex-rs/config/src/loader/mod.rs
+++ b/codex-rs/config/src/loader/mod.rs
@@ -594,7 +594,10 @@ async fn load_config_toml_for_required_layer_raw(
})?;
let base_dir = AbsolutePathBuf::from_absolute_path(config_parent)?;
let toml_file_uri = PathUri::from_abs_path(toml_file);
- let toml_value = match fs.read_file_text(&toml_file_uri, /*sandbox*/ None).await {
+ let toml_value = match fs
+ .read_file_text(&toml_file_uri, Default::default(), /*sandbox*/ None)
+ .await
+ {
Ok(contents) => {
let config: TomlValue = toml::from_str(&contents).map_err(|err| {
let config_error =
@@ -685,7 +688,11 @@ pub async fn load_requirements_toml(
) -> io::Result<Option<RequirementsLayerEntry>> {
let requirements_toml_file_uri = PathUri::from_abs_path(requirements_toml_file);
match fs
- .read_file_text(&requirements_toml_file_uri, /*sandbox*/ None)
+ .read_file_text(
+ &requirements_toml_file_uri,
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await
{
Ok(contents) => {
@@ -1315,7 +1322,10 @@ async fn find_project_root(
for marker in project_root_markers {
let marker_path = ancestor.join(marker);
let marker_path_uri = PathUri::from_abs_path(&marker_path);
- let Ok(metadata) = fs.get_metadata(&marker_path_uri, /*sandbox*/ None).await else {
+ let Ok(metadata) = fs
+ .get_metadata(&marker_path_uri, Default::default(), /*sandbox*/ None)
+ .await
+ else {
continue;
};
if marker == ".git"
@@ -1323,6 +1333,7 @@ async fn find_project_root(
&& fs
.get_metadata(
&PathUri::from_abs_path(&marker_path.join("HEAD")),
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -1341,7 +1352,10 @@ async fn find_git_checkout_root(
cwd: &AbsolutePathBuf,
) -> Option<AbsolutePathBuf> {
let cwd_uri = PathUri::from_abs_path(cwd);
- let base = match fs.get_metadata(&cwd_uri, /*sandbox*/ None).await {
+ let base = match fs
+ .get_metadata(&cwd_uri, Default::default(), /*sandbox*/ None)
+ .await
+ {
Ok(metadata) if metadata.is_directory => cwd.clone(),
_ => cwd.parent()?,
};
@@ -1349,13 +1363,17 @@ async fn find_git_checkout_root(
for dir in base.ancestors() {
let dot_git = dir.join(".git");
let dot_git_uri = PathUri::from_abs_path(&dot_git);
- let Ok(metadata) = fs.get_metadata(&dot_git_uri, /*sandbox*/ None).await else {
+ let Ok(metadata) = fs
+ .get_metadata(&dot_git_uri, Default::default(), /*sandbox*/ None)
+ .await
+ else {
continue;
};
if metadata.is_directory
&& fs
.get_metadata(
&PathUri::from_abs_path(&dot_git.join("HEAD")),
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -1471,7 +1489,7 @@ async fn discover_project_layers(
let dot_codex_abs = dir.join(".codex");
let dot_codex_uri = PathUri::from_abs_path(&dot_codex_abs);
if !fs
- .get_metadata(&dot_codex_uri, /*sandbox*/ None)
+ .get_metadata(&dot_codex_uri, Default::default(), /*sandbox*/ None)
.await
.map(|metadata| metadata.is_directory)
.unwrap_or(false)
@@ -1489,7 +1507,10 @@ async fn discover_project_layers(
}
let config_file = dot_codex_abs.join(CONFIG_TOML_FILE);
let config_file_uri = PathUri::from_abs_path(&config_file);
- match fs.read_file_text(&config_file_uri, /*sandbox*/ None).await {
+ match fs
+ .read_file_text(&config_file_uri, Default::default(), /*sandbox*/ None)
+ .await
+ {
Ok(contents) => {
let config: TomlValue = match toml::from_str(&contents) {
Ok(config) => config,
@@ -1601,7 +1622,11 @@ async fn load_root_checkout_project_config(
let hooks_config_file_uri = PathUri::from_abs_path(&hooks_config_file);
Ok(
match fs
- .read_file_text(&hooks_config_file_uri, /*sandbox*/ None)
+ .read_file_text(
+ &hooks_config_file_uri,
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await
{
Ok(contents) => {
diff --git a/codex-rs/config/src/loader/tests.rs b/codex-rs/config/src/loader/tests.rs
index 5cb1ad9af1..6f3979cf61 100644
--- a/codex-rs/config/src/loader/tests.rs
+++ b/codex-rs/config/src/loader/tests.rs
@@ -5,8 +5,11 @@ use codex_file_system::ExecutorFileSystemFuture;
use codex_file_system::FileMetadata;
use codex_file_system::FileSystemReadStream;
use codex_file_system::FileSystemSandboxContext;
+use codex_file_system::GetMetadataOptions;
use codex_file_system::ReadDirectoryEntry;
+use codex_file_system::ReadFileOptions;
use codex_file_system::RemoveOptions;
+use codex_file_system::WriteFileOptions;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
@@ -29,6 +32,7 @@ impl ExecutorFileSystem for TestFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ _options: ReadFileOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
Box::pin(async move {
@@ -54,6 +58,7 @@ impl ExecutorFileSystem for TestFileSystem {
&'a self,
_path: &'a PathUri,
_contents: Vec<u8>,
+ _options: WriteFileOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
Box::pin(async move { unimplemented!("test filesystem only supports reads") })
@@ -71,6 +76,7 @@ impl ExecutorFileSystem for TestFileSystem {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ _options: GetMetadataOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(async move {
diff --git a/codex-rs/core-plugins/src/plugin_metrics_sidecar.rs b/codex-rs/core-plugins/src/plugin_metrics_sidecar.rs
index aefab13ecf..7474c0a659 100644
--- a/codex-rs/core-plugins/src/plugin_metrics_sidecar.rs
+++ b/codex-rs/core-plugins/src/plugin_metrics_sidecar.rs
@@ -4,6 +4,7 @@ use codex_exec_server::Environment;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::RemoveOptions;
+use codex_exec_server::WriteFileOptions;
use codex_protocol::models::AdditionalPermissionProfile;
use codex_protocol::models::FileSystemPermissions;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -71,6 +72,7 @@ impl Drop for RemotePluginMetricsDirectory {
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -151,7 +153,12 @@ impl PluginMetricsSidecar {
let output_path = directory.path.join("measurements.json").ok()?;
directory
.filesystem
- .write_file(&output_path, Vec::new(), /*sandbox*/ None)
+ .write_file(
+ &output_path,
+ Vec::new(),
+ WriteFileOptions::default(),
+ /*sandbox*/ None,
+ )
.await
.ok()?;
let file_stream = directory
diff --git a/codex-rs/core-plugins/src/provider.rs b/codex-rs/core-plugins/src/provider.rs
index 41484206c8..56e44903b6 100644
--- a/codex-rs/core-plugins/src/provider.rs
+++ b/codex-rs/core-plugins/src/provider.rs
@@ -1,6 +1,8 @@
use crate::manifest::parse_plugin_manifest_uri;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::ExecutorFileSystem;
+use codex_exec_server::GetMetadataOptions;
+use codex_exec_server::ReadFileOptions;
use codex_plugin::PluginProvider;
use codex_plugin::ResolvedPlugin;
use codex_plugin::ResolvedPluginError;
@@ -156,7 +158,11 @@ async fn resolve_plugin_root(
let root_id = &selected_root.id;
let CapabilityRootLocation::Environment { environment_id, .. } = &selected_root.location;
let root_metadata = file_system
- .get_metadata(&plugin_root, /*sandbox*/ None)
+ .get_metadata(
+ &plugin_root,
+ GetMetadataOptions::default(),
+ /*sandbox*/ None,
+ )
.await
.map_err(|source| ExecutorPluginProviderError::InspectRoot {
root_id: root_id.clone(),
@@ -181,7 +187,11 @@ async fn resolve_plugin_root(
}
})?;
match file_system
- .get_metadata(&candidate_uri, /*sandbox*/ None)
+ .get_metadata(
+ &candidate_uri,
+ GetMetadataOptions::default(),
+ /*sandbox*/ None,
+ )
.await
{
Ok(metadata) if metadata.is_file => {
@@ -203,7 +213,11 @@ async fn resolve_plugin_root(
return Ok(None);
};
let contents = file_system
- .read_file_text(&manifest_uri, /*sandbox*/ None)
+ .read_file_text(
+ &manifest_uri,
+ ReadFileOptions::default(),
+ /*sandbox*/ None,
+ )
.await
.map_err(|source| ExecutorPluginProviderError::ReadManifest {
root_id: root_id.clone(),
diff --git a/codex-rs/core-plugins/src/provider_tests.rs b/codex-rs/core-plugins/src/provider_tests.rs
index 523c4087b7..51734741c3 100644
--- a/codex-rs/core-plugins/src/provider_tests.rs
+++ b/codex-rs/core-plugins/src/provider_tests.rs
@@ -11,9 +11,12 @@ use codex_exec_server::FileMetadata;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::FileSystemResult;
use codex_exec_server::FileSystemSandboxContext;
+use codex_exec_server::GetMetadataOptions;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_exec_server::ReadDirectoryEntry;
+use codex_exec_server::ReadFileOptions;
use codex_exec_server::RemoveOptions;
+use codex_exec_server::WriteFileOptions;
use codex_exec_server_test_support::environment_manager_without_environments;
use codex_plugin::PluginProvider;
use codex_plugin::ResolvedPlugin;
@@ -74,6 +77,7 @@ impl ExecutorFileSystem for SyntheticPluginFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ _options: ReadFileOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
Box::pin(async move {
@@ -101,6 +105,7 @@ impl ExecutorFileSystem for SyntheticPluginFileSystem {
&'a self,
_path: &'a PathUri,
_contents: Vec<u8>,
+ _options: WriteFileOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
Box::pin(async { Self::unsupported() })
@@ -118,6 +123,7 @@ impl ExecutorFileSystem for SyntheticPluginFileSystem {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ _options: GetMetadataOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(async move {
diff --git a/codex-rs/core-plugins/src/script_attribution.rs b/codex-rs/core-plugins/src/script_attribution.rs
index 1b61d3c138..97e752d661 100644
--- a/codex-rs/core-plugins/src/script_attribution.rs
+++ b/codex-rs/core-plugins/src/script_attribution.rs
@@ -17,6 +17,8 @@ use crate::store::DEFAULT_PLUGIN_VERSION;
use crate::store::PluginStore;
use crate::store::plugin_version_for_source;
use codex_exec_server::ExecutorFileSystem;
+use codex_exec_server::GetMetadataOptions;
+use codex_exec_server::ReadFileOptions;
use codex_plugin::PluginId;
use codex_protocol::items::is_safe_plugin_relative_path;
use codex_shell_command::bash::extract_bash_command;
@@ -256,14 +258,18 @@ impl TrustedPluginRoots {
return None;
}
let metadata = file_system
- .get_metadata(&script, /*sandbox*/ None)
+ .get_metadata(
+ &script,
+ GetMetadataOptions::default(),
+ /*sandbox*/ None,
+ )
.await
.ok()?;
if !metadata.is_file || metadata.size != candidate.contents.len() as u64 {
return None;
}
let contents = file_system
- .read_file(&script, /*sandbox*/ None)
+ .read_file(&script, ReadFileOptions::default(), /*sandbox*/ None)
.await
.ok()?;
(contents == candidate.contents).then_some(candidate.attribution)
diff --git a/codex-rs/core/src/agents_md.rs b/codex-rs/core/src/agents_md.rs
index 255c7ca614..c65a688063 100644
--- a/codex-rs/core/src/agents_md.rs
+++ b/codex-rs/core/src/agents_md.rs
@@ -24,6 +24,8 @@ use codex_config::default_project_root_markers;
use codex_config::merge_toml_values;
use codex_config::project_root_markers_from_config;
use codex_exec_server::ExecutorFileSystem;
+use codex_exec_server::GetMetadataOptions;
+use codex_exec_server::ReadFileOptions;
use codex_extension_api::UserInstructions;
use codex_file_system::FileSystemSandboxContext;
use codex_file_system::FindUpErrorPolicy;
@@ -153,7 +155,7 @@ async fn read_agents_md(
break;
}
- let mut data = match fs.read_file(&p, sandbox).await {
+ let mut data = match fs.read_file(&p, ReadFileOptions::default(), sandbox).await {
Ok(data) => data,
Err(err) if err.kind() == io::ErrorKind::NotFound => continue,
Err(err) => return Err(err),
@@ -252,7 +254,10 @@ async fn agents_md_paths(
let candidate = directory
.join(name)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
- match fs.get_metadata(&candidate, sandbox).await {
+ match fs
+ .get_metadata(&candidate, GetMetadataOptions::default(), sandbox)
+ .await
+ {
Ok(metadata) if metadata.is_file => return Ok(Some(candidate)),
Ok(_) => {}
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
diff --git a/codex-rs/core/src/agents_md_tests.rs b/codex-rs/core/src/agents_md_tests.rs
index 3dada2a80b..8e889a1990 100644
--- a/codex-rs/core/src/agents_md_tests.rs
+++ b/codex-rs/core/src/agents_md_tests.rs
@@ -17,9 +17,12 @@ use codex_exec_server::ExecutorFileSystemFuture;
use codex_exec_server::FileMetadata;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::FileSystemSandboxContext;
+use codex_exec_server::GetMetadataOptions;
use codex_exec_server::LOCAL_FS;
use codex_exec_server::ReadDirectoryEntry;
+use codex_exec_server::ReadFileOptions;
use codex_exec_server::RemoveOptions;
+use codex_exec_server::WriteFileOptions;
use codex_extension_api::UserInstructions;
use codex_features::Feature;
use codex_protocol::config_types::WindowsSandboxLevel;
@@ -87,6 +90,7 @@ impl FailingFileSystem {
async fn read_file(
&self,
path: &PathUri,
+ options: ReadFileOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> io::Result<Vec<u8>> {
if path.to_abs_path()? == self.path
@@ -94,13 +98,14 @@ impl FailingFileSystem {
{
return Err(io::Error::new(kind, "injected read failure"));
}
- LOCAL_FS.read_file(path, sandbox).await
+ LOCAL_FS.read_file(path, options, sandbox).await
}
async fn write_file(
&self,
_path: &PathUri,
_contents: Vec<u8>,
+ _options: WriteFileOptions,
_sandbox: Option<&FileSystemSandboxContext>,
) -> io::Result<()> {
unreachable!("write_file should not be called")
@@ -118,6 +123,7 @@ impl FailingFileSystem {
async fn get_metadata(
&self,
path: &PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> io::Result<FileMetadata> {
let path_abs = path.to_abs_path()?;
@@ -138,7 +144,7 @@ impl FailingFileSystem {
.await
.expect("metadata release semaphore")
.forget();
- LOCAL_FS.get_metadata(path, sandbox).await
+ LOCAL_FS.get_metadata(path, options, sandbox).await
}
InjectedFailure::MetadataBlockedByFilenamePrefix(prefix)
if path_abs
@@ -152,7 +158,7 @@ impl FailingFileSystem {
.await
.expect("metadata release semaphore")
.forget();
- LOCAL_FS.get_metadata(path, sandbox).await
+ LOCAL_FS.get_metadata(path, options, sandbox).await
}
InjectedFailure::MetadataPending if path_abs == self.path => {
std::future::pending().await
@@ -161,7 +167,7 @@ impl FailingFileSystem {
| InjectedFailure::MetadataBlocked
| InjectedFailure::MetadataBlockedByFilenamePrefix(_)
| InjectedFailure::MetadataPending
- | InjectedFailure::Read(_) => LOCAL_FS.get_metadata(path, sandbox).await,
+ | InjectedFailure::Read(_) => LOCAL_FS.get_metadata(path, options, sandbox).await,
}
}
@@ -205,9 +211,10 @@ impl ExecutorFileSystem for FailingFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ options: ReadFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
- Box::pin(FailingFileSystem::read_file(self, path, sandbox))
+ Box::pin(FailingFileSystem::read_file(self, path, options, sandbox))
}
fn read_file_stream<'a>(
@@ -227,9 +234,12 @@ impl ExecutorFileSystem for FailingFileSystem {
&'a self,
path: &'a PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
- Box::pin(FailingFileSystem::write_file(self, path, contents, sandbox))
+ Box::pin(FailingFileSystem::write_file(
+ self, path, contents, options, sandbox,
+ ))
}
fn create_directory<'a>(
@@ -246,9 +256,12 @@ impl ExecutorFileSystem for FailingFileSystem {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
- Box::pin(FailingFileSystem::get_metadata(self, path, sandbox))
+ Box::pin(FailingFileSystem::get_metadata(
+ self, path, options, sandbox,
+ ))
}
fn read_directory<'a>(
diff --git a/codex-rs/core/src/config/agent_roles.rs b/codex-rs/core/src/config/agent_roles.rs
index f2fa797128..7918da1021 100644
--- a/codex-rs/core/src/config/agent_roles.rs
+++ b/codex-rs/core/src/config/agent_roles.rs
@@ -4,6 +4,8 @@ use codex_config::config_toml::AgentRoleToml;
use codex_config::config_toml::AgentsToml;
use codex_config::config_toml::ConfigToml;
use codex_exec_server::ExecutorFileSystem;
+use codex_exec_server::GetMetadataOptions;
+use codex_exec_server::ReadFileOptions;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_absolute_path::AbsolutePathBufGuard;
use codex_utils_path_uri::PathUri;
@@ -317,7 +319,9 @@ async fn read_resolved_agent_role_file(
role_name_hint: Option<&str>,
) -> std::io::Result<ResolvedAgentRoleFile> {
let path_uri = PathUri::from_abs_path(path);
- let contents = fs.read_file_text(&path_uri, /*sandbox*/ None).await?;
+ let contents = fs
+ .read_file_text(&path_uri, ReadFileOptions::default(), /*sandbox*/ None)
+ .await?;
let config_base_dir = path.parent().unwrap_or_else(|| path.clone());
parse_agent_role_file_contents(
&contents,
@@ -391,7 +395,11 @@ async fn validate_agent_role_config_file(
let config_file_uri = PathUri::from_abs_path(config_file);
let metadata = fs
- .get_metadata(&config_file_uri, /*sandbox*/ None)
+ .get_metadata(
+ &config_file_uri,
+ GetMetadataOptions::default(),
+ /*sandbox*/ None,
+ )
.await
.map_err(|e| {
std::io::Error::new(
diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs
index a66a2edc14..0a3ebf4587 100644
--- a/codex-rs/core/src/config/mod.rs
+++ b/codex-rs/core/src/config/mod.rs
@@ -58,6 +58,7 @@ use codex_core_plugins::PluginLoadOutcome;
use codex_core_plugins::PluginsConfigInput;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::LOCAL_FS;
+use codex_exec_server::ReadFileOptions;
use codex_features::CodeModeConfigToml;
use codex_features::CurrentTimeReminderConfigToml;
use codex_features::CurrentTimeReminderDeliveryMode;
@@ -4259,7 +4260,7 @@ impl Config {
let path_uri = PathUri::from_abs_path(path);
let contents = fs
- .read_file_text(&path_uri, /*sandbox*/ None)
+ .read_file_text(&path_uri, ReadFileOptions::default(), /*sandbox*/ None)
.await
.map_err(|e| {
std::io::Error::new(
diff --git a/codex-rs/core/src/git_info_tests.rs b/codex-rs/core/src/git_info_tests.rs
index 8adf5206e6..e8ba696981 100644
--- a/codex-rs/core/src/git_info_tests.rs
+++ b/codex-rs/core/src/git_info_tests.rs
@@ -6,9 +6,12 @@ use codex_exec_server::FileMetadata;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::FileSystemResult;
use codex_exec_server::FileSystemSandboxContext;
+use codex_exec_server::GetMetadataOptions;
use codex_exec_server::LOCAL_FS;
use codex_exec_server::ReadDirectoryEntry;
+use codex_exec_server::ReadFileOptions;
use codex_exec_server::RemoveOptions;
+use codex_exec_server::WriteFileOptions;
use codex_git_utils::GitInfo;
use codex_git_utils::GitSha;
use codex_git_utils::collect_git_info;
@@ -68,6 +71,7 @@ impl ExecutorFileSystem for MetadataOverrideFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ options: ReadFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
Box::pin(async move {
@@ -79,7 +83,7 @@ impl ExecutorFileSystem for MetadataOverrideFileSystem {
fs::remove_file(local_path.as_path())?;
std::os::unix::fs::symlink(replacement, local_path.as_path())?;
}
- LOCAL_FS.read_file(path, sandbox).await
+ LOCAL_FS.read_file(path, options, sandbox).await
})
}
@@ -95,6 +99,7 @@ impl ExecutorFileSystem for MetadataOverrideFileSystem {
&'a self,
_path: &'a PathUri,
_contents: Vec<u8>,
+ _options: WriteFileOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
Box::pin(async { Self::unsupported() })
@@ -112,6 +117,7 @@ impl ExecutorFileSystem for MetadataOverrideFileSystem {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(async move {
@@ -121,7 +127,7 @@ impl ExecutorFileSystem for MetadataOverrideFileSystem {
"injected metadata failure",
))
} else {
- LOCAL_FS.get_metadata(path, sandbox).await
+ LOCAL_FS.get_metadata(path, options, sandbox).await
}
})
}
diff --git a/codex-rs/core/src/mcp_openai_file.rs b/codex-rs/core/src/mcp_openai_file.rs
index e0a0cda2d0..1320519b03 100644
--- a/codex-rs/core/src/mcp_openai_file.rs
+++ b/codex-rs/core/src/mcp_openai_file.rs
@@ -16,6 +16,7 @@ use crate::session::step_context::StepContext;
use codex_api::HostedFileUploadContext;
use codex_api::OPENAI_FILE_UPLOAD_LIMIT_BYTES;
use codex_api::upload_openai_file;
+use codex_exec_server::GetMetadataOptions;
use codex_login::CodexAuth;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_sandboxing::policy_transforms::effective_file_system_sandbox_policy;
@@ -196,7 +197,7 @@ async fn build_uploaded_argument_value(
}
let fs = turn_environment.environment.get_filesystem();
let metadata = fs
- .get_metadata(&path_uri, sandbox.as_ref())
+ .get_metadata(&path_uri, GetMetadataOptions::default(), sandbox.as_ref())
.await
.map_err(|error| contextualize_error(error.to_string()))?;
if !metadata.is_file {
diff --git a/codex-rs/core/src/tools/handlers/view_image.rs b/codex-rs/core/src/tools/handlers/view_image.rs
index ee8684350e..96152b20da 100644
--- a/codex-rs/core/src/tools/handlers/view_image.rs
+++ b/codex-rs/core/src/tools/handlers/view_image.rs
@@ -1,3 +1,5 @@
+use codex_exec_server::GetMetadataOptions;
+use codex_exec_server::ReadFileOptions;
use codex_protocol::items::ImageViewItem;
use codex_protocol::items::TurnItem;
use codex_protocol::models::DEFAULT_IMAGE_DETAIL;
@@ -154,7 +156,7 @@ impl ViewImageHandler {
let fs = turn_environment.environment.get_filesystem();
let metadata = fs
- .get_metadata(&path_uri, Some(&sandbox))
+ .get_metadata(&path_uri, GetMetadataOptions::default(), Some(&sandbox))
.await
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
@@ -168,7 +170,7 @@ impl ViewImageHandler {
)));
}
let file_bytes = fs
- .read_file(&path_uri, Some(&sandbox))
+ .read_file(&path_uri, ReadFileOptions::default(), Some(&sandbox))
.await
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
diff --git a/codex-rs/core/src/tools/runtimes/apply_patch.rs b/codex-rs/core/src/tools/runtimes/apply_patch.rs
index bedb63fbca..4446a0da08 100644
--- a/codex-rs/core/src/tools/runtimes/apply_patch.rs
+++ b/codex-rs/core/src/tools/runtimes/apply_patch.rs
@@ -16,6 +16,7 @@ use crate::tools::sandboxing::ToolRuntime;
use crate::tools::sandboxing::executor_windows_sandbox_level;
use codex_apply_patch::AppliedPatchDelta;
use codex_apply_patch::ApplyPatchAction;
+use codex_apply_patch::ApplyPatchOptions;
use codex_exec_server::FileSystemSandboxContext;
use codex_protocol::error::CodexErr;
use codex_protocol::error::SandboxErr;
@@ -173,9 +174,19 @@ impl ToolRuntime<ApplyPatchRequest, ApplyPatchRuntimeOutput> for ApplyPatchRunti
let sandbox = Self::file_system_sandbox_context_for_attempt(req, attempt);
let mut stdout = Vec::new();
let mut stderr = Vec::new();
- let result = codex_apply_patch::apply_patch_with_mode(
+ let result = codex_apply_patch::apply_patch_with_options(
&req.action.patch,
- req.action.update_file_mode(),
+ ApplyPatchOptions {
+ update_file_mode: req.action.update_file_mode(),
+ // Only reject links when an otherwise-required sandbox was bypassed.
+ // Executor-managed sandboxes can have SandboxType::None.
+ follow_symlinks: attempt.sandbox_requested
+ || !attempt.manager.should_sandbox(
+ attempt.permissions,
+ self.sandbox_preference(),
+ attempt.enforce_managed_network,
+ ),
+ },
&req.action.cwd,
&mut stdout,
&mut stderr,
diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs
index 4c64f544da..cf2ad9a78c 100644
--- a/codex-rs/core/tests/common/test_codex.rs
+++ b/codex-rs/core/tests/common/test_codex.rs
@@ -231,7 +231,10 @@ pub async fn test_env() -> Result<TestEnv> {
.get_filesystem()
.create_directory(
&cwd_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -1150,14 +1153,22 @@ impl TestCodexHarness {
.fs()
.create_directory(
&parent_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
}
self.test
.fs()
- .write_file(&path_uri, contents.as_ref().to_vec(), /*sandbox*/ None)
+ .write_file(
+ &path_uri,
+ contents.as_ref().to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await?;
Ok(())
}
@@ -1167,7 +1178,7 @@ impl TestCodexHarness {
Ok(self
.test
.fs()
- .read_file_text(&path_uri, /*sandbox*/ None)
+ .read_file_text(&path_uri, Default::default(), /*sandbox*/ None)
.await?)
}
@@ -1177,7 +1188,10 @@ impl TestCodexHarness {
.fs()
.create_directory(
&path_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -1198,6 +1212,7 @@ impl TestCodexHarness {
RemoveOptions {
recursive: false,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -1214,7 +1229,7 @@ impl TestCodexHarness {
match self
.test
.fs()
- .get_metadata(path_uri, /*sandbox*/ None)
+ .get_metadata(path_uri, Default::default(), /*sandbox*/ None)
.await
{
Ok(_) => Ok(true),
diff --git a/codex-rs/core/tests/suite/agents_md.rs b/codex-rs/core/tests/suite/agents_md.rs
index 9a1ff1f9a9..0b1183e921 100644
--- a/codex-rs/core/tests/suite/agents_md.rs
+++ b/codex-rs/core/tests/suite/agents_md.rs
@@ -197,11 +197,17 @@ async fn agents_override_is_preferred_over_agents_md() -> Result<()> {
let override_md = cwd.join("AGENTS.override.md");
let agents_md_uri = executor_path_uri(&agents_md)?;
let override_md_uri = executor_path_uri(&override_md)?;
- fs.write_file(&agents_md_uri, b"base doc".to_vec(), /*sandbox*/ None)
- .await?;
+ fs.write_file(
+ &agents_md_uri,
+ b"base doc".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
+ .await?;
fs.write_file(
&override_md_uri,
b"override doc".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -235,13 +241,17 @@ async fn configured_fallback_is_used_when_agents_candidate_is_directory() -> Res
let fallback_uri = executor_path_uri(&fallback)?;
fs.create_directory(
&agents_dir_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
fs.write_file(
&fallback_uri,
b"fallback doc".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -281,25 +291,31 @@ async fn agents_docs_are_concatenated_from_project_root_to_cwd() -> Result<()> {
fs.create_directory(
&nested_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
fs.write_file(
&root_agents_uri,
b"root doc".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
fs.write_file(
&git_marker_uri,
b"gitdir: /tmp/mock-git-dir\n".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
fs.write_file(
&nested_agents_uri,
b"child doc".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -421,6 +437,7 @@ async fn selected_environment_sources_match_model_visible_instructions() -> Resu
fs.write_file(
&agents_md_uri,
b"project doc".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -523,6 +540,7 @@ async fn denied_project_instructions_fail_thread_creation() -> Result<()> {
fs.write_file(
&executor_path_uri(cwd.join(GLOBAL_AGENTS_FILENAME))?,
PROJECT_INSTRUCTIONS.as_bytes().to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -563,6 +581,7 @@ async fn tightening_environment_read_permissions_invalidates_cached_project_inst
fs.write_file(
&executor_path_uri(cwd.join(GLOBAL_AGENTS_FILENAME))?,
PROJECT_INSTRUCTIONS.as_bytes().to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -651,6 +670,7 @@ async fn loads_user_instructions_without_a_primary_environment() -> Result<()> {
fs.write_file(
&project_agents_uri,
PROJECT_INSTRUCTIONS.as_bytes().to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -721,6 +741,7 @@ async fn fresh_thread_composes_global_before_project_and_reports_sources() -> Re
fs.write_file(
&agents_md_uri,
PROJECT_INSTRUCTIONS.as_bytes().to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -747,6 +768,7 @@ async fn fresh_thread_composes_global_before_project_and_reports_sources() -> Re
.write_file(
&test.workspace_path_uri(GLOBAL_AGENTS_FILENAME)?,
NEW_PROJECT_INSTRUCTIONS.as_bytes().to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -829,6 +851,7 @@ async fn multi_environment_project_instructions_share_one_byte_budget() -> Resul
fs.write_file(
&executor_path_uri(cwd.join(GLOBAL_AGENTS_FILENAME))?,
b"ABCDE".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -911,6 +934,7 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho
fs.write_file(
&executor_path_uri(cwd.join(GLOBAL_AGENTS_FILENAME))?,
b"remote project instructions".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -959,6 +983,7 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho
.write_file(
&executor_path_uri(test.config.cwd.join(GLOBAL_AGENTS_OVERRIDE_FILENAME))?,
b"new remote project instructions".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs
index 007198c394..aba1a9e3e1 100644
--- a/codex-rs/core/tests/suite/apply_patch_cli.rs
+++ b/codex-rs/core/tests/suite/apply_patch_cli.rs
@@ -21,6 +21,8 @@ use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_exec_server::REMOTE_ENVIRONMENT_ID;
use codex_exec_server::RemoveOptions;
use codex_features::Feature;
+#[cfg(unix)]
+use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::Settings;
@@ -34,6 +36,10 @@ use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EnvironmentConfigState;
use codex_protocol::protocol::EventMsg;
+#[cfg(unix)]
+use codex_protocol::protocol::Op;
+#[cfg(unix)]
+use codex_protocol::protocol::ReviewDecision;
use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::protocol::ThreadSettingsOverrides;
use codex_protocol::protocol::TurnEnvironmentSelection;
@@ -933,6 +939,92 @@ async fn intercepted_apply_patch_verification_uses_local_sandbox() -> Result<()>
Ok(())
}
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn escalated_patch_rejects_symlink_swapped_after_approval_request() -> Result<()> {
+ skip_if_no_network!(Ok(()));
+ skip_if_remote!(
+ Ok(()),
+ "approval-time symlink swap uses the local filesystem"
+ );
+ let temp = tempfile::tempdir_in(std::env::current_dir()?)?;
+ let root = temp.path().canonicalize()?;
+ let work = root.join("work");
+ let outside = root.join("victim.txt");
+ fs::create_dir(&work)?;
+ fs::write(work.join("file.txt"), "original\n")?;
+ fs::write(&outside, "original\n")?;
+ let harness = apply_patch_harness_with(move |builder| {
+ builder.with_model("gpt-5.4").with_config(move |config| {
+ config.cwd = work.try_into().expect("absolute workspace");
+ config.workspace_roots = vec![config.cwd.clone()];
+ config
+ .permissions
+ .set_workspace_roots(config.workspace_roots.clone());
+ config.approvals_reviewer = ApprovalsReviewer::User;
+ })
+ })
+ .await?;
+ let test = harness.test();
+ let call_id = "apply-patch-approval-swap";
+ let patch =
+ "*** Begin Patch\n*** Update File: file.txt\n@@\n-original\n+changed\n*** End Patch";
+ mount_apply_patch(&harness, call_id, patch, "done").await;
+ let (sandbox_policy, permission_profile) = turn_permission_fields(
+ restrictive_workspace_write_profile(),
+ test.config.cwd.as_path(),
+ );
+ test.codex
+ .start_or_steer_turn(
+ TurnInputRequest::user_input(vec![UserInput::Text {
+ text: "apply the patch".to_string(),
+ text_elements: Vec::new(),
+ }])
+ .with_thread_settings(ThreadSettingsOverrides {
+ approval_policy: Some(AskForApproval::UnlessTrusted),
+ approvals_reviewer: Some(ApprovalsReviewer::User),
+ sandbox_policy: Some(sandbox_policy),
+ permission_profile,
+ ..Default::default()
+ }),
+ )
+ .await?;
+ let event = wait_for_event(&test.codex, |event| {
+ matches!(
+ event,
+ EventMsg::ApplyPatchApprovalRequest(_) | EventMsg::TurnComplete(_)
+ )
+ })
+ .await;
+ let EventMsg::ApplyPatchApprovalRequest(approval) = event else {
+ panic!("expected patch approval before completion");
+ };
+ assert_eq!(approval.call_id, call_id);
+ let target = harness.path("file.txt");
+ fs::remove_file(&target)?;
+ create_file_symlink(&outside, &target)?;
+ test.codex
+ .submit(Op::PatchApproval {
+ id: approval.call_id,
+ decision: ReviewDecision::Approved,
+ })
+ .await?;
+ wait_for_event(&test.codex, |event| {
+ matches!(event, EventMsg::TurnComplete(_))
+ })
+ .await;
+
+ let output = harness.apply_patch_output(call_id).await;
+ assert_eq!(fs::read_to_string(&outside)?, "original\n", "{output:?}");
+ assert!(fs::symlink_metadata(&target)?.is_symlink());
+ assert!(
+ output.contains("Failed to read file to update"),
+ "{output:?}"
+ );
+ test.codex.shutdown_and_wait().await?;
+ Ok(())
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_patch_cli_does_not_write_through_symlink_escape_outside_workspace() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -1601,7 +1693,10 @@ async fn apply_patch_turn_diff_paths_stay_repo_relative_when_session_cwd_is_nest
let cwd_uri = PathUri::from_host_native_path(&cwd)?;
fs.create_directory(
&cwd_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -1611,11 +1706,17 @@ async fn apply_patch_turn_diff_paths_stay_repo_relative_when_session_cwd_is_nest
fs.write_file(
&git_uri,
b"gitdir: /tmp/fake-worktree\n".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
+ .await?;
+ fs.write_file(
+ &repo_file_uri,
+ b"before\n".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
- fs.write_file(&repo_file_uri, b"before\n".to_vec(), /*sandbox*/ None)
- .await?;
Ok(())
})
})
@@ -1690,7 +1791,10 @@ async fn apply_patch_turn_diff_skips_git_root_when_feature_is_enabled(
let cwd_uri = PathUri::from_host_native_path(&cwd)?;
fs.create_directory(
&cwd_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -1700,11 +1804,17 @@ async fn apply_patch_turn_diff_skips_git_root_when_feature_is_enabled(
fs.write_file(
&git_uri,
b"gitdir: /tmp/fake-worktree\n".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
+ .await?;
+ fs.write_file(
+ &work_file_uri,
+ b"before\n".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
- fs.write_file(&work_file_uri, b"before\n".to_vec(), /*sandbox*/ None)
- .await?;
Ok(())
})
})
@@ -1974,7 +2084,7 @@ async fn apply_patch_turn_diff_emits_portable_paths_for_remote_cwd() -> Result<(
);
assert_eq!(
test.fs()
- .read_file_text(&file_uri, /*sandbox*/ None)
+ .read_file_text(&file_uri, Default::default(), /*sandbox*/ None)
.await?,
"hello\n"
);
@@ -2019,6 +2129,7 @@ async fn apply_patch_turn_diff_tracks_local_and_remote_environment_paths() -> Re
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -2027,7 +2138,10 @@ async fn apply_patch_turn_diff_tracks_local_and_remote_environment_paths() -> Re
test.fs()
.create_directory(
&shared_cwd_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -2114,6 +2228,7 @@ async fn apply_patch_turn_diff_tracks_local_and_remote_environment_paths() -> Re
test.fs()
.read_file_text(
&PathUri::from_host_native_path(shared_cwd.join(file_name))?,
+ Default::default(),
/*sandbox*/ None,
)
.await?,
@@ -2146,6 +2261,7 @@ index 0000000000000000000000000000000000000000..9c998f7b995a7327177b38a90d138517
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -2287,6 +2403,7 @@ async fn apply_patch_clears_aggregated_diff_after_inexact_delta() -> Result<()>
fs.write_file(
&binary_path_uri,
vec![0xff, 0xfe, 0xfd],
+ Default::default(),
/*sandbox*/ None,
)
.await?;
diff --git a/codex-rs/core/tests/suite/codex_delegate.rs b/codex-rs/core/tests/suite/codex_delegate.rs
index 4b53f7ed26..d8cb4483f7 100644
--- a/codex-rs/core/tests/suite/codex_delegate.rs
+++ b/codex-rs/core/tests/suite/codex_delegate.rs
@@ -282,7 +282,7 @@ async fn codex_delegate_rejects_skill_mcp_dependency_installation_without_prompt
let agents_dir = skill_dir.join("agents");
fs.create_directory(
&PathUri::from_host_native_path(&agents_dir)?,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions { recursive: true, follow_symlinks: true },
/*sandbox*/ None,
)
.await?;
@@ -290,14 +290,14 @@ async fn codex_delegate_rejects_skill_mcp_dependency_installation_without_prompt
&PathUri::from_host_native_path(skill_dir.join("SKILL.md"))?,
b"---\nname: dependency-skill\ndescription: Requires an MCP server.\n---\n\nReview dependency instructions.\n"
.to_vec(),
- /*sandbox*/ None,
+ Default::default(), /*sandbox*/ None,
)
.await?;
fs.write_file(
&PathUri::from_host_native_path(agents_dir.join("openai.yaml"))?,
b"dependencies:\n tools:\n - type: mcp\n value: missing-review-server\n transport: streamable_http\n url: http://127.0.0.1:1/mcp\n"
.to_vec(),
- /*sandbox*/ None,
+ Default::default(), /*sandbox*/ None,
)
.await?;
Ok(())
diff --git a/codex-rs/core/tests/suite/guardian_review.rs b/codex-rs/core/tests/suite/guardian_review.rs
index a9ab69e15e..d758c8b1da 100644
--- a/codex-rs/core/tests/suite/guardian_review.rs
+++ b/codex-rs/core/tests/suite/guardian_review.rs
@@ -640,6 +640,7 @@ async fn guardian_session_is_reused_for_consecutive_tool_reviews_without_prewarm
fs.write_file(
&codex_utils_path_uri::PathUri::from_abs_path(&cwd.join("guardian-secret.txt")),
SECRET.as_bytes().to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
diff --git a/codex-rs/core/tests/suite/hooks.rs b/codex-rs/core/tests/suite/hooks.rs
index f4714df156..c6af1bc336 100644
--- a/codex-rs/core/tests/suite/hooks.rs
+++ b/codex-rs/core/tests/suite/hooks.rs
@@ -2915,7 +2915,12 @@ async fn permission_request_hook_allow_bypasses_strict_auto_review() -> Result<(
.cwd
.join(marker_name)?;
test.fs()
- .write_file(&marker, b"seed".to_vec(), /*sandbox*/ None)
+ .write_file(
+ &marker,
+ b"seed".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await
.context("create strict auto-review marker")?;
let (sandbox_policy, permission_profile) =
@@ -2964,7 +2969,7 @@ async fn permission_request_hook_allow_bypasses_strict_auto_review() -> Result<(
requests[2].function_call_output(command_call_id);
assert!(
test.fs()
- .read_file(&marker, /*sandbox*/ None)
+ .read_file(&marker, Default::default(), /*sandbox*/ None)
.await
.is_err(),
"hook-approved command should remove marker without Guardian review"
diff --git a/codex-rs/core/tests/suite/mcp_startup_refresh_http_proxy.rs b/codex-rs/core/tests/suite/mcp_startup_refresh_http_proxy.rs
index 12b87e1198..fff2535394 100644
--- a/codex-rs/core/tests/suite/mcp_startup_refresh_http_proxy.rs
+++ b/codex-rs/core/tests/suite/mcp_startup_refresh_http_proxy.rs
@@ -312,14 +312,14 @@ async fn skill_mcp_dependency_oauth_uses_configured_http_client() -> Result<()>
let agents_dir = skill_dir.join("agents");
fs.create_directory(
&PathUri::from_host_native_path(&agents_dir)?,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions { recursive: true, follow_symlinks: true },
/*sandbox*/ None,
)
.await?;
fs.write_file(
&PathUri::from_host_native_path(skill_dir.join("SKILL.md"))?,
b"---\nname: proxy-skill\ndescription: Uses a proxied MCP server.\n---\n".to_vec(),
- /*sandbox*/ None,
+ Default::default(), /*sandbox*/ None,
)
.await?;
let metadata = format!(
@@ -328,7 +328,7 @@ async fn skill_mcp_dependency_oauth_uses_configured_http_client() -> Result<()>
fs.write_file(
&PathUri::from_host_native_path(agents_dir.join("openai.yaml"))?,
metadata.into_bytes(),
- /*sandbox*/ None,
+ Default::default(), /*sandbox*/ None,
)
.await?;
Ok(())
diff --git a/codex-rs/core/tests/suite/mcp_tool_cache.rs b/codex-rs/core/tests/suite/mcp_tool_cache.rs
index 67795fac3b..a4c8b2fb9c 100644
--- a/codex-rs/core/tests/suite/mcp_tool_cache.rs
+++ b/codex-rs/core/tests/suite/mcp_tool_cache.rs
@@ -88,7 +88,10 @@ async fn wait_for_new_pid(
) -> anyhow::Result<String> {
tokio::time::timeout(Duration::from_secs(5), async {
loop {
- if let Ok(contents) = fs.read_file_text(path, /*sandbox*/ None).await {
+ if let Ok(contents) = fs
+ .read_file_text(path, Default::default(), /*sandbox*/ None)
+ .await
+ {
let pid = contents.trim();
if !pid.is_empty() && Some(pid) != previous_pid {
return pid.to_string();
@@ -447,8 +450,13 @@ async fn cached_mcp_startup_is_eager_for_root_and_lazy_for_subagents() -> anyhow
.start_or_steer_turn(user_turn("use the echo tool"))
.await?;
let first_pid = wait_for_new_pid(fs.as_ref(), &pid_file, /*previous_pid*/ None).await?;
- fs.write_file(&barrier_file, b"ready".to_vec(), /*sandbox*/ None)
- .await?;
+ fs.write_file(
+ &barrier_file,
+ b"ready".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
+ .await?;
wait_for_event(&fixture.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
@@ -477,6 +485,7 @@ async fn cached_mcp_startup_is_eager_for_root_and_lazy_for_subagents() -> anyhow
RemoveOptions {
recursive: false,
force: false,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -484,6 +493,7 @@ async fn cached_mcp_startup_is_eager_for_root_and_lazy_for_subagents() -> anyhow
fs.write_file(
&app_only_cwd_marker_file,
b"app-only".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -538,7 +548,9 @@ async fn cached_mcp_startup_is_eager_for_root_and_lazy_for_subagents() -> anyhow
&format!("Echo from {cached_process}."),
);
assert_eq!(
- fs.read_file_text(&pid_file, /*sandbox*/ None).await?.trim(),
+ fs.read_file_text(&pid_file, Default::default(), /*sandbox*/ None)
+ .await?
+ .trim(),
eager_pid,
"cached tool definitions should not start an unused subagent-owned MCP process"
);
@@ -642,8 +654,13 @@ async fn cached_mcp_startup_is_eager_for_root_and_lazy_for_subagents() -> anyhow
.context("the unrelated tool should emit its plan update")?;
fixture.codex.shutdown_and_wait().await?;
- fs.write_file(&barrier_file, b"ready".to_vec(), /*sandbox*/ None)
- .await?;
+ fs.write_file(
+ &barrier_file,
+ b"ready".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
+ .await?;
let expected_error = format!("MCP tool `{SERVER_NAME}/cwd` is not available to the model");
assert_eq!(cached_turn.await??, second_process);
assert_definition(
@@ -703,6 +720,7 @@ async fn cached_mcp_startup_is_eager_for_root_and_lazy_for_subagents() -> anyhow
RemoveOptions {
recursive: false,
force: false,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -751,8 +769,13 @@ async fn cached_mcp_startup_is_eager_for_root_and_lazy_for_subagents() -> anyhow
matches!(event, EventMsg::TurnAborted(_))
})
.await;
- fs.write_file(&barrier_file, b"ready".to_vec(), /*sandbox*/ None)
- .await?;
+ fs.write_file(
+ &barrier_file,
+ b"ready".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
+ .await?;
tokio::time::timeout(
Duration::from_secs(2),
wait_for_event(&interrupted_thread, |event| {
diff --git a/codex-rs/core/tests/suite/network_approval.rs b/codex-rs/core/tests/suite/network_approval.rs
index 6db81300d4..001c2936e1 100644
--- a/codex-rs/core/tests/suite/network_approval.rs
+++ b/codex-rs/core/tests/suite/network_approval.rs
@@ -1956,7 +1956,10 @@ async fn approved_network_host_for_one_environment_still_prompts_in_another() ->
test.fs()
.create_directory(
&remote_cwd_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -2031,6 +2034,7 @@ async fn approved_network_host_for_one_environment_still_prompts_in_another() ->
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
diff --git a/codex-rs/core/tests/suite/openai_file_mcp.rs b/codex-rs/core/tests/suite/openai_file_mcp.rs
index 724b45e234..80cbbb56c5 100644
--- a/codex-rs/core/tests/suite/openai_file_mcp.rs
+++ b/codex-rs/core/tests/suite/openai_file_mcp.rs
@@ -236,6 +236,7 @@ async fn codex_apps_file_params_omit_fields_absent_from_tool_schema() -> Result<
fs.write_file(
&report_path,
vec![b'x'; STREAMED_FILE_SIZE],
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -346,6 +347,7 @@ async fn codex_apps_file_params_stream_allowed_file_under_restricted_read_policy
fs.write_file(
&report_path,
vec![b'x'; STREAMED_FILE_SIZE],
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -380,8 +382,13 @@ async fn codex_apps_file_params_reject_denied_file_before_upload() -> Result<()>
.with_config(|config| restrict_apps_upload_reads(config, "report.txt"))
.with_workspace_setup(|cwd, fs| async move {
let report_path = PathUri::from_abs_path(&cwd.join("report.txt"));
- fs.write_file(&report_path, b"private".to_vec(), /*sandbox*/ None)
- .await?;
+ fs.write_file(
+ &report_path,
+ b"private".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
+ .await?;
Ok(())
});
let test = builder.build_with_auto_env(&server).await?;
diff --git a/codex-rs/core/tests/suite/remote_env.rs b/codex-rs/core/tests/suite/remote_env.rs
index b1aff33f7e..43819b1e00 100644
--- a/codex-rs/core/tests/suite/remote_env.rs
+++ b/codex-rs/core/tests/suite/remote_env.rs
@@ -293,10 +293,15 @@ async fn remote_test_env_can_connect_and_use_filesystem() -> Result<()> {
let payload = b"remote-test-env-ok".to_vec();
file_system
- .write_file(&file_path_uri, payload.clone(), /*sandbox*/ None)
+ .write_file(
+ &file_path_uri,
+ payload.clone(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await?;
let actual = file_system
- .read_file(&file_path_uri, /*sandbox*/ None)
+ .read_file(&file_path_uri, Default::default(), /*sandbox*/ None)
.await?;
assert_eq!(actual, payload);
@@ -306,6 +311,7 @@ async fn remote_test_env_can_connect_and_use_filesystem() -> Result<()> {
RemoveOptions {
recursive: false,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -625,7 +631,7 @@ async fn environment_permissions_follow_configuration_ownership() -> Result<()>
assert!(!output.contains("WRITE_SUCCEEDED"));
assert!(
test.fs()
- .read_file_text(&marker, /*sandbox*/ None)
+ .read_file_text(&marker, Default::default(), /*sandbox*/ None)
.await
.is_err(),
"read-only attachment unexpectedly wrote {FILE_NAME}"
@@ -2756,7 +2762,10 @@ async fn exec_command_routes_to_selected_remote_environment() -> Result<()> {
test.fs()
.create_directory(
&remote_cwd_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -2764,6 +2773,7 @@ async fn exec_command_routes_to_selected_remote_environment() -> Result<()> {
.write_file(
&remote_marker_uri,
b"remote-routing".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -2802,6 +2812,7 @@ async fn exec_command_routes_to_selected_remote_environment() -> Result<()> {
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -2834,7 +2845,10 @@ async fn remote_exec_materializes_target_roots_before_sandbox_selection() -> Res
test.fs()
.create_directory(
&remote_cwd_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -2842,6 +2856,7 @@ async fn remote_exec_materializes_target_roots_before_sandbox_selection() -> Res
.write_file(
&remote_cwd_uri.join(SECRET_FILE)?,
SECRET.as_bytes().to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -2958,6 +2973,7 @@ async fn remote_exec_materializes_target_roots_before_sandbox_selection() -> Res
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -3010,7 +3026,10 @@ async fn remote_request_permissions_grant_unblocks_later_remote_exec() -> Result
test.fs()
.create_directory(
&remote_write_root_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -3149,6 +3168,7 @@ async fn remote_request_permissions_grant_unblocks_later_remote_exec() -> Result
test.fs()
.read_file_text(
&PathUri::from_host_native_path(&remote_target_path)?,
+ Default::default(),
/*sandbox*/ None,
)
.await?,
@@ -3165,6 +3185,7 @@ async fn remote_request_permissions_grant_unblocks_later_remote_exec() -> Result
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -3194,7 +3215,10 @@ async fn apply_patch_freeform_routes_to_selected_remote_environment() -> Result<
test.fs()
.create_directory(
&remote_cwd_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -3238,6 +3262,7 @@ async fn apply_patch_freeform_routes_to_selected_remote_environment() -> Result<
.fs()
.read_file_text(
&PathUri::from_host_native_path(remote_cwd.join(file_name))?,
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -3253,6 +3278,7 @@ async fn apply_patch_freeform_routes_to_selected_remote_environment() -> Result<
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -3284,7 +3310,10 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
test.fs()
.create_directory(
&remote_cwd_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -3302,6 +3331,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
RemoveOptions {
recursive: false,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -3406,7 +3436,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
.await;
assert_eq!(
test.fs()
- .read_file_text(&target_path_uri, /*sandbox*/ None)
+ .read_file_text(&target_path_uri, Default::default(), /*sandbox*/ None)
.await?,
"remote\n"
);
@@ -3421,7 +3451,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
wait_for_completion_without_patch_approval(&test).await;
assert_eq!(
test.fs()
- .read_file_text(&target_path_uri, /*sandbox*/ None)
+ .read_file_text(&target_path_uri, Default::default(), /*sandbox*/ None)
.await?,
"remote updated\n"
);
@@ -3433,6 +3463,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
RemoveOptions {
recursive: false,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -3443,6 +3474,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -3472,7 +3504,10 @@ async fn apply_patch_intercepted_exec_command_routes_to_selected_remote_environm
test.fs()
.create_directory(
&remote_cwd_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -3526,6 +3561,7 @@ async fn apply_patch_intercepted_exec_command_routes_to_selected_remote_environm
.fs()
.read_file_text(
&PathUri::from_host_native_path(remote_cwd.join(file_name))?,
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -3541,6 +3577,7 @@ async fn apply_patch_intercepted_exec_command_routes_to_selected_remote_environm
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -3566,7 +3603,10 @@ async fn remote_test_env_sandboxed_read_allows_readable_root() -> Result<()> {
file_system
.create_directory(
&allowed_dir_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -3574,13 +3614,14 @@ async fn remote_test_env_sandboxed_read_allows_readable_root() -> Result<()> {
.write_file(
&file_path_uri,
b"sandboxed hello".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await?;
let sandbox = read_only_sandbox(allowed_dir.clone());
let contents = file_system
- .read_file(&file_path_uri, Some(&sandbox))
+ .read_file(&file_path_uri, Default::default(), Some(&sandbox))
.await?;
assert_eq!(contents, b"sandboxed hello");
@@ -3590,6 +3631,7 @@ async fn remote_test_env_sandboxed_read_allows_readable_root() -> Result<()> {
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -3622,7 +3664,10 @@ async fn remote_test_env_sandboxed_read_rejects_symlink_parent_dotdot_escape() -
let requested_path =
PathUri::from_host_native_path(allowed_dir.join("link").join("..").join("secret.txt"))?;
let sandbox = read_only_sandbox(allowed_dir.clone());
- let error = match file_system.read_file(&requested_path, Some(&sandbox)).await {
+ let error = match file_system
+ .read_file(&requested_path, Default::default(), Some(&sandbox))
+ .await
+ {
Ok(_) => anyhow::bail!("read should fail after path normalization"),
Err(error) => error,
};
@@ -3670,6 +3715,7 @@ async fn remote_test_env_remove_removes_symlink_not_target() -> Result<()> {
RemoveOptions {
recursive: false,
force: false,
+ follow_symlinks: true,
},
Some(&sandbox),
)
@@ -3678,6 +3724,7 @@ async fn remote_test_env_remove_removes_symlink_not_target() -> Result<()> {
let symlink_exists = file_system
.get_metadata(
&PathUri::from_abs_path(&absolute_path(symlink_path)),
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -3686,6 +3733,7 @@ async fn remote_test_env_remove_removes_symlink_not_target() -> Result<()> {
let outside = file_system
.read_file_text(
&PathUri::from_host_native_path(&outside_file)?,
+ Default::default(),
/*sandbox*/ None,
)
.await?;
@@ -3697,6 +3745,7 @@ async fn remote_test_env_remove_removes_symlink_not_target() -> Result<()> {
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -3769,6 +3818,7 @@ async fn remote_test_env_copy_preserves_symlink_source() -> Result<()> {
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
diff --git a/codex-rs/core/tests/suite/request_plugin_install.rs b/codex-rs/core/tests/suite/request_plugin_install.rs
index b70e5b5ca9..571697f24c 100644
--- a/codex-rs/core/tests/suite/request_plugin_install.rs
+++ b/codex-rs/core/tests/suite/request_plugin_install.rs
@@ -233,7 +233,7 @@ async fn start_gated_step_preparation(test: &TestCodex, server: &MockServer) ->
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let mcp_started = fs
- .read_file_text(&pid_file, /*sandbox*/ None)
+ .read_file_text(&pid_file, Default::default(), /*sandbox*/ None)
.await
.is_ok_and(|pid| !pid.trim().is_empty());
let recommendation_count = server
@@ -424,7 +424,12 @@ async fn mcp_discovery_overlaps_endpoint_plugin_recommendations() -> Result<()>
"sampling should wait for the complete MCP catalog"
);
test.fs()
- .write_file(&barrier, b"ready".to_vec(), /*sandbox*/ None)
+ .write_file(
+ &barrier,
+ b"ready".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
@@ -489,7 +494,12 @@ async fn interrupting_concurrent_step_preparation_prevents_sampling() -> Result<
);
test.fs()
- .write_file(&barrier, b"ready".to_vec(), /*sandbox*/ None)
+ .write_file(
+ &barrier,
+ b"ready".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await?;
test.codex.shutdown_and_wait().await?;
assert!(
diff --git a/codex-rs/core/tests/suite/review.rs b/codex-rs/core/tests/suite/review.rs
index 2007b9edac..f095d56e55 100644
--- a/codex-rs/core/tests/suite/review.rs
+++ b/codex-rs/core/tests/suite/review.rs
@@ -652,7 +652,10 @@ async fn review_uses_updated_turn_permissions_and_approval_policy() {
test.fs()
.create_directory(
&selection.cwd,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await
diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs
index 247528921b..06c631a370 100644
--- a/codex-rs/core/tests/suite/rmcp_client.rs
+++ b/codex-rs/core/tests/suite/rmcp_client.rs
@@ -1421,7 +1421,10 @@ async fn stdio_server_uses_configured_cwd_before_runtime_fallback() -> anyhow::R
let configured_cwd_uri = PathUri::from_host_native_path(&configured_cwd)?;
fs.create_directory(
&configured_cwd_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
diff --git a/codex-rs/core/tests/suite/skills.rs b/codex-rs/core/tests/suite/skills.rs
index fcc632ed14..cd84ad1e81 100644
--- a/codex-rs/core/tests/suite/skills.rs
+++ b/codex-rs/core/tests/suite/skills.rs
@@ -45,15 +45,23 @@ async fn write_repo_skill(
let skill_dir_uri = PathUri::from_host_native_path(&skill_dir)?;
fs.create_directory(
&skill_dir_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
let contents = format!("---\nname: {name}\ndescription: {description}\n---\n\n{body}\n");
let path = skill_dir.join("SKILL.md");
let path_uri = PathUri::from_host_native_path(&path)?;
- fs.write_file(&path_uri, contents.into_bytes(), /*sandbox*/ None)
- .await?;
+ fs.write_file(
+ &path_uri,
+ contents.into_bytes(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
+ .await?;
Ok(())
}
diff --git a/codex-rs/core/tests/suite/skills_extension.rs b/codex-rs/core/tests/suite/skills_extension.rs
index d7b0211e6c..e7c3091df4 100644
--- a/codex-rs/core/tests/suite/skills_extension.rs
+++ b/codex-rs/core/tests/suite/skills_extension.rs
@@ -548,7 +548,7 @@ async fn capability_sections_render_in_order_with_host_repo_and_plugin_skills()
let skill_dir = cwd.join(".agents/skills/repo-search");
fs.create_directory(
&PathUri::from_host_native_path(&skill_dir)?,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions { recursive: true, follow_symlinks: true },
/*sandbox*/ None,
)
.await?;
@@ -558,7 +558,7 @@ async fn capability_sections_render_in_order_with_host_repo_and_plugin_skills()
"---\nname: repo-search\ndescription: inspect repo data\n---\n\n{REPO_SKILL_BODY}\n"
)
.into_bytes(),
- /*sandbox*/ None,
+ Default::default(), /*sandbox*/ None,
)
.await?;
Ok(())
diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs
index afd4ee05d1..d28dc6b79b 100644
--- a/codex-rs/core/tests/suite/unified_exec.rs
+++ b/codex-rs/core/tests/suite/unified_exec.rs
@@ -242,7 +242,10 @@ async fn create_workspace_directory(
test.fs()
.create_directory(
&abs_path_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs
index 75eb32dbdc..f39a1f3c77 100644
--- a/codex-rs/core/tests/suite/view_image.rs
+++ b/codex-rs/core/tests/suite/view_image.rs
@@ -166,7 +166,10 @@ async fn create_workspace_directory(test: &TestCodex, rel_path: &str) -> anyhow:
test.fs()
.create_directory(
&abs_path_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -183,13 +186,21 @@ async fn write_workspace_file(
test.fs()
.create_directory(
&parent_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
}
test.fs()
- .write_file(&abs_path_uri, contents, /*sandbox*/ None)
+ .write_file(
+ &abs_path_uri,
+ contents,
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await?;
Ok(abs_path_uri.to_path_buf())
}
@@ -728,7 +739,12 @@ async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<()
let image_path_uri = remote_cwd_uri.join("remote.png")?;
let png = png_bytes(/*width*/ 1, /*height*/ 1, [0, 255, 0, 255])?;
test.fs()
- .write_file(&image_path_uri, png, /*sandbox*/ None)
+ .write_file(
+ &image_path_uri,
+ png,
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await?;
let absolute_image_path = image_path_uri.inferred_native_path_string();
let remote_selection = TurnEnvironmentSelection {
@@ -810,6 +826,7 @@ async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<()
RemoveOptions {
recursive: false,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
diff --git a/codex-rs/core/tests/suite/workspace_roots.rs b/codex-rs/core/tests/suite/workspace_roots.rs
index 6ad6fa3e1f..c83525647f 100644
--- a/codex-rs/core/tests/suite/workspace_roots.rs
+++ b/codex-rs/core/tests/suite/workspace_roots.rs
@@ -125,7 +125,9 @@ async fn submit_workspace_turn(test: &TestCodex, prompt: &str) -> Result<()> {
async fn read_file(test: &TestCodex, path: &PathUri) -> Result<String> {
Ok(String::from_utf8(
- test.fs().read_file(path, /*sandbox*/ None).await?,
+ test.fs()
+ .read_file(path, Default::default(), /*sandbox*/ None)
+ .await?,
)?)
}
@@ -137,6 +139,7 @@ async fn remove_files(test: &TestCodex, paths: &[&PathUri]) -> Result<()> {
RemoveOptions {
recursive: false,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -233,7 +236,10 @@ async fn workspace_roots_allow_apply_patch_in_secondary_root() -> Result<()> {
.join(sibling_workspace_root_name(&cwd, SECONDARY_ROOT_NAME));
fs.create_directory(
&PathUri::from_abs_path(&secondary_root),
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -289,6 +295,7 @@ async fn workspace_roots_allow_apply_patch_in_secondary_root() -> Result<()> {
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -314,7 +321,10 @@ async fn workspace_roots_allow_patches_but_protect_metadata_directories() -> Res
test.fs()
.create_directory(
&cwd.join(directory)?,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
@@ -377,7 +387,7 @@ async fn workspace_roots_allow_patches_but_protect_metadata_directories() -> Res
let protected_path = cwd.join(directory)?.join("protected.txt")?;
let error = test
.fs()
- .get_metadata(&protected_path, /*sandbox*/ None)
+ .get_metadata(&protected_path, Default::default(), /*sandbox*/ None)
.await
.expect_err("protected metadata file should not be created");
assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
@@ -441,13 +451,13 @@ async fn workspace_roots_deny_file_and_command_writes_outside_roots() -> Result<
);
assert!(
test.fs()
- .read_file(&patch_path, /*sandbox*/ None)
+ .read_file(&patch_path, Default::default(), /*sandbox*/ None)
.await
.is_err()
);
assert!(
test.fs()
- .read_file(&command_path, /*sandbox*/ None)
+ .read_file(&command_path, Default::default(), /*sandbox*/ None)
.await
.is_err()
);
diff --git a/codex-rs/exec-server-protocol/src/protocol.rs b/codex-rs/exec-server-protocol/src/protocol.rs
index 34cb686fa6..8095b662d6 100644
--- a/codex-rs/exec-server-protocol/src/protocol.rs
+++ b/codex-rs/exec-server-protocol/src/protocol.rs
@@ -361,6 +361,8 @@ pub struct TerminateResponse {
#[serde(rename_all = "camelCase")]
pub struct FsReadFileParams {
pub path: PathUri,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub follow_symlinks: Option<bool>,
pub sandbox: Option<FileSystemSandboxContext>,
}
@@ -414,6 +416,8 @@ pub struct FsCloseResponse {}
pub struct FsWriteFileParams {
pub path: PathUri,
pub data_base64: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub follow_symlinks: Option<bool>,
pub sandbox: Option<FileSystemSandboxContext>,
}
@@ -426,6 +430,8 @@ pub struct FsWriteFileResponse {}
pub struct FsCreateDirectoryParams {
pub path: PathUri,
pub recursive: Option<bool>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub follow_symlinks: Option<bool>,
pub sandbox: Option<FileSystemSandboxContext>,
/// Atomically restrict a newly created, non-recursive directory to its owner.
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -440,6 +446,8 @@ pub struct FsCreateDirectoryResponse {}
#[serde(rename_all = "camelCase")]
pub struct FsGetMetadataParams {
pub path: PathUri,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub follow_symlinks: Option<bool>,
pub sandbox: Option<FileSystemSandboxContext>,
}
@@ -504,6 +512,8 @@ pub struct FsRemoveParams {
pub path: PathUri,
pub recursive: Option<bool>,
pub force: Option<bool>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub follow_symlinks: Option<bool>,
pub sandbox: Option<FileSystemSandboxContext>,
}
diff --git a/codex-rs/exec-server/Cargo.toml b/codex-rs/exec-server/Cargo.toml
index e69e7d7bd4..20ecc463d6 100644
--- a/codex-rs/exec-server/Cargo.toml
+++ b/codex-rs/exec-server/Cargo.toml
@@ -58,12 +58,16 @@ uuid = { workspace = true, features = ["v4"] }
[target.'cfg(unix)'.dependencies]
libc = { workspace = true }
-rustix = { workspace = true }
+rustix = { workspace = true, features = ["fs"] }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.52", features = [
"Win32_Foundation",
+ "Win32_Security",
"Win32_Storage_FileSystem",
+ "Win32_System_IO",
+ "Win32_System_Kernel",
+ "Win32_System_Pipes",
"Win32_System_Threading",
] }
diff --git a/codex-rs/exec-server/src/capability_discovery.rs b/codex-rs/exec-server/src/capability_discovery.rs
index d2c9253eb2..43721630e2 100644
--- a/codex-rs/exec-server/src/capability_discovery.rs
+++ b/codex-rs/exec-server/src/capability_discovery.rs
@@ -86,7 +86,10 @@ async fn discover_root(
return discovery;
}
- match file_system.get_metadata(&path, sandbox).await {
+ match file_system
+ .get_metadata(&path, Default::default(), sandbox)
+ .await
+ {
Ok(metadata) if metadata.is_directory => {}
Ok(_) => {
discovery.error = Some(format!("capability root {path} is not a directory"));
@@ -329,7 +332,10 @@ async fn read_optional_text_file(
budget: &mut BundleBudget,
warnings: &mut Vec<String>,
) -> Option<CapabilityTextFile> {
- let metadata = match file_system.get_metadata(&path, sandbox).await {
+ let metadata = match file_system
+ .get_metadata(&path, Default::default(), sandbox)
+ .await
+ {
Ok(metadata) if metadata.is_file => metadata,
Ok(_) => return None,
Err(error) if error.kind() == io::ErrorKind::NotFound => return None,
diff --git a/codex-rs/exec-server/src/environment.rs b/codex-rs/exec-server/src/environment.rs
index 1bca7c9408..1b93c7e47c 100644
--- a/codex-rs/exec-server/src/environment.rs
+++ b/codex-rs/exec-server/src/environment.rs
@@ -919,6 +919,7 @@ impl Environment {
.fs_create_directory(FsCreateDirectoryParams {
path: path.clone(),
recursive: Some(false),
+ follow_symlinks: None,
sandbox: None,
private: Some(true),
})
@@ -1840,7 +1841,7 @@ mod tests {
let err = environment
.get_filesystem()
- .read_file(&path, Some(&sandbox))
+ .read_file(&path, Default::default(), Some(&sandbox))
.await
.expect_err("sandboxed read should require runtime paths");
diff --git a/codex-rs/exec-server/src/fs_helper.rs b/codex-rs/exec-server/src/fs_helper.rs
index 53e2f56881..e519215faf 100644
--- a/codex-rs/exec-server/src/fs_helper.rs
+++ b/codex-rs/exec-server/src/fs_helper.rs
@@ -8,7 +8,10 @@ use tokio::io;
use crate::CopyOptions;
use crate::CreateDirectoryOptions;
use crate::ExecutorFileSystem;
+use crate::GetMetadataOptions;
+use crate::ReadFileOptions;
use crate::RemoveOptions;
+use crate::WriteFileOptions;
use crate::local_file_system::DirectFileSystem;
use crate::protocol::FS_CANONICALIZE_METHOD;
use crate::protocol::FS_COPY_METHOD;
@@ -225,7 +228,13 @@ pub(crate) async fn run_direct_request(
)),
FsHelperRequest::ReadFile(params) => {
let data = file_system
- .read_file(&params.path, /*sandbox*/ None)
+ .read_file(
+ &params.path,
+ ReadFileOptions {
+ follow_symlinks: params.follow_symlinks.unwrap_or(true),
+ },
+ /*sandbox*/ None,
+ )
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::ReadFile(FsReadFileResponse {
@@ -239,7 +248,14 @@ pub(crate) async fn run_direct_request(
))
})?;
file_system
- .write_file(&params.path, bytes, /*sandbox*/ None)
+ .write_file(
+ &params.path,
+ bytes,
+ WriteFileOptions {
+ follow_symlinks: params.follow_symlinks.unwrap_or(true),
+ },
+ /*sandbox*/ None,
+ )
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::WriteFile(FsWriteFileResponse {}))
@@ -250,6 +266,7 @@ pub(crate) async fn run_direct_request(
&params.path,
CreateDirectoryOptions {
recursive: params.recursive.unwrap_or(true),
+ follow_symlinks: params.follow_symlinks.unwrap_or(true),
},
/*sandbox*/ None,
)
@@ -261,7 +278,13 @@ pub(crate) async fn run_direct_request(
}
FsHelperRequest::GetMetadata(params) => {
let metadata = file_system
- .get_metadata(&params.path, /*sandbox*/ None)
+ .get_metadata(
+ &params.path,
+ GetMetadataOptions {
+ follow_symlinks: params.follow_symlinks.unwrap_or(true),
+ },
+ /*sandbox*/ None,
+ )
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::GetMetadata(FsGetMetadataResponse {
@@ -312,6 +335,7 @@ pub(crate) async fn run_direct_request(
RemoveOptions {
recursive: params.recursive.unwrap_or(true),
force: params.force.unwrap_or(true),
+ follow_symlinks: params.follow_symlinks.unwrap_or(true),
},
/*sandbox*/ None,
)
@@ -370,6 +394,7 @@ mod tests {
let request = serde_json::to_value(FsHelperRequest::WriteFile(FsWriteFileParams {
path: path.clone(),
data_base64: String::new(),
+ follow_symlinks: None,
sandbox: None,
}))?;
assert_eq!(
diff --git a/codex-rs/exec-server/src/lib.rs b/codex-rs/exec-server/src/lib.rs
index 997510a04c..a840bf8fef 100644
--- a/codex-rs/exec-server/src/lib.rs
+++ b/codex-rs/exec-server/src/lib.rs
@@ -19,6 +19,7 @@ mod fs_sandbox;
mod local_file_system;
mod local_process;
mod network_policy_decisions;
+mod no_follow;
mod noise_channel;
mod noise_relay;
mod process;
@@ -72,13 +73,16 @@ pub use codex_file_system::FileMetadata;
pub use codex_file_system::FileSystemReadStream;
pub use codex_file_system::FileSystemResult;
pub use codex_file_system::FileSystemSandboxContext;
+pub use codex_file_system::GetMetadataOptions;
pub use codex_file_system::ReadDirectoryEntry;
+pub use codex_file_system::ReadFileOptions;
pub use codex_file_system::RemoveOptions;
pub use codex_file_system::WalkEntry;
pub use codex_file_system::WalkEntryKind;
pub use codex_file_system::WalkError;
pub use codex_file_system::WalkOptions;
pub use codex_file_system::WalkOutcome;
+pub use codex_file_system::WriteFileOptions;
pub use codex_protocol::shell_environment::CODEX_EXEC_SERVER_NOISE_AUTH_TOKEN_ENV_VAR;
pub use environment::CODEX_EXEC_SERVER_NOISE_CHATGPT_ACCOUNT_ID_ENV_VAR;
pub use environment::CODEX_EXEC_SERVER_NOISE_ENVIRONMENT_ID_ENV_VAR;
diff --git a/codex-rs/exec-server/src/local_file_system.rs b/codex-rs/exec-server/src/local_file_system.rs
index 852ba3d26d..c1cd76061b 100644
--- a/codex-rs/exec-server/src/local_file_system.rs
+++ b/codex-rs/exec-server/src/local_file_system.rs
@@ -20,10 +20,14 @@ use crate::FileMetadata;
use crate::FileSystemReadStream;
use crate::FileSystemResult;
use crate::FileSystemSandboxContext;
+use crate::GetMetadataOptions;
use crate::ReadDirectoryEntry;
+use crate::ReadFileOptions;
use crate::RemoveOptions;
use crate::WalkOptions;
use crate::WalkOutcome;
+use crate::WriteFileOptions;
+use crate::no_follow;
use crate::regular_file;
use crate::sandboxed_file_system::SandboxedFileSystem;
@@ -116,10 +120,11 @@ impl LocalFileSystem {
async fn read_file(
&self,
path: &PathUri,
+ options: ReadFileOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>> {
let (file_system, sandbox) = self.file_system_for(sandbox)?;
- file_system.read_file(path, sandbox).await
+ file_system.read_file(path, options, sandbox).await
}
async fn read_file_stream(
@@ -135,10 +140,13 @@ impl LocalFileSystem {
&self,
path: &PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<()> {
let (file_system, sandbox) = self.file_system_for(sandbox)?;
- file_system.write_file(path, contents, sandbox).await
+ file_system
+ .write_file(path, contents, options, sandbox)
+ .await
}
async fn create_directory(
@@ -154,10 +162,11 @@ impl LocalFileSystem {
async fn get_metadata(
&self,
path: &PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
let (file_system, sandbox) = self.file_system_for(sandbox)?;
- file_system.get_metadata(path, sandbox).await
+ file_system.get_metadata(path, options, sandbox).await
}
async fn read_directory(
@@ -215,9 +224,10 @@ impl ExecutorFileSystem for LocalFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ options: ReadFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
- Box::pin(LocalFileSystem::read_file(self, path, sandbox))
+ Box::pin(LocalFileSystem::read_file(self, path, options, sandbox))
}
fn read_file_stream<'a>(
@@ -232,9 +242,12 @@ impl ExecutorFileSystem for LocalFileSystem {
&'a self,
path: &'a PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
- Box::pin(LocalFileSystem::write_file(self, path, contents, sandbox))
+ Box::pin(LocalFileSystem::write_file(
+ self, path, contents, options, sandbox,
+ ))
}
fn create_directory<'a>(
@@ -251,9 +264,10 @@ impl ExecutorFileSystem for LocalFileSystem {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
- Box::pin(LocalFileSystem::get_metadata(self, path, sandbox))
+ Box::pin(LocalFileSystem::get_metadata(self, path, options, sandbox))
}
fn read_directory<'a>(
@@ -323,10 +337,13 @@ impl UnsandboxedFileSystem {
async fn read_file(
&self,
path: &PathUri,
+ options: ReadFileOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>> {
reject_platform_sandbox_context(sandbox)?;
- self.file_system.read_file(path, /*sandbox*/ None).await
+ self.file_system
+ .read_file(path, options, /*sandbox*/ None)
+ .await
}
async fn read_file_stream(
@@ -344,11 +361,12 @@ impl UnsandboxedFileSystem {
&self,
path: &PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<()> {
reject_platform_sandbox_context(sandbox)?;
self.file_system
- .write_file(path, contents, /*sandbox*/ None)
+ .write_file(path, contents, options, /*sandbox*/ None)
.await
}
@@ -367,10 +385,13 @@ impl UnsandboxedFileSystem {
async fn get_metadata(
&self,
path: &PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
reject_platform_sandbox_context(sandbox)?;
- self.file_system.get_metadata(path, /*sandbox*/ None).await
+ self.file_system
+ .get_metadata(path, options, /*sandbox*/ None)
+ .await
}
async fn read_directory(
@@ -427,9 +448,12 @@ impl ExecutorFileSystem for UnsandboxedFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ options: ReadFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
- Box::pin(UnsandboxedFileSystem::read_file(self, path, sandbox))
+ Box::pin(UnsandboxedFileSystem::read_file(
+ self, path, options, sandbox,
+ ))
}
fn read_file_stream<'a>(
@@ -444,10 +468,11 @@ impl ExecutorFileSystem for UnsandboxedFileSystem {
&'a self,
path: &'a PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
Box::pin(UnsandboxedFileSystem::write_file(
- self, path, contents, sandbox,
+ self, path, contents, options, sandbox,
))
}
@@ -465,9 +490,12 @@ impl ExecutorFileSystem for UnsandboxedFileSystem {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
- Box::pin(UnsandboxedFileSystem::get_metadata(self, path, sandbox))
+ Box::pin(UnsandboxedFileSystem::get_metadata(
+ self, path, options, sandbox,
+ ))
}
fn read_directory<'a>(
@@ -530,9 +558,15 @@ impl DirectFileSystem {
async fn read_file(
&self,
path: &PathUri,
+ options: ReadFileOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>> {
- let file = self.open_file_for_read(path, sandbox).await?;
+ reject_sandbox_context(sandbox)?;
+ let file = if options.follow_symlinks {
+ self.open_file_for_read(path, /*sandbox*/ None).await?
+ } else {
+ no_follow::open_file(path.to_abs_path()?.as_path()).await?
+ };
let metadata = file.metadata().await?;
if metadata.len() > MAX_READ_FILE_BYTES {
return Err(file_too_large_error());
@@ -563,11 +597,16 @@ impl DirectFileSystem {
&self,
path: &PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<()> {
reject_sandbox_context(sandbox)?;
let path = path.to_abs_path()?;
- tokio::fs::write(path.as_path(), contents).await
+ if options.follow_symlinks {
+ tokio::fs::write(path.as_path(), contents).await
+ } else {
+ no_follow::write_file(path.as_path(), contents).await
+ }
}
async fn create_directory(
@@ -578,6 +617,9 @@ impl DirectFileSystem {
) -> FileSystemResult<()> {
reject_sandbox_context(sandbox)?;
let path = path.to_abs_path()?;
+ if !options.follow_symlinks {
+ return no_follow::create_directory(path.as_path(), options.recursive).await;
+ }
if options.recursive {
tokio::fs::create_dir_all(path.as_path()).await?;
} else {
@@ -589,10 +631,14 @@ impl DirectFileSystem {
async fn get_metadata(
&self,
path: &PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
reject_sandbox_context(sandbox)?;
let path = path.to_abs_path()?;
+ if !options.follow_symlinks {
+ return no_follow::metadata(path.as_path()).await;
+ }
let symlink_metadata = tokio::fs::symlink_metadata(path.as_path()).await?;
let is_symlink = symlink_metadata.is_symlink();
let metadata = if is_symlink {
@@ -600,14 +646,7 @@ impl DirectFileSystem {
} else {
symlink_metadata
};
- Ok(FileMetadata {
- is_directory: metadata.is_dir(),
- is_file: metadata.is_file(),
- is_symlink,
- size: metadata.len(),
- created_at_ms: metadata.created().ok().map_or(0, system_time_to_unix_ms),
- modified_at_ms: metadata.modified().ok().map_or(0, system_time_to_unix_ms),
- })
+ Ok(file_metadata(metadata, is_symlink))
}
async fn read_directory(
@@ -646,6 +685,9 @@ impl DirectFileSystem {
) -> FileSystemResult<()> {
reject_sandbox_context(sandbox)?;
let path = path.to_abs_path()?;
+ if !options.follow_symlinks {
+ return no_follow::remove(path.as_path(), options.recursive, options.force).await;
+ }
match tokio::fs::symlink_metadata(path.as_path()).await {
Ok(metadata) => {
let file_type = metadata.file_type();
@@ -731,9 +773,10 @@ impl ExecutorFileSystem for DirectFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ options: ReadFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
- Box::pin(DirectFileSystem::read_file(self, path, sandbox))
+ Box::pin(DirectFileSystem::read_file(self, path, options, sandbox))
}
fn read_file_stream<'a>(
@@ -748,9 +791,12 @@ impl ExecutorFileSystem for DirectFileSystem {
&'a self,
path: &'a PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
- Box::pin(DirectFileSystem::write_file(self, path, contents, sandbox))
+ Box::pin(DirectFileSystem::write_file(
+ self, path, contents, options, sandbox,
+ ))
}
fn create_directory<'a>(
@@ -767,9 +813,10 @@ impl ExecutorFileSystem for DirectFileSystem {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
- Box::pin(DirectFileSystem::get_metadata(self, path, sandbox))
+ Box::pin(DirectFileSystem::get_metadata(self, path, options, sandbox))
}
fn read_directory<'a>(
@@ -816,6 +863,17 @@ fn reject_sandbox_context(sandbox: Option<&FileSystemSandboxContext>) -> io::Res
Ok(())
}
+fn file_metadata(metadata: std::fs::Metadata, is_symlink: bool) -> FileMetadata {
+ FileMetadata {
+ is_directory: metadata.is_dir(),
+ is_file: metadata.is_file(),
+ is_symlink,
+ size: metadata.len(),
+ created_at_ms: metadata.created().ok().map_or(0, system_time_to_unix_ms),
+ modified_at_ms: metadata.modified().ok().map_or(0, system_time_to_unix_ms),
+ }
+}
+
fn reject_platform_sandbox_context(sandbox: Option<&FileSystemSandboxContext>) -> io::Result<()> {
if sandbox.is_some_and(FileSystemSandboxContext::should_run_in_sandbox) {
return Err(io::Error::new(
diff --git a/codex-rs/exec-server/src/local_file_system_path_uri_tests.rs b/codex-rs/exec-server/src/local_file_system_path_uri_tests.rs
index dcddd98e08..78a48c5302 100644
--- a/codex-rs/exec-server/src/local_file_system_path_uri_tests.rs
+++ b/codex-rs/exec-server/src/local_file_system_path_uri_tests.rs
@@ -7,7 +7,7 @@ use super::*;
#[tokio::test]
async fn direct_file_system_rejects_non_native_uri_as_invalid_input() {
let error = DirectFileSystem
- .read_file(&non_native_uri(), /*sandbox*/ None)
+ .read_file(&non_native_uri(), Default::default(), /*sandbox*/ None)
.await
.expect_err("non-native URI should be rejected");
diff --git a/codex-rs/exec-server/src/no_follow/mod.rs b/codex-rs/exec-server/src/no_follow/mod.rs
new file mode 100644
index 0000000000..54461e887c
--- /dev/null
+++ b/codex-rs/exec-server/src/no_follow/mod.rs
@@ -0,0 +1,60 @@
+use crate::FileMetadata;
+use std::io;
+use std::path::Path;
+#[cfg(windows)]
+use std::time::SystemTime;
+#[cfg(windows)]
+use std::time::UNIX_EPOCH;
+
+#[cfg(unix)]
+mod unix;
+#[cfg(windows)]
+mod windows;
+
+#[cfg(unix)]
+use unix as imp;
+#[cfg(windows)]
+use windows as imp;
+
+pub(crate) async fn open_file(path: &Path) -> io::Result<tokio::fs::File> {
+ imp::open_file(path.to_path_buf()).await
+}
+
+pub(crate) async fn write_file(path: &Path, contents: Vec<u8>) -> io::Result<()> {
+ imp::write_file(path.to_path_buf(), contents).await
+}
+
+#[cfg(unix)]
+pub(crate) async fn metadata(path: &Path) -> io::Result<FileMetadata> {
+ imp::metadata(path.to_path_buf()).await
+}
+
+#[cfg(windows)]
+pub(crate) async fn metadata(path: &Path) -> io::Result<FileMetadata> {
+ imp::metadata(path.to_path_buf())
+ .await
+ .map(|metadata| FileMetadata {
+ is_directory: metadata.is_dir(),
+ is_file: metadata.is_file(),
+ is_symlink: false,
+ size: metadata.len(),
+ created_at_ms: metadata.created().ok().map_or(0, system_time_to_unix_ms),
+ modified_at_ms: metadata.modified().ok().map_or(0, system_time_to_unix_ms),
+ })
+}
+
+#[cfg(windows)]
+fn system_time_to_unix_ms(time: SystemTime) -> i64 {
+ time.duration_since(UNIX_EPOCH)
+ .ok()
+ .and_then(|duration| i64::try_from(duration.as_millis()).ok())
+ .unwrap_or(0)
+}
+
+pub(crate) async fn create_directory(path: &Path, recursive: bool) -> io::Result<()> {
+ imp::create_directory(path.to_path_buf(), recursive).await
+}
+
+pub(crate) async fn remove(path: &Path, recursive: bool, force: bool) -> io::Result<()> {
+ imp::remove(path.to_path_buf(), recursive, force).await
+}
diff --git a/codex-rs/exec-server/src/no_follow/unix.rs b/codex-rs/exec-server/src/no_follow/unix.rs
new file mode 100644
index 0000000000..225704a36f
--- /dev/null
+++ b/codex-rs/exec-server/src/no_follow/unix.rs
@@ -0,0 +1,263 @@
+use crate::FileMetadata;
+use rustix::fs::AtFlags;
+use rustix::fs::Mode;
+use rustix::fs::OFlags;
+use rustix::fs::Stat;
+use rustix::fs::fstat;
+use rustix::fs::mkdirat;
+use rustix::fs::open;
+use rustix::fs::openat;
+use rustix::fs::statat;
+use rustix::fs::unlinkat;
+use std::ffi::OsString;
+use std::io;
+use std::io::Write;
+use std::os::fd::OwnedFd;
+use std::path::Component;
+use std::path::Path;
+use std::path::PathBuf;
+
+#[cfg(any(target_os = "linux", target_os = "android"))]
+fn directory_access_flags() -> OFlags {
+ OFlags::PATH
+}
+
+#[cfg(target_vendor = "apple")]
+fn directory_access_flags() -> OFlags {
+ OFlags::from_bits_retain(libc::O_SEARCH as u32)
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
+fn directory_access_flags() -> OFlags {
+ OFlags::RDONLY
+}
+
+fn components(path: &Path) -> io::Result<Vec<OsString>> {
+ if !path.is_absolute() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "no-follow filesystem operations require an absolute path",
+ ));
+ }
+ path.components()
+ .filter_map(|component| match component {
+ Component::RootDir => None,
+ Component::Normal(component) => Some(Ok(component.to_os_string())),
+ Component::CurDir | Component::ParentDir | Component::Prefix(_) => {
+ Some(Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "no-follow filesystem operations require a normalized path",
+ )))
+ }
+ })
+ .collect()
+}
+
+fn root() -> io::Result<OwnedFd> {
+ open(
+ "/",
+ directory_access_flags() | OFlags::DIRECTORY | OFlags::CLOEXEC,
+ Mode::empty(),
+ )
+ .map_err(io::Error::from)
+}
+
+fn open_directory(parent: &OwnedFd, name: &OsString) -> io::Result<OwnedFd> {
+ openat(
+ parent,
+ name,
+ directory_access_flags() | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
+ Mode::empty(),
+ )
+ .map_err(io::Error::from)
+}
+
+fn parent(path: &Path) -> io::Result<(OwnedFd, OsString)> {
+ let mut components = components(path)?;
+ let leaf = components
+ .pop()
+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path must name an entry"))?;
+ let mut directory = root()?;
+ for component in components {
+ directory = open_directory(&directory, &component)?;
+ }
+ Ok((directory, leaf))
+}
+
+fn open_entry_sync(path: &Path) -> io::Result<std::fs::File> {
+ let (parent, leaf) = parent(path)?;
+ let file = openat(
+ &parent,
+ leaf,
+ OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
+ Mode::empty(),
+ )
+ .map_err(io::Error::from)?;
+ Ok(std::fs::File::from(file))
+}
+
+fn open_file_sync(path: &Path) -> io::Result<std::fs::File> {
+ let file = open_entry_sync(path)?;
+ if !file.metadata()?.is_file() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "path is not a regular file",
+ ));
+ }
+ Ok(file)
+}
+
+pub(super) async fn open_file(path: PathBuf) -> io::Result<tokio::fs::File> {
+ tokio::task::spawn_blocking(move || open_file_sync(&path).map(tokio::fs::File::from_std))
+ .await
+ .map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
+}
+
+pub(super) async fn write_file(path: PathBuf, contents: Vec<u8>) -> io::Result<()> {
+ tokio::task::spawn_blocking(move || {
+ let (parent, leaf) = parent(&path)?;
+ // Prevent FIFOs and devices from blocking during open before the
+ // descriptor can be validated as a regular file below.
+ let file = openat(
+ &parent,
+ leaf,
+ OFlags::WRONLY | OFlags::CREATE | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
+ Mode::from_raw_mode(0o666),
+ )
+ .map_err(io::Error::from)?;
+ let mut file = std::fs::File::from(file);
+ if !file.metadata()?.is_file() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "path is not a regular file",
+ ));
+ }
+ file.set_len(0)?;
+ file.write_all(&contents)
+ })
+ .await
+ .map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
+}
+
+fn metadata_sync(path: &Path) -> io::Result<FileMetadata> {
+ let components = components(path)?;
+ let metadata = if components.is_empty() {
+ fstat(root()?).map_err(io::Error::from)?
+ } else {
+ let (parent, leaf) = parent(path)?;
+ statat(&parent, leaf, AtFlags::SYMLINK_NOFOLLOW).map_err(io::Error::from)?
+ };
+ file_metadata(metadata)
+}
+
+fn file_metadata(metadata: Stat) -> io::Result<FileMetadata> {
+ let kind = metadata.st_mode & libc::S_IFMT;
+ if kind == libc::S_IFLNK {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "path contains a symbolic link",
+ ));
+ }
+ Ok(FileMetadata {
+ is_directory: kind == libc::S_IFDIR,
+ is_file: kind == libc::S_IFREG,
+ is_symlink: false,
+ size: u64::try_from(metadata.st_size).unwrap_or(0),
+ created_at_ms: created_at_ms(&metadata),
+ modified_at_ms: unix_time_ms(metadata.st_mtime, metadata.st_mtime_nsec),
+ })
+}
+
+#[cfg(target_vendor = "apple")]
+fn created_at_ms(metadata: &Stat) -> i64 {
+ unix_time_ms(metadata.st_birthtime, metadata.st_birthtime_nsec)
+}
+
+#[cfg(not(target_vendor = "apple"))]
+fn created_at_ms(_metadata: &Stat) -> i64 {
+ 0
+}
+
+fn unix_time_ms(seconds: i64, nanoseconds: impl TryInto<i64>) -> i64 {
+ let nanoseconds = nanoseconds.try_into().unwrap_or_default();
+ seconds
+ .saturating_mul(1_000)
+ .saturating_add(nanoseconds / 1_000_000)
+}
+
+pub(super) async fn metadata(path: PathBuf) -> io::Result<FileMetadata> {
+ tokio::task::spawn_blocking(move || metadata_sync(&path))
+ .await
+ .map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
+}
+
+pub(super) async fn create_directory(path: PathBuf, recursive: bool) -> io::Result<()> {
+ tokio::task::spawn_blocking(move || {
+ let components = components(&path)?;
+ if components.is_empty() && !recursive {
+ return Err(io::Error::new(
+ io::ErrorKind::AlreadyExists,
+ "directory already exists",
+ ));
+ }
+ let mut directory = root()?;
+ for (index, component) in components.iter().enumerate() {
+ let is_leaf = index + 1 == components.len();
+ if !recursive && is_leaf {
+ mkdirat(&directory, component, Mode::from_raw_mode(0o777))
+ .map_err(io::Error::from)?;
+ return Ok(());
+ }
+ match open_directory(&directory, component) {
+ Ok(next) => directory = next,
+ Err(error) if recursive && error.kind() == io::ErrorKind::NotFound => {
+ match mkdirat(&directory, component, Mode::from_raw_mode(0o777)) {
+ Ok(()) | Err(rustix::io::Errno::EXIST) => {}
+ Err(error) => return Err(io::Error::from(error)),
+ }
+ directory = open_directory(&directory, component)?;
+ }
+ Err(error) => return Err(error),
+ }
+ }
+ Ok(())
+ })
+ .await
+ .map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
+}
+
+pub(super) async fn remove(path: PathBuf, recursive: bool, force: bool) -> io::Result<()> {
+ tokio::task::spawn_blocking(move || {
+ if recursive {
+ return Err(io::Error::new(
+ io::ErrorKind::Unsupported,
+ "recursive no-follow removal is unsupported",
+ ));
+ }
+ let (parent, leaf) = match parent(&path) {
+ Ok(value) => value,
+ Err(error) if force && error.kind() == io::ErrorKind::NotFound => return Ok(()),
+ Err(error) => return Err(error),
+ };
+ let metadata = match statat(&parent, &leaf, AtFlags::SYMLINK_NOFOLLOW) {
+ Ok(metadata) => metadata,
+ Err(error) if force && error == rustix::io::Errno::NOENT => return Ok(()),
+ Err(error) => return Err(io::Error::from(error)),
+ };
+ let kind = metadata.st_mode & libc::S_IFMT;
+ if kind == libc::S_IFLNK {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "path contains a symbolic link",
+ ));
+ }
+ let flags = if kind == libc::S_IFDIR {
+ AtFlags::REMOVEDIR
+ } else {
+ AtFlags::empty()
+ };
+ unlinkat(&parent, leaf, flags).map_err(io::Error::from)
+ })
+ .await
+ .map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
+}
diff --git a/codex-rs/exec-server/src/no_follow/windows.rs b/codex-rs/exec-server/src/no_follow/windows.rs
new file mode 100644
index 0000000000..c6ab7677e5
--- /dev/null
+++ b/codex-rs/exec-server/src/no_follow/windows.rs
@@ -0,0 +1,320 @@
+use crate::regular_file;
+use std::ffi::OsStr;
+use std::ffi::c_void;
+use std::io;
+use std::io::Write;
+use std::mem::size_of;
+use std::os::windows::ffi::OsStrExt;
+use std::os::windows::io::FromRawHandle;
+use std::os::windows::io::OwnedHandle;
+use std::os::windows::io::RawHandle;
+use std::path::Component;
+use std::path::Path;
+use std::path::PathBuf;
+use std::path::Prefix;
+use std::ptr;
+use windows_sys::Win32::Foundation::HANDLE;
+use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
+use windows_sys::Win32::Foundation::NTSTATUS;
+use windows_sys::Win32::Foundation::RtlNtStatusToDosError;
+use windows_sys::Win32::Foundation::UNICODE_STRING;
+use windows_sys::Win32::Security::SECURITY_QUALITY_OF_SERVICE;
+use windows_sys::Win32::Security::SecurityIdentification;
+use windows_sys::Win32::Storage::FileSystem::DELETE;
+use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL;
+use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
+use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
+use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE;
+use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
+use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
+use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_DATA;
+use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
+use windows_sys::Win32::System::IO::IO_STATUS_BLOCK_0;
+use windows_sys::Win32::System::Kernel::OBJ_CASE_INSENSITIVE;
+use windows_sys::Win32::System::Kernel::OBJ_DONT_REPARSE;
+
+const FILE_DIRECTORY_FILE: u32 = 0x0000_0001;
+const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x0000_0020;
+const FILE_NON_DIRECTORY_FILE: u32 = 0x0000_0040;
+const FILE_DELETE_ON_CLOSE: u32 = 0x0000_1000;
+const FILE_OPEN: u32 = 1;
+const FILE_CREATE: u32 = 2;
+const FILE_OPEN_IF: u32 = 3;
+const SYNCHRONIZE_ACCESS: u32 = 0x0010_0000;
+const STATUS_REPARSE_POINT_ENCOUNTERED: NTSTATUS = 0xC000_050B_u32 as i32;
+const SECURITY_STATIC_TRACKING: u8 = 0;
+const BOOLEAN_TRUE: u8 = 1;
+
+#[repr(C)]
+struct ObjectAttributes {
+ length: u32,
+ root_directory: HANDLE,
+ object_name: *const UNICODE_STRING,
+ attributes: u32,
+ security_descriptor: *const c_void,
+ security_quality_of_service: *const c_void,
+}
+
+#[link(name = "ntdll")]
+unsafe extern "system" {
+ fn NtCreateFile(
+ file_handle: *mut HANDLE,
+ desired_access: u32,
+ object_attributes: *const ObjectAttributes,
+ io_status_block: *mut IO_STATUS_BLOCK,
+ allocation_size: *const i64,
+ file_attributes: u32,
+ share_access: u32,
+ create_disposition: u32,
+ create_options: u32,
+ ea_buffer: *const c_void,
+ ea_length: u32,
+ ) -> NTSTATUS;
+}
+
+fn nt_path(path: &Path) -> io::Result<Vec<u16>> {
+ if !path.is_absolute() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "no-follow filesystem operations require an absolute path",
+ ));
+ }
+
+ let (prefix, source_offset) = match path.components().next() {
+ Some(Component::Prefix(prefix)) => match prefix.kind() {
+ Prefix::Disk(_) => ("\\??\\", 0),
+ Prefix::VerbatimDisk(_) => ("\\??\\", 4),
+ Prefix::UNC(_, _) => ("\\??\\UNC\\", 2),
+ Prefix::VerbatimUNC(_, _) => ("\\??\\UNC\\", 8),
+ _ => {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "no-follow filesystem operations require a local disk or UNC path",
+ ));
+ }
+ },
+ _ => {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "no-follow filesystem operations require an absolute Windows path",
+ ));
+ }
+ };
+
+ let mut result: Vec<u16> = OsStr::new(prefix).encode_wide().collect();
+ result.extend(
+ path.as_os_str()
+ .encode_wide()
+ .skip(source_offset)
+ .map(|unit| {
+ if unit == b'/' as u16 {
+ b'\\' as u16
+ } else {
+ unit
+ }
+ }),
+ );
+ result.push(0);
+ Ok(result)
+}
+
+fn open_handle(
+ path: &Path,
+ desired_access: u32,
+ create_disposition: u32,
+ create_options: u32,
+) -> io::Result<OwnedHandle> {
+ let mut path = nt_path(path)?;
+ let name_length = u16::try_from((path.len() - 1) * size_of::<u16>())
+ .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "filesystem path is too long"))?;
+ let maximum_length = u16::try_from(path.len() * size_of::<u16>())
+ .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "filesystem path is too long"))?;
+ let object_name = UNICODE_STRING {
+ Length: name_length,
+ MaximumLength: maximum_length,
+ Buffer: path.as_mut_ptr(),
+ };
+ let security_quality_of_service = SECURITY_QUALITY_OF_SERVICE {
+ Length: size_of::<SECURITY_QUALITY_OF_SERVICE>() as u32,
+ ImpersonationLevel: SecurityIdentification,
+ ContextTrackingMode: SECURITY_STATIC_TRACKING,
+ EffectiveOnly: BOOLEAN_TRUE,
+ };
+ let object_attributes = ObjectAttributes {
+ length: size_of::<ObjectAttributes>() as u32,
+ root_directory: 0,
+ object_name: &object_name,
+ attributes: OBJ_CASE_INSENSITIVE as u32 | OBJ_DONT_REPARSE as u32,
+ security_descriptor: ptr::null(),
+ security_quality_of_service: (&raw const security_quality_of_service).cast(),
+ };
+ let mut io_status_block = IO_STATUS_BLOCK {
+ Anonymous: IO_STATUS_BLOCK_0 { Status: 0 },
+ Information: 0,
+ };
+ let mut handle = 0;
+ let status = unsafe {
+ NtCreateFile(
+ &mut handle,
+ desired_access | SYNCHRONIZE_ACCESS,
+ &object_attributes,
+ &mut io_status_block,
+ ptr::null(),
+ FILE_ATTRIBUTE_NORMAL,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ create_disposition,
+ create_options | FILE_SYNCHRONOUS_IO_NONALERT,
+ ptr::null(),
+ /*ea_length*/ 0,
+ )
+ };
+ if status < 0 {
+ if status == STATUS_REPARSE_POINT_ENCOUNTERED {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "path contains a reparse point",
+ ));
+ }
+ let code = unsafe { RtlNtStatusToDosError(status) };
+ return Err(io::Error::from_raw_os_error(code as i32));
+ }
+ if handle == 0 || handle == INVALID_HANDLE_VALUE {
+ return Err(io::Error::other(
+ "NtCreateFile returned an invalid filesystem handle",
+ ));
+ }
+
+ Ok(unsafe { OwnedHandle::from_raw_handle(handle as RawHandle) })
+}
+
+fn open_entry(path: &Path) -> io::Result<std::fs::File> {
+ let handle = open_handle(
+ path,
+ FILE_READ_ATTRIBUTES,
+ FILE_OPEN,
+ /*create_options*/ 0,
+ )?;
+ Ok(std::fs::File::from(handle))
+}
+
+fn open_file_sync(path: &Path) -> io::Result<std::fs::File> {
+ let handle = open_handle(path, FILE_GENERIC_READ, FILE_OPEN, FILE_NON_DIRECTORY_FILE)?;
+ let file = std::fs::File::from(handle);
+ validate_regular_file(&file, path)?;
+ Ok(file)
+}
+
+fn validate_regular_file(file: &std::fs::File, path: &Path) -> io::Result<()> {
+ if !regular_file::is_disk_file(file) || !file.metadata()?.is_file() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ format!("path `{}` is not a file", path.display()),
+ ));
+ }
+ Ok(())
+}
+
+pub(super) async fn open_file(path: PathBuf) -> io::Result<tokio::fs::File> {
+ tokio::task::spawn_blocking(move || open_file_sync(&path).map(tokio::fs::File::from_std))
+ .await
+ .map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
+}
+
+pub(super) async fn write_file(path: PathBuf, contents: Vec<u8>) -> io::Result<()> {
+ tokio::task::spawn_blocking(move || {
+ let handle = open_handle(
+ &path,
+ FILE_READ_ATTRIBUTES | FILE_WRITE_DATA,
+ FILE_OPEN_IF,
+ FILE_NON_DIRECTORY_FILE,
+ )?;
+ let mut file = std::fs::File::from(handle);
+ validate_regular_file(&file, &path)?;
+ file.set_len(0)?;
+ file.write_all(&contents)
+ })
+ .await
+ .map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
+}
+
+pub(super) async fn metadata(path: PathBuf) -> io::Result<std::fs::Metadata> {
+ tokio::task::spawn_blocking(move || open_entry(&path)?.metadata())
+ .await
+ .map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
+}
+
+fn create_directory_sync(path: &Path, recursive: bool) -> io::Result<()> {
+ if !recursive {
+ open_handle(path, FILE_READ_ATTRIBUTES, FILE_CREATE, FILE_DIRECTORY_FILE)?;
+ return Ok(());
+ }
+
+ let mut current = PathBuf::new();
+ for component in path.components() {
+ current.push(component.as_os_str());
+ if matches!(component, Component::Normal(_)) {
+ open_or_create_directory(&current)?;
+ }
+ }
+ Ok(())
+}
+
+fn open_or_create_directory(path: &Path) -> io::Result<()> {
+ match open_handle(path, FILE_READ_ATTRIBUTES, FILE_OPEN, FILE_DIRECTORY_FILE) {
+ Ok(_) => Ok(()),
+ Err(error) if error.kind() == io::ErrorKind::NotFound => {
+ match open_handle(path, FILE_READ_ATTRIBUTES, FILE_CREATE, FILE_DIRECTORY_FILE) {
+ Ok(_) => Ok(()),
+ Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
+ open_handle(path, FILE_READ_ATTRIBUTES, FILE_OPEN, FILE_DIRECTORY_FILE)?;
+ Ok(())
+ }
+ Err(error) => Err(error),
+ }
+ }
+ Err(error) => Err(error),
+ }
+}
+
+pub(super) async fn create_directory(path: PathBuf, recursive: bool) -> io::Result<()> {
+ tokio::task::spawn_blocking(move || create_directory_sync(&path, recursive))
+ .await
+ .map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
+}
+
+fn remove_sync(path: &Path, recursive: bool, force: bool) -> io::Result<()> {
+ if recursive {
+ return Err(io::Error::new(
+ io::ErrorKind::Unsupported,
+ "recursive no-follow removal is unsupported",
+ ));
+ }
+
+ let metadata = match open_entry(path).and_then(|file| file.metadata()) {
+ Ok(metadata) => metadata,
+ Err(error) if force && error.kind() == io::ErrorKind::NotFound => return Ok(()),
+ Err(error) => return Err(error),
+ };
+ let create_options = if metadata.is_dir() {
+ FILE_DIRECTORY_FILE
+ } else {
+ FILE_NON_DIRECTORY_FILE
+ };
+ open_handle(
+ path,
+ DELETE,
+ FILE_OPEN,
+ create_options | FILE_DELETE_ON_CLOSE,
+ )?;
+ Ok(())
+}
+
+pub(super) async fn remove(path: PathBuf, recursive: bool, force: bool) -> io::Result<()> {
+ tokio::task::spawn_blocking(move || remove_sync(&path, recursive, force))
+ .await
+ .map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
+}
+
+#[cfg(test)]
+#[path = "windows_tests.rs"]
+mod tests;
diff --git a/codex-rs/exec-server/src/no_follow/windows_tests.rs b/codex-rs/exec-server/src/no_follow/windows_tests.rs
new file mode 100644
index 0000000000..d9e3b0bbeb
--- /dev/null
+++ b/codex-rs/exec-server/src/no_follow/windows_tests.rs
@@ -0,0 +1,43 @@
+use super::*;
+use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE;
+use windows_sys::Win32::Storage::FileSystem::PIPE_ACCESS_DUPLEX;
+use windows_sys::Win32::System::Pipes::CreateNamedPipeW;
+use windows_sys::Win32::System::Pipes::PIPE_READMODE_BYTE;
+use windows_sys::Win32::System::Pipes::PIPE_TYPE_BYTE;
+use windows_sys::Win32::System::Pipes::PIPE_WAIT;
+
+#[test]
+fn native_open_rejects_named_pipes_before_connecting() {
+ let pipe_name = format!("codex-no-follow-{}", uuid::Uuid::new_v4());
+ let server_path = PathBuf::from(format!(r"\\.\pipe\{pipe_name}"));
+ let client_path = PathBuf::from(format!(r"\\localhost\pipe\{pipe_name}"));
+ let wide_path = server_path
+ .as_os_str()
+ .encode_wide()
+ .chain(std::iter::once(0))
+ .collect::<Vec<_>>();
+ let pipe = unsafe {
+ CreateNamedPipeW(
+ wide_path.as_ptr(),
+ PIPE_ACCESS_DUPLEX,
+ PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
+ /*nmaxinstances*/ 1,
+ /*noutbuffersize*/ 1,
+ /*ninbuffersize*/ 1,
+ /*ndefaulttimeout*/ 1_000,
+ ptr::null(),
+ )
+ };
+ assert_ne!(pipe, INVALID_HANDLE_VALUE);
+ let _pipe = unsafe { OwnedHandle::from_raw_handle(pipe as RawHandle) };
+
+ let error = open_handle(
+ &client_path,
+ FILE_GENERIC_READ | FILE_GENERIC_WRITE,
+ FILE_OPEN,
+ FILE_NON_DIRECTORY_FILE,
+ )
+ .expect_err("strict native open should reject named pipes");
+ assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
+ assert_eq!(error.to_string(), "path contains a reparse point");
+}
diff --git a/codex-rs/exec-server/src/regular_file.rs b/codex-rs/exec-server/src/regular_file.rs
index fb74501709..4182046a62 100644
--- a/codex-rs/exec-server/src/regular_file.rs
+++ b/codex-rs/exec-server/src/regular_file.rs
@@ -63,8 +63,7 @@ fn configure_open(options: &mut tokio::fs::OpenOptions) {
fn configure_open(_options: &mut tokio::fs::OpenOptions) {}
#[cfg(windows)]
-fn is_disk_file(file: &tokio::fs::File) -> bool {
- use std::os::windows::io::AsRawHandle;
+pub(crate) fn is_disk_file(file: &impl std::os::windows::io::AsRawHandle) -> bool {
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Storage::FileSystem::FILE_TYPE_DISK;
use windows_sys::Win32::Storage::FileSystem::GetFileType;
diff --git a/codex-rs/exec-server/src/remote_file_system.rs b/codex-rs/exec-server/src/remote_file_system.rs
index 40bf0d1b89..7d624cefda 100644
--- a/codex-rs/exec-server/src/remote_file_system.rs
+++ b/codex-rs/exec-server/src/remote_file_system.rs
@@ -18,10 +18,13 @@ use crate::FileMetadata;
use crate::FileSystemReadStream;
use crate::FileSystemResult;
use crate::FileSystemSandboxContext;
+use crate::GetMetadataOptions;
use crate::ReadDirectoryEntry;
+use crate::ReadFileOptions;
use crate::RemoveOptions;
use crate::WalkOptions;
use crate::WalkOutcome;
+use crate::WriteFileOptions;
use crate::client::LazyRemoteExecServerClient;
use crate::protocol::FsCanonicalizeParams;
use crate::protocol::FsCopyParams;
@@ -76,6 +79,7 @@ impl RemoteFileSystem {
async fn read_file(
&self,
path: &PathUri,
+ options: ReadFileOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>> {
trace!("remote fs read_file");
@@ -83,6 +87,7 @@ impl RemoteFileSystem {
let response = client
.fs_read_file(FsReadFileParams {
path: path.clone(),
+ follow_symlinks: (!options.follow_symlinks).then_some(false),
sandbox: remote_sandbox_context(sandbox),
})
.await
@@ -109,6 +114,7 @@ impl RemoteFileSystem {
&self,
path: &PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<()> {
trace!("remote fs write_file");
@@ -117,6 +123,7 @@ impl RemoteFileSystem {
.fs_write_file(FsWriteFileParams {
path: path.clone(),
data_base64: STANDARD.encode(contents),
+ follow_symlinks: (!options.follow_symlinks).then_some(false),
sandbox: remote_sandbox_context(sandbox),
})
.await;
@@ -137,6 +144,7 @@ impl RemoteFileSystem {
.fs_create_directory(FsCreateDirectoryParams {
path: path.clone(),
recursive: Some(options.recursive),
+ follow_symlinks: (!options.follow_symlinks).then_some(false),
sandbox: remote_sandbox_context(sandbox),
private: None,
})
@@ -150,10 +158,11 @@ impl RemoteFileSystem {
async fn get_metadata(
&self,
path: &PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
- if sandbox.is_some() {
- return self.get_metadata_uncached(path, sandbox).await;
+ if sandbox.is_some() || !options.follow_symlinks {
+ return self.get_metadata_uncached(path, options, sandbox).await;
}
let request = {
@@ -163,7 +172,7 @@ impl RemoteFileSystem {
};
let result = match request
.get_or_init(|| async {
- self.get_metadata_uncached(path, /*sandbox*/ None)
+ self.get_metadata_uncached(path, options, /*sandbox*/ None)
.await
.map_err(Arc::new)
})
@@ -188,6 +197,7 @@ impl RemoteFileSystem {
async fn get_metadata_uncached(
&self,
path: &PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
trace!("remote fs get_metadata");
@@ -195,6 +205,7 @@ impl RemoteFileSystem {
let response = client
.fs_get_metadata(FsGetMetadataParams {
path: path.clone(),
+ follow_symlinks: (!options.follow_symlinks).then_some(false),
sandbox: remote_sandbox_context(sandbox),
})
.await
@@ -278,6 +289,7 @@ impl RemoteFileSystem {
path: path.clone(),
recursive: Some(options.recursive),
force: Some(options.force),
+ follow_symlinks: (!options.follow_symlinks).then_some(false),
sandbox: remote_sandbox_context(sandbox),
})
.await;
@@ -321,9 +333,10 @@ impl ExecutorFileSystem for RemoteFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ options: ReadFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
- Box::pin(RemoteFileSystem::read_file(self, path, sandbox))
+ Box::pin(RemoteFileSystem::read_file(self, path, options, sandbox))
}
fn read_file_stream<'a>(
@@ -338,9 +351,12 @@ impl ExecutorFileSystem for RemoteFileSystem {
&'a self,
path: &'a PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
- Box::pin(RemoteFileSystem::write_file(self, path, contents, sandbox))
+ Box::pin(RemoteFileSystem::write_file(
+ self, path, contents, options, sandbox,
+ ))
}
fn create_directory<'a>(
@@ -357,9 +373,10 @@ impl ExecutorFileSystem for RemoteFileSystem {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
- Box::pin(RemoteFileSystem::get_metadata(self, path, sandbox))
+ Box::pin(RemoteFileSystem::get_metadata(self, path, options, sandbox))
}
fn read_directory<'a>(
diff --git a/codex-rs/exec-server/src/remote_file_system_path_uri_tests.rs b/codex-rs/exec-server/src/remote_file_system_path_uri_tests.rs
index cd0f5c1a2f..adba21c78c 100644
--- a/codex-rs/exec-server/src/remote_file_system_path_uri_tests.rs
+++ b/codex-rs/exec-server/src/remote_file_system_path_uri_tests.rs
@@ -74,7 +74,7 @@ async fn remote_file_system_sends_path_and_sandbox_cwd_uris_without_native_conve
for path in &paths {
assert_eq!(
file_system
- .read_file(path, Some(&sandbox))
+ .read_file(path, Default::default(), Some(&sandbox))
.await
.expect("remote read should succeed"),
Vec::<u8>::new()
@@ -85,6 +85,7 @@ async fn remote_file_system_sends_path_and_sandbox_cwd_uris_without_native_conve
.into_iter()
.map(|path| FsReadFileParams {
path,
+ follow_symlinks: None,
sandbox: Some(sandbox.clone()),
})
.collect::<Vec<_>>();
@@ -114,8 +115,8 @@ async fn concurrent_remote_metadata_requests_share_only_in_flight_results() {
let path = PathUri::parse("file:///workspace/project/AGENTS.md").expect("valid path URI");
let (first, second) = tokio::join!(
- file_system.get_metadata(&path, /*sandbox*/ None),
- file_system.get_metadata(&path, /*sandbox*/ None),
+ file_system.get_metadata(&path, Default::default(), /*sandbox*/ None),
+ file_system.get_metadata(&path, Default::default(), /*sandbox*/ None),
);
let expected = FileMetadata {
is_directory: false,
@@ -133,14 +134,18 @@ async fn concurrent_remote_metadata_requests_share_only_in_flight_results() {
let initializing_path = path.clone();
let initializer = tokio::spawn(async move {
initializing_file_system
- .get_metadata(&initializing_path, /*sandbox*/ None)
+ .get_metadata(
+ &initializing_path,
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await
});
abandoned_request_rx
.await
.expect("server should receive the abandoned metadata request");
- let follower = file_system.get_metadata(&path, /*sandbox*/ None);
+ let follower = file_system.get_metadata(&path, Default::default(), /*sandbox*/ None);
tokio::pin!(follower);
assert!(futures::poll!(follower.as_mut()).is_pending());
assert_eq!(
@@ -175,6 +180,7 @@ async fn concurrent_remote_metadata_requests_share_only_in_flight_results() {
vec![
FsGetMetadataParams {
path: path.clone(),
+ follow_symlinks: None,
sandbox: None,
};
3
@@ -204,8 +210,8 @@ async fn concurrent_remote_metadata_errors_are_shared_but_retried() {
let path = PathUri::parse("file:///workspace/project/AGENTS.md").expect("valid path URI");
let (first, second) = tokio::join!(
- file_system.get_metadata(&path, /*sandbox*/ None),
- file_system.get_metadata(&path, /*sandbox*/ None),
+ file_system.get_metadata(&path, Default::default(), /*sandbox*/ None),
+ file_system.get_metadata(&path, Default::default(), /*sandbox*/ None),
);
assert_eq!(
first.expect_err("first metadata error").kind(),
@@ -217,7 +223,7 @@ async fn concurrent_remote_metadata_errors_are_shared_but_retried() {
);
assert_eq!(
file_system
- .get_metadata(&path, /*sandbox*/ None)
+ .get_metadata(&path, Default::default(), /*sandbox*/ None)
.await
.expect("failed metadata request should be retried")
.size,
@@ -228,10 +234,12 @@ async fn concurrent_remote_metadata_errors_are_shared_but_retried() {
vec![
FsGetMetadataParams {
path: path.clone(),
+ follow_symlinks: None,
sandbox: None,
},
FsGetMetadataParams {
path,
+ follow_symlinks: None,
sandbox: None,
},
]
@@ -279,21 +287,30 @@ async fn remote_metadata_starts_fresh_after_intervening_filesystem_mutation() {
.await
.expect("remote filesystem client should connect");
- let stale_request = file_system.get_metadata(&path, /*sandbox*/ None);
+ let stale_request =
+ file_system.get_metadata(&path, Default::default(), /*sandbox*/ None);
tokio::pin!(stale_request);
assert!(futures::poll!(stale_request.as_mut()).is_pending());
let result = match mutation {
MetadataMutation::Write => {
file_system
- .write_file(&path, b"updated".to_vec(), /*sandbox*/ None)
+ .write_file(
+ &path,
+ b"updated".to_vec(),
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await
}
MetadataMutation::CreateDirectory => {
file_system
.create_directory(
&path,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await
@@ -305,6 +322,7 @@ async fn remote_metadata_starts_fresh_after_intervening_filesystem_mutation() {
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -333,7 +351,7 @@ async fn remote_metadata_starts_fresh_after_intervening_filesystem_mutation() {
}
let (refreshed, stale) = tokio::join!(
- file_system.get_metadata(&path, /*sandbox*/ None),
+ file_system.get_metadata(&path, Default::default(), /*sandbox*/ None),
stale_request.as_mut(),
);
assert_eq!(stale.expect("original metadata request").size, 42);
@@ -343,6 +361,7 @@ async fn remote_metadata_starts_fresh_after_intervening_filesystem_mutation() {
vec![
FsGetMetadataParams {
path: path.clone(),
+ follow_symlinks: None,
sandbox: None,
};
2
@@ -386,15 +405,15 @@ async fn remote_metadata_requests_do_not_cross_path_or_sandbox_boundaries() {
);
let (first, second) = tokio::join!(
- file_system.get_metadata(&first_path, /*sandbox*/ None),
- file_system.get_metadata(&second_path, /*sandbox*/ None),
+ file_system.get_metadata(&first_path, Default::default(), /*sandbox*/ None),
+ file_system.get_metadata(&second_path, Default::default(), /*sandbox*/ None),
);
first.expect("metadata for first path");
second.expect("metadata for second path");
let (first, second) = tokio::join!(
- file_system.get_metadata(&first_path, Some(&sandbox)),
- file_system.get_metadata(&first_path, Some(&sandbox)),
+ file_system.get_metadata(&first_path, Default::default(), Some(&sandbox)),
+ file_system.get_metadata(&first_path, Default::default(), Some(&sandbox)),
);
first.expect("first sandboxed metadata request");
second.expect("second sandboxed metadata request");
diff --git a/codex-rs/exec-server/src/sandboxed_file_open.rs b/codex-rs/exec-server/src/sandboxed_file_open.rs
index 9799c27106..93c78706a4 100644
--- a/codex-rs/exec-server/src/sandboxed_file_open.rs
+++ b/codex-rs/exec-server/src/sandboxed_file_open.rs
@@ -20,6 +20,7 @@ pub(crate) async fn open(
) -> Result<tokio::fs::File, JSONRPCErrorError> {
let request = serde_json::to_vec(&FsHelperRequest::Open(FsReadFileParams {
path,
+ follow_symlinks: None,
sandbox: None,
}))
.map_err(|error| internal_error(format!("invalid fs sandbox helper request: {error}")))?;
diff --git a/codex-rs/exec-server/src/sandboxed_file_system.rs b/codex-rs/exec-server/src/sandboxed_file_system.rs
index c22e0167de..ce70fe9a75 100644
--- a/codex-rs/exec-server/src/sandboxed_file_system.rs
+++ b/codex-rs/exec-server/src/sandboxed_file_system.rs
@@ -15,10 +15,13 @@ use crate::FileMetadata;
use crate::FileSystemReadStream;
use crate::FileSystemResult;
use crate::FileSystemSandboxContext;
+use crate::GetMetadataOptions;
use crate::ReadDirectoryEntry;
+use crate::ReadFileOptions;
use crate::RemoveOptions;
use crate::WalkOptions;
use crate::WalkOutcome;
+use crate::WriteFileOptions;
use crate::fs_helper::FsHelperPayload;
use crate::fs_helper::FsHelperRequest;
use crate::fs_sandbox::FileSystemSandboxRunner;
@@ -97,6 +100,7 @@ impl SandboxedFileSystem {
async fn read_file(
&self,
path: &PathUri,
+ options: ReadFileOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>> {
let sandbox = require_platform_sandbox(sandbox)?;
@@ -106,6 +110,7 @@ impl SandboxedFileSystem {
sandbox,
FsHelperRequest::ReadFile(FsReadFileParams {
path: path.clone(),
+ follow_symlinks: (!options.follow_symlinks).then_some(false),
sandbox: None,
}),
)
@@ -124,6 +129,7 @@ impl SandboxedFileSystem {
&self,
path: &PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<()> {
let sandbox = require_platform_sandbox(sandbox)?;
@@ -133,6 +139,7 @@ impl SandboxedFileSystem {
FsHelperRequest::WriteFile(FsWriteFileParams {
path: path.clone(),
data_base64: STANDARD.encode(contents),
+ follow_symlinks: (!options.follow_symlinks).then_some(false),
sandbox: None,
}),
)
@@ -155,6 +162,7 @@ impl SandboxedFileSystem {
FsHelperRequest::CreateDirectory(FsCreateDirectoryParams {
path: path.clone(),
recursive: Some(options.recursive),
+ follow_symlinks: (!options.follow_symlinks).then_some(false),
sandbox: None,
private: None,
}),
@@ -168,6 +176,7 @@ impl SandboxedFileSystem {
async fn get_metadata(
&self,
path: &PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<FileMetadata> {
let sandbox = require_platform_sandbox(sandbox)?;
@@ -177,6 +186,7 @@ impl SandboxedFileSystem {
sandbox,
FsHelperRequest::GetMetadata(FsGetMetadataParams {
path: path.clone(),
+ follow_symlinks: (!options.follow_symlinks).then_some(false),
sandbox: None,
}),
)
@@ -259,6 +269,7 @@ impl SandboxedFileSystem {
path: path.clone(),
recursive: Some(remove_options.recursive),
force: Some(remove_options.force),
+ follow_symlinks: (!remove_options.follow_symlinks).then_some(false),
sandbox: None,
}),
)
@@ -306,9 +317,10 @@ impl ExecutorFileSystem for SandboxedFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ options: ReadFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
- Box::pin(SandboxedFileSystem::read_file(self, path, sandbox))
+ Box::pin(SandboxedFileSystem::read_file(self, path, options, sandbox))
}
fn read_file_stream<'a>(
@@ -329,10 +341,11 @@ impl ExecutorFileSystem for SandboxedFileSystem {
&'a self,
path: &'a PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
Box::pin(SandboxedFileSystem::write_file(
- self, path, contents, sandbox,
+ self, path, contents, options, sandbox,
))
}
@@ -350,9 +363,12 @@ impl ExecutorFileSystem for SandboxedFileSystem {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
- Box::pin(SandboxedFileSystem::get_metadata(self, path, sandbox))
+ Box::pin(SandboxedFileSystem::get_metadata(
+ self, path, options, sandbox,
+ ))
}
fn read_directory<'a>(
diff --git a/codex-rs/exec-server/src/sandboxed_file_system_path_uri_tests.rs b/codex-rs/exec-server/src/sandboxed_file_system_path_uri_tests.rs
index eb1a0d5dc4..031d89080f 100644
--- a/codex-rs/exec-server/src/sandboxed_file_system_path_uri_tests.rs
+++ b/codex-rs/exec-server/src/sandboxed_file_system_path_uri_tests.rs
@@ -23,7 +23,7 @@ async fn sandboxed_file_system_rejects_non_native_uri_as_invalid_input() {
);
let error = file_system
- .read_file(&non_native_uri(), Some(&sandbox))
+ .read_file(&non_native_uri(), Default::default(), Some(&sandbox))
.await
.expect_err("non-native URI should be rejected");
diff --git a/codex-rs/exec-server/src/server/file_system_handler.rs b/codex-rs/exec-server/src/server/file_system_handler.rs
index 23151c2e5f..e781558f94 100644
--- a/codex-rs/exec-server/src/server/file_system_handler.rs
+++ b/codex-rs/exec-server/src/server/file_system_handler.rs
@@ -10,7 +10,10 @@ use crate::CopyOptions;
use crate::CreateDirectoryOptions;
use crate::ExecServerRuntimePaths;
use crate::ExecutorFileSystem;
+use crate::GetMetadataOptions;
+use crate::ReadFileOptions;
use crate::RemoveOptions;
+use crate::WriteFileOptions;
use crate::file_read::FileReadHandleManager;
use crate::local_file_system::LocalFileSystem;
use crate::protocol::FS_READ_DIRECTORY_METHOD;
@@ -125,7 +128,13 @@ impl FileSystemHandler {
) -> Result<FsReadFileResponse, JSONRPCErrorError> {
let bytes = self
.file_system
- .read_file(&params.path, params.sandbox.as_ref())
+ .read_file(
+ &params.path,
+ ReadFileOptions {
+ follow_symlinks: params.follow_symlinks.unwrap_or(true),
+ },
+ params.sandbox.as_ref(),
+ )
.await
.map_err(map_fs_error)?;
Ok(FsReadFileResponse {
@@ -143,7 +152,14 @@ impl FileSystemHandler {
))
})?;
self.file_system
- .write_file(&params.path, bytes, params.sandbox.as_ref())
+ .write_file(
+ &params.path,
+ bytes,
+ WriteFileOptions {
+ follow_symlinks: params.follow_symlinks.unwrap_or(true),
+ },
+ params.sandbox.as_ref(),
+ )
.await
.map_err(map_fs_error)?;
Ok(FsWriteFileResponse {})
@@ -154,6 +170,11 @@ impl FileSystemHandler {
params: FsCreateDirectoryParams,
) -> Result<FsCreateDirectoryResponse, JSONRPCErrorError> {
if params.private.unwrap_or(false) {
+ if params.follow_symlinks == Some(false) {
+ return Err(invalid_request(
+ "private directories do not support followSymlinks=false".to_string(),
+ ));
+ }
if params.recursive.unwrap_or(false) || params.sandbox.is_some() {
return Err(invalid_request(
"private directories must be non-recursive and unsandboxed".to_string(),
@@ -178,7 +199,10 @@ impl FileSystemHandler {
self.file_system
.create_directory(
&params.path,
- CreateDirectoryOptions { recursive },
+ CreateDirectoryOptions {
+ recursive,
+ follow_symlinks: params.follow_symlinks.unwrap_or(true),
+ },
params.sandbox.as_ref(),
)
.await
@@ -192,7 +216,13 @@ impl FileSystemHandler {
) -> Result<FsGetMetadataResponse, JSONRPCErrorError> {
let metadata = self
.file_system
- .get_metadata(&params.path, params.sandbox.as_ref())
+ .get_metadata(
+ &params.path,
+ GetMetadataOptions {
+ follow_symlinks: params.follow_symlinks.unwrap_or(true),
+ },
+ params.sandbox.as_ref(),
+ )
.await
.map_err(map_fs_error)?;
Ok(FsGetMetadataResponse {
@@ -262,7 +292,11 @@ impl FileSystemHandler {
self.file_system
.remove(
&params.path,
- RemoveOptions { recursive, force },
+ RemoveOptions {
+ recursive,
+ force,
+ follow_symlinks: params.follow_symlinks.unwrap_or(true),
+ },
params.sandbox.as_ref(),
)
.await
@@ -337,6 +371,7 @@ mod tests {
handler
.create_directory(FsCreateDirectoryParams {
path: PathUri::from_host_native_path(&directory).expect("directory URI"),
+ follow_symlinks: None,
recursive: Some(false),
sandbox: None,
private: Some(true),
@@ -354,6 +389,37 @@ mod tests {
);
}
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn private_directories_reject_no_follow_before_resolving_the_path() {
+ let temp_dir = tempfile::tempdir().expect("tempdir");
+ let runtime_paths = ExecServerRuntimePaths::new(
+ std::env::current_exe().expect("current exe"),
+ /*codex_linux_sandbox_exe*/ None,
+ )
+ .expect("runtime paths");
+ let handler = FileSystemHandler::new(runtime_paths);
+ let target = temp_dir.path().join("target");
+ std::fs::create_dir(&target).expect("create target");
+ let alias = temp_dir.path().join("alias");
+ std::os::unix::fs::symlink(&target, &alias).expect("create alias");
+ let directory = alias.join("private-metrics");
+
+ let error = handler
+ .create_directory(FsCreateDirectoryParams {
+ path: PathUri::from_host_native_path(&directory).expect("directory URI"),
+ follow_symlinks: Some(false),
+ recursive: Some(false),
+ sandbox: None,
+ private: Some(true),
+ })
+ .await
+ .expect_err("strict private directory request must fail closed");
+
+ assert!(error.message.contains("followSymlinks=false"));
+ assert!(!target.join("private-metrics").exists());
+ }
+
#[cfg(windows)]
#[tokio::test]
async fn private_directories_are_rejected_when_owner_only_permissions_are_unsupported() {
@@ -368,6 +434,7 @@ mod tests {
let error = handler
.create_directory(FsCreateDirectoryParams {
path: PathUri::from_host_native_path(&directory).expect("directory URI"),
+ follow_symlinks: None,
recursive: Some(false),
sandbox: None,
private: Some(true),
@@ -412,6 +479,7 @@ mod tests {
handler
.write_file(FsWriteFileParams {
path: path.clone(),
+ follow_symlinks: None,
data_base64: STANDARD.encode("ok"),
sandbox: Some(sandbox_context(sandbox_policy.clone())),
})
@@ -436,6 +504,7 @@ mod tests {
let response = handler
.read_file(FsReadFileParams {
path,
+ follow_symlinks: None,
sandbox: Some(sandbox_context(sandbox_policy)),
})
.await
diff --git a/codex-rs/exec-server/tests/file_stream.rs b/codex-rs/exec-server/tests/file_stream.rs
index cb03cc38b5..9fd3201eeb 100644
--- a/codex-rs/exec-server/tests/file_stream.rs
+++ b/codex-rs/exec-server/tests/file_stream.rs
@@ -9,6 +9,7 @@ use codex_exec_server::FsCloseParams;
use codex_exec_server::FsOpenParams;
use codex_exec_server::FsReadBlockParams;
use codex_exec_server::FsReadBlockResponse;
+use codex_exec_server::ReadFileOptions;
use codex_exec_server::RemoteExecServerConnectArgs;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
@@ -94,7 +95,7 @@ async fn file_reads_reject_fifo_without_waiting_for_a_writer() -> Result<()> {
let path_uri = PathUri::from_host_native_path(&path)?;
let read_error = timeout(
Duration::from_secs(1),
- file_system.read_file(&path_uri, /*sandbox*/ None),
+ file_system.read_file(&path_uri, ReadFileOptions::default(), /*sandbox*/ None),
)
.await
.expect("reading a FIFO should not wait for a writer")
@@ -130,6 +131,7 @@ async fn file_reads_reject_named_pipes() -> Result<()> {
Duration::from_secs(1),
file_system.read_file(
&PathUri::from_host_native_path(std::path::Path::new(&read_path))?,
+ ReadFileOptions::default(),
/*sandbox*/ None,
),
)
diff --git a/codex-rs/exec-server/tests/file_system/shared.rs b/codex-rs/exec-server/tests/file_system/shared.rs
index b62adf7009..5fd70bce5a 100644
--- a/codex-rs/exec-server/tests/file_system/shared.rs
+++ b/codex-rs/exec-server/tests/file_system/shared.rs
@@ -78,6 +78,7 @@ async fn file_system_get_metadata_reports_files_and_directories(
let file_metadata = file_system
.get_metadata(
&PathUri::from_host_native_path(&file_path)?,
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -98,6 +99,7 @@ async fn file_system_get_metadata_reports_files_and_directories(
let directory_metadata = file_system
.get_metadata(
&PathUri::from_host_native_path(&directory_path)?,
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -133,7 +135,10 @@ async fn file_system_create_directory_creates_nested_directories(
file_system
.create_directory(
&PathUri::from_host_native_path(&nested_dir)?,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await
@@ -158,6 +163,7 @@ async fn file_system_write_file_writes_bytes(
.write_file(
&PathUri::from_host_native_path(&file_path)?,
b"hello from trait".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -206,6 +212,7 @@ async fn file_system_read_file_returns_bytes(
let contents = file_system
.read_file(
&PathUri::from_host_native_path(&file_path)?,
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -274,6 +281,7 @@ async fn file_system_read_file_text_returns_string(
let contents = file_system
.read_file_text(
&PathUri::from_host_native_path(&file_path)?,
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -586,6 +594,7 @@ async fn file_system_remove_removes_directory(
RemoveOptions {
recursive: true,
force: true,
+ follow_symlinks: true,
},
/*sandbox*/ None,
)
@@ -612,6 +621,7 @@ async fn file_system_write_file_reports_missing_parent(
.write_file(
&PathUri::from_host_native_path(&missing_parent_path)?,
b"hello from trait".to_vec(),
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -677,7 +687,11 @@ async fn file_system_sandboxed_metadata_and_read_allow_readable_root(
let sandbox = read_only_sandbox(allowed_dir);
let metadata = file_system
- .get_metadata(&PathUri::from_host_native_path(&file_path)?, Some(&sandbox))
+ .get_metadata(
+ &PathUri::from_host_native_path(&file_path)?,
+ Default::default(),
+ Some(&sandbox),
+ )
.await
.with_context(|| format!("mode={implementation}"))?;
assert_eq!(
@@ -693,7 +707,11 @@ async fn file_system_sandboxed_metadata_and_read_allow_readable_root(
);
let contents = file_system
- .read_file(&PathUri::from_host_native_path(&file_path)?, Some(&sandbox))
+ .read_file(
+ &PathUri::from_host_native_path(&file_path)?,
+ Default::default(),
+ Some(&sandbox),
+ )
.await
.with_context(|| format!("mode={implementation}"))?;
assert_eq!(contents, b"sandboxed hello");
@@ -743,6 +761,7 @@ async fn sandboxed_file_operations_cannot_read_helper_siblings() -> Result<()> {
let allowed_contents = file_system
.read_file(
&PathUri::from_host_native_path(&allowed_file)?,
+ Default::default(),
Some(&sandbox),
)
.await?;
@@ -766,7 +785,10 @@ async fn sandboxed_file_operations_cannot_read_helper_siblings() -> Result<()> {
for path in [sibling, escaping_link] {
let path = PathUri::from_host_native_path(path)?;
assert!(
- file_system.read_file(&path, Some(&sandbox)).await.is_err(),
+ file_system
+ .read_file(&path, Default::default(), Some(&sandbox))
+ .await
+ .is_err(),
"sandboxed read unexpectedly accessed helper sibling {path}"
);
assert!(
@@ -901,6 +923,7 @@ async fn file_system_sandboxed_write_allows_additional_write_root(
.write_file(
&PathUri::from_host_native_path(&file_path)?,
b"created".to_vec(),
+ Default::default(),
Some(&sandbox),
)
.await
diff --git a/codex-rs/exec-server/tests/file_system_unix.rs b/codex-rs/exec-server/tests/file_system_unix.rs
index c045b3ae5c..860fde4298 100644
--- a/codex-rs/exec-server/tests/file_system_unix.rs
+++ b/codex-rs/exec-server/tests/file_system_unix.rs
@@ -8,13 +8,18 @@ mod shared;
#[path = "file_system/support.rs"]
mod support;
+use std::ffi::CString;
+use std::os::unix::ffi::OsStrExt;
+use std::os::unix::fs::FileTypeExt;
use std::os::unix::fs::MetadataExt;
-#[cfg(target_os = "linux")]
use std::os::unix::fs::PermissionsExt;
use std::os::unix::fs::symlink;
+use std::os::unix::net::UnixListener;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
+use std::sync::Arc;
+use std::time::Duration;
use anyhow::Context;
use anyhow::Result;
@@ -24,12 +29,15 @@ use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::Environment;
use codex_exec_server::FileMetadata;
use codex_exec_server::FileSystemSandboxContext;
+use codex_exec_server::GetMetadataOptions;
use codex_exec_server::ReadDirectoryEntry;
+use codex_exec_server::ReadFileOptions;
use codex_exec_server::RemoveOptions;
use codex_exec_server::WalkEntry;
use codex_exec_server::WalkEntryKind;
use codex_exec_server::WalkOptions;
use codex_exec_server::WalkOutcome;
+use codex_exec_server::WriteFileOptions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
@@ -41,6 +49,7 @@ use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use test_case::test_case;
+use tokio::time::timeout;
#[cfg(target_os = "linux")]
use crate::common::exec_server::exec_server_with_env;
@@ -165,6 +174,341 @@ async fn file_system_canonicalize_resolves_directory_symlink(
.await
}
+#[test_case(FileSystemImplementation::Local ; "local")]
+#[test_case(FileSystemImplementation::Remote ; "remote")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn file_system_operations_can_reject_symlinks_in_any_path_component(
+ implementation: FileSystemImplementation,
+) -> Result<()> {
+ let context = create_file_system_context(implementation).await?;
+ let tmp = TempDir::new()?;
+ let tmp_path = tmp.path().canonicalize()?;
+ let real = tmp_path.join("real");
+ std::fs::create_dir(&real)?;
+ let existing = real.join("existing.txt");
+ std::fs::write(&existing, "unchanged")?;
+ let removable = real.join("removable.txt");
+ std::fs::write(&removable, "keep")?;
+ let directory_link = tmp_path.join("directory-link");
+ symlink(&real, &directory_link)?;
+ let file_link = tmp_path.join("file-link");
+ symlink(&existing, &file_link)?;
+
+ let no_follow_read = ReadFileOptions {
+ follow_symlinks: false,
+ };
+ let no_follow_write = WriteFileOptions {
+ follow_symlinks: false,
+ };
+ let no_follow_metadata = GetMetadataOptions {
+ follow_symlinks: false,
+ };
+ let no_follow_create = CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: false,
+ };
+ let no_follow_remove = RemoveOptions {
+ recursive: false,
+ force: false,
+ follow_symlinks: false,
+ };
+ let uri = |path: &Path| PathUri::from_host_native_path(path);
+
+ assert!(
+ context
+ .file_system
+ .read_file(&uri(&file_link)?, no_follow_read, /*sandbox*/ None)
+ .await
+ .is_err()
+ );
+ assert!(
+ context
+ .file_system
+ .read_file(
+ &uri(&directory_link.join("existing.txt"))?,
+ no_follow_read,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ assert!(
+ context
+ .file_system
+ .write_file(
+ &uri(&file_link)?,
+ b"changed".to_vec(),
+ no_follow_write,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ assert_eq!(std::fs::read_to_string(&existing)?, "unchanged");
+ assert!(
+ context
+ .file_system
+ .write_file(
+ &uri(&directory_link.join("existing.txt"))?,
+ b"changed".to_vec(),
+ no_follow_write,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ assert_eq!(std::fs::read_to_string(&existing)?, "unchanged");
+ assert!(
+ context
+ .file_system
+ .get_metadata(&uri(&file_link)?, no_follow_metadata, /*sandbox*/ None)
+ .await
+ .is_err()
+ );
+ let directory_metadata = context
+ .file_system
+ .get_metadata(&uri(&real)?, no_follow_metadata, /*sandbox*/ None)
+ .await?;
+ assert!(directory_metadata.is_directory);
+ assert!(
+ context
+ .file_system
+ .create_directory(
+ &uri(&directory_link.join("created"))?,
+ no_follow_create,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ assert!(!real.join("created").exists());
+ assert!(
+ context
+ .file_system
+ .remove(
+ &uri(&directory_link.join("removable.txt"))?,
+ no_follow_remove,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ assert!(removable.exists());
+ assert!(
+ context
+ .file_system
+ .remove(&uri(&file_link)?, no_follow_remove, /*sandbox*/ None)
+ .await
+ .is_err()
+ );
+ assert!(file_link.symlink_metadata()?.file_type().is_symlink());
+
+ Ok(())
+}
+
+#[test_case(FileSystemImplementation::Local ; "local")]
+#[test_case(FileSystemImplementation::Remote ; "remote")]
+#[tokio::test]
+async fn file_system_no_follow_non_recursive_root_creation_fails(
+ implementation: FileSystemImplementation,
+) -> Result<()> {
+ let context = create_file_system_context(implementation).await?;
+ let result = context
+ .file_system
+ .create_directory(
+ &PathUri::from_host_native_path(Path::new("/"))?,
+ CreateDirectoryOptions {
+ recursive: false,
+ follow_symlinks: false,
+ },
+ /*sandbox*/ None,
+ )
+ .await;
+
+ assert!(result.is_err());
+ Ok(())
+}
+
+#[test_case(FileSystemImplementation::Local ; "local")]
+#[test_case(FileSystemImplementation::Remote ; "remote")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn file_system_no_follow_operations_support_search_only_ancestors(
+ implementation: FileSystemImplementation,
+) -> Result<()> {
+ let context = create_file_system_context(implementation).await?;
+ let tmp = TempDir::new()?;
+ let root = tmp.path().canonicalize()?;
+ let search_only = root.join("search-only");
+ std::fs::create_dir(&search_only)?;
+ let existing = search_only.join("existing.txt");
+ std::fs::write(&existing, "before")?;
+ let unreadable = search_only.join("unreadable.txt");
+ std::fs::write(&unreadable, "metadata only")?;
+ std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000))?;
+ let socket_path = search_only.join("socket");
+ let _socket = UnixListener::bind(&socket_path)?;
+ let removable = search_only.join("removable.txt");
+ std::fs::write(&removable, "remove")?;
+ std::fs::set_permissions(&search_only, std::fs::Permissions::from_mode(0o300))?;
+
+ let uri = |path: &Path| PathUri::from_host_native_path(path);
+ let result: Result<()> = async {
+ let root_metadata = context
+ .file_system
+ .get_metadata(
+ &uri(Path::new("/"))?,
+ GetMetadataOptions {
+ follow_symlinks: false,
+ },
+ /*sandbox*/ None,
+ )
+ .await?;
+ assert!(root_metadata.is_directory);
+
+ assert_eq!(
+ context
+ .file_system
+ .read_file(
+ &uri(&existing)?,
+ ReadFileOptions {
+ follow_symlinks: false,
+ },
+ /*sandbox*/ None,
+ )
+ .await?,
+ b"before"
+ );
+ context
+ .file_system
+ .write_file(
+ &uri(&existing)?,
+ b"after".to_vec(),
+ WriteFileOptions {
+ follow_symlinks: false,
+ },
+ /*sandbox*/ None,
+ )
+ .await?;
+ assert_eq!(std::fs::read_to_string(&existing)?, "after");
+
+ for metadata_path in [&unreadable, &socket_path] {
+ context
+ .file_system
+ .get_metadata(
+ &uri(metadata_path)?,
+ GetMetadataOptions {
+ follow_symlinks: false,
+ },
+ /*sandbox*/ None,
+ )
+ .await?;
+ }
+
+ let nested = search_only.join("created").join("nested");
+ context
+ .file_system
+ .create_directory(
+ &uri(&nested)?,
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: false,
+ },
+ /*sandbox*/ None,
+ )
+ .await?;
+ assert!(nested.is_dir());
+
+ context
+ .file_system
+ .remove(
+ &uri(&removable)?,
+ RemoveOptions {
+ recursive: false,
+ force: false,
+ follow_symlinks: false,
+ },
+ /*sandbox*/ None,
+ )
+ .await?;
+ assert!(!removable.exists());
+ Ok(())
+ }
+ .await;
+
+ std::fs::set_permissions(&search_only, std::fs::Permissions::from_mode(0o700))?;
+ std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o600))?;
+ result
+}
+
+#[test_case(FileSystemImplementation::Local ; "local")]
+#[test_case(FileSystemImplementation::Remote ; "remote")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn file_system_no_follow_write_rejects_fifo_without_blocking(
+ implementation: FileSystemImplementation,
+) -> Result<()> {
+ let context = create_file_system_context(implementation).await?;
+ let tmp = TempDir::new()?;
+ let fifo = tmp.path().canonicalize()?.join("fifo");
+ let fifo_c = CString::new(fifo.as_os_str().as_bytes())?;
+ if unsafe { libc::mkfifo(fifo_c.as_ptr(), 0o600) } != 0 {
+ return Err(std::io::Error::last_os_error().into());
+ }
+
+ let result = timeout(
+ Duration::from_secs(1),
+ context.file_system.write_file(
+ &PathUri::from_host_native_path(&fifo)?,
+ b"must not be written".to_vec(),
+ WriteFileOptions {
+ follow_symlinks: false,
+ },
+ /*sandbox*/ None,
+ ),
+ )
+ .await
+ .context("strict FIFO write must not block")?;
+ assert!(result.is_err());
+ assert!(fifo.symlink_metadata()?.file_type().is_fifo());
+ Ok(())
+}
+
+#[test_case(FileSystemImplementation::Local ; "local")]
+#[test_case(FileSystemImplementation::Remote ; "remote")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn file_system_no_follow_recursive_mkdir_handles_concurrent_creators(
+ implementation: FileSystemImplementation,
+) -> Result<()> {
+ let context = create_file_system_context(implementation).await?;
+ let tmp = TempDir::new()?;
+ let path = tmp.path().canonicalize()?.join("shared").join("nested");
+ let path_uri = PathUri::from_host_native_path(&path)?;
+ let barrier = Arc::new(tokio::sync::Barrier::new(16));
+ let mut tasks = Vec::new();
+ for _ in 0..16 {
+ let file_system = Arc::clone(&context.file_system);
+ let path_uri = path_uri.clone();
+ let barrier = Arc::clone(&barrier);
+ tasks.push(tokio::spawn(async move {
+ barrier.wait().await;
+ file_system
+ .create_directory(
+ &path_uri,
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: false,
+ },
+ /*sandbox*/ None,
+ )
+ .await
+ }));
+ }
+ for task in tasks {
+ task.await??;
+ }
+ assert!(path.is_dir());
+ Ok(())
+}
+
#[test_case(FileSystemImplementation::Local ; "local")]
#[test_case(FileSystemImplementation::Remote ; "remote")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -202,6 +546,7 @@ async fn sandboxed_file_system_helper_finds_bwrap_on_preserved_path() -> Result<
.write_file(
&PathUri::from_host_native_path(&file_path)?,
b"written through fs helper".to_vec(),
+ Default::default(),
Some(&sandbox),
)
.await?;
@@ -248,6 +593,7 @@ async fn remote_read_file_materializes_environment_workspace_roots() -> Result<(
file_system
.read_file(
&PathUri::from_host_native_path(&workspace_file)?,
+ Default::default(),
Some(&sandbox),
)
.await?,
@@ -256,6 +602,7 @@ async fn remote_read_file_materializes_environment_workspace_roots() -> Result<(
let error = file_system
.read_file(
&PathUri::from_host_native_path(&excluded_file)?,
+ Default::default(),
Some(&sandbox),
)
.await
@@ -287,7 +634,11 @@ async fn remote_read_file_preserves_empty_workspace_roots() -> Result<()> {
sandbox.workspace_roots.clear();
let error = file_system
- .read_file(&PathUri::from_host_native_path(&file)?, Some(&sandbox))
+ .read_file(
+ &PathUri::from_host_native_path(&file)?,
+ Default::default(),
+ Some(&sandbox),
+ )
.await
.expect_err("empty workspace roots should not grant cwd access");
assert_sandbox_denied(&error);
@@ -312,6 +663,7 @@ async fn file_system_metadata_and_directory_listing_follow_symlinks(
let symlink_metadata = file_system
.get_metadata(
&PathUri::from_host_native_path(&symlink_path)?,
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -336,6 +688,7 @@ async fn file_system_metadata_and_directory_listing_follow_symlinks(
let dir_symlink_metadata = file_system
.get_metadata(
&PathUri::from_host_native_path(&dir_symlink_path)?,
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -357,6 +710,7 @@ async fn file_system_metadata_and_directory_listing_follow_symlinks(
let error = file_system
.get_metadata(
&PathUri::from_host_native_path(&dangling_symlink_path)?,
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -554,6 +908,7 @@ async fn file_system_sandboxed_write_rejects_unwritable_path(
.write_file(
&PathUri::from_host_native_path(&blocked_path)?,
b"nope".to_vec(),
+ Default::default(),
Some(&sandbox),
)
.await
@@ -590,6 +945,7 @@ async fn file_system_sandboxed_write_allows_explicit_alias_roots(
.write_file(
&PathUri::from_host_native_path(&file_path)?,
b"created".to_vec(),
+ Default::default(),
Some(&sandbox),
)
.await
@@ -621,6 +977,7 @@ async fn file_system_sandboxed_read_rejects_symlink_escape(
let error = match file_system
.read_file(
&PathUri::from_host_native_path(&requested_path)?,
+ Default::default(),
Some(&sandbox),
)
.await
@@ -664,7 +1021,10 @@ async fn file_system_sandboxed_read_rejects_symlink_parent_dotdot_escape(
let requested_path =
PathUri::from_host_native_path(allowed_dir.join("link").join("..").join("secret.txt"))?;
let sandbox = read_only_sandbox(allowed_dir);
- let error = match file_system.read_file(&requested_path, Some(&sandbox)).await {
+ let error = match file_system
+ .read_file(&requested_path, Default::default(), Some(&sandbox))
+ .await
+ {
Ok(_) => anyhow::bail!("read should fail after path normalization"),
Err(error) => error,
};
@@ -700,6 +1060,7 @@ async fn file_system_sandboxed_write_rejects_symlink_escape(
.write_file(
&PathUri::from_host_native_path(&requested_path)?,
b"nope".to_vec(),
+ Default::default(),
Some(&sandbox),
)
.await
@@ -738,6 +1099,7 @@ async fn file_system_sandboxed_write_preserves_existing_hard_link(
.write_file(
&PathUri::from_host_native_path(&hard_link)?,
b"updated through existing hard link\n".to_vec(),
+ Default::default(),
Some(&sandbox),
)
.await
@@ -783,7 +1145,10 @@ async fn file_system_create_directory_rejects_symlink_escape(
let error = match file_system
.create_directory(
&PathUri::from_host_native_path(&requested_path)?,
- CreateDirectoryOptions { recursive: false },
+ CreateDirectoryOptions {
+ recursive: false,
+ follow_symlinks: true,
+ },
Some(&sandbox),
)
.await
@@ -894,6 +1259,7 @@ async fn file_system_remove_removes_symlink_not_target(
RemoveOptions {
recursive: false,
force: false,
+ follow_symlinks: true,
},
Some(&sandbox),
)
@@ -971,6 +1337,7 @@ async fn file_system_remove_rejects_symlink_escape(
RemoveOptions {
recursive: false,
force: false,
+ follow_symlinks: true,
},
Some(&sandbox),
)
diff --git a/codex-rs/exec-server/tests/file_system_windows.rs b/codex-rs/exec-server/tests/file_system_windows.rs
index 1d5b4a13fe..c4e21fd27c 100644
--- a/codex-rs/exec-server/tests/file_system_windows.rs
+++ b/codex-rs/exec-server/tests/file_system_windows.rs
@@ -10,13 +10,22 @@ mod support;
use std::path::Path;
use std::process::Command;
+use std::time::Duration;
use anyhow::Result;
+use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::FileSystemSandboxContext;
+use codex_exec_server::GetMetadataOptions;
+use codex_exec_server::ReadFileOptions;
+use codex_exec_server::RemoveOptions;
+use codex_exec_server::WriteFileOptions;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::protocol::SandboxPolicy;
use codex_utils_path_uri::PathUri;
use test_case::test_case;
+use tokio::net::windows::named_pipe::ServerOptions;
+use tokio::time::timeout;
+use uuid::Uuid;
use crate::support::FileSystemImplementation;
use crate::support::create_file_system_context;
@@ -60,6 +69,267 @@ async fn file_system_sandboxed_canonicalize_resolves_directory_junction(
.await
}
+#[test_case(FileSystemImplementation::Local ; "local")]
+#[test_case(FileSystemImplementation::Remote ; "remote")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn file_system_operations_can_reject_junctions_in_any_path_component(
+ implementation: FileSystemImplementation,
+) -> Result<()> {
+ let context = create_file_system_context(implementation).await?;
+ let tmp = tempfile::TempDir::new()?;
+ let real = tmp.path().join("real");
+ std::fs::create_dir(&real)?;
+ let existing = real.join("existing.txt");
+ std::fs::write(&existing, "unchanged")?;
+ let removable = real.join("removable.txt");
+ std::fs::write(&removable, "keep")?;
+ let directory_junction = tmp.path().join("directory-junction");
+ create_directory_junction(&real, &directory_junction)?;
+
+ let no_follow_read = ReadFileOptions {
+ follow_symlinks: false,
+ };
+ let no_follow_write = WriteFileOptions {
+ follow_symlinks: false,
+ };
+ let no_follow_metadata = GetMetadataOptions {
+ follow_symlinks: false,
+ };
+ let no_follow_create = CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: false,
+ };
+ let no_follow_remove = RemoveOptions {
+ recursive: false,
+ force: false,
+ follow_symlinks: false,
+ };
+ let uri = |path: &Path| PathUri::from_host_native_path(path);
+
+ assert_eq!(
+ context
+ .file_system
+ .read_file(&uri(&existing)?, no_follow_read, /*sandbox*/ None,)
+ .await?,
+ b"unchanged"
+ );
+
+ let overwritten = real.join("overwritten.txt");
+ std::fs::write(&overwritten, "before")?;
+ context
+ .file_system
+ .write_file(
+ &uri(&overwritten)?,
+ b"after".to_vec(),
+ no_follow_write,
+ /*sandbox*/ None,
+ )
+ .await?;
+ assert_eq!(std::fs::read_to_string(&overwritten)?, "after");
+
+ let created_file = real.join("created.txt");
+ context
+ .file_system
+ .write_file(
+ &uri(&created_file)?,
+ b"created".to_vec(),
+ no_follow_write,
+ /*sandbox*/ None,
+ )
+ .await?;
+ assert_eq!(std::fs::read_to_string(&created_file)?, "created");
+
+ let nested_directory = real.join("nested").join("directory");
+ context
+ .file_system
+ .create_directory(
+ &uri(&nested_directory)?,
+ no_follow_create,
+ /*sandbox*/ None,
+ )
+ .await?;
+ assert!(nested_directory.is_dir());
+
+ let removed_file = real.join("removed.txt");
+ std::fs::write(&removed_file, "remove")?;
+ context
+ .file_system
+ .remove(
+ &uri(&removed_file)?,
+ no_follow_remove,
+ /*sandbox*/ None,
+ )
+ .await?;
+ assert!(!removed_file.exists());
+
+ let removed_directory = real.join("removed-directory");
+ std::fs::create_dir(&removed_directory)?;
+ context
+ .file_system
+ .remove(
+ &uri(&removed_directory)?,
+ no_follow_remove,
+ /*sandbox*/ None,
+ )
+ .await?;
+ assert!(!removed_directory.exists());
+
+ let file_link_target = real.join("file-link-target.txt");
+ std::fs::write(&file_link_target, "target")?;
+ let file_link = tmp.path().join("file-link.txt");
+ if std::os::windows::fs::symlink_file(&file_link_target, &file_link).is_ok() {
+ assert!(
+ context
+ .file_system
+ .write_file(
+ &uri(&file_link)?,
+ b"changed".to_vec(),
+ no_follow_write,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ assert_eq!(std::fs::read_to_string(&file_link_target)?, "target");
+ }
+
+ assert!(
+ context
+ .file_system
+ .read_file(
+ &uri(&directory_junction.join("existing.txt"))?,
+ no_follow_read,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ assert!(
+ context
+ .file_system
+ .write_file(
+ &uri(&directory_junction.join("existing.txt"))?,
+ b"changed".to_vec(),
+ no_follow_write,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ assert_eq!(std::fs::read_to_string(&existing)?, "unchanged");
+ assert!(
+ context
+ .file_system
+ .get_metadata(
+ &uri(&directory_junction)?,
+ no_follow_metadata,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ let directory_metadata = context
+ .file_system
+ .get_metadata(&uri(&real)?, no_follow_metadata, /*sandbox*/ None)
+ .await?;
+ assert!(directory_metadata.is_directory);
+ assert!(
+ context
+ .file_system
+ .create_directory(
+ &uri(&directory_junction.join("created"))?,
+ no_follow_create,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ assert!(!real.join("created").exists());
+ assert!(
+ context
+ .file_system
+ .remove(
+ &uri(&directory_junction.join("removable.txt"))?,
+ no_follow_remove,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ assert!(removable.exists());
+ assert!(
+ context
+ .file_system
+ .remove(
+ &uri(&directory_junction)?,
+ no_follow_remove,
+ /*sandbox*/ None,
+ )
+ .await
+ .is_err()
+ );
+ assert!(
+ directory_junction
+ .symlink_metadata()?
+ .file_type()
+ .is_symlink()
+ );
+
+ Ok(())
+}
+
+#[test_case(FileSystemImplementation::Local ; "local")]
+#[test_case(FileSystemImplementation::Remote ; "remote")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn file_system_no_follow_operations_reject_named_pipes(
+ implementation: FileSystemImplementation,
+) -> Result<()> {
+ let context = create_file_system_context(implementation).await?;
+ let pipe_name = format!("codex-fs-no-follow-{}", Uuid::new_v4());
+ let server_path = format!(r"\\.\pipe\{pipe_name}");
+ let client_path = format!(r"\\localhost\pipe\{pipe_name}");
+ let _pipe = ServerOptions::new()
+ .first_pipe_instance(true)
+ .create(&server_path)?;
+
+ let error = timeout(
+ Duration::from_secs(1),
+ context.file_system.read_file(
+ &PathUri::from_host_native_path(Path::new(&client_path))?,
+ ReadFileOptions {
+ follow_symlinks: false,
+ },
+ /*sandbox*/ None,
+ ),
+ )
+ .await
+ .expect("strict named-pipe read must not hang")
+ .expect_err("strict named-pipe read must be rejected");
+ assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
+
+ let pipe_name = format!("codex-fs-no-follow-write-{}", Uuid::new_v4());
+ let server_path = format!(r"\\.\pipe\{pipe_name}");
+ let client_path = format!(r"\\localhost\pipe\{pipe_name}");
+ let _pipe = ServerOptions::new()
+ .first_pipe_instance(true)
+ .create(&server_path)?;
+ timeout(
+ Duration::from_secs(1),
+ context.file_system.write_file(
+ &PathUri::from_host_native_path(Path::new(&client_path))?,
+ b"must not be written".to_vec(),
+ WriteFileOptions {
+ follow_symlinks: false,
+ },
+ /*sandbox*/ None,
+ ),
+ )
+ .await
+ .expect("strict named-pipe write must not hang")
+ .expect_err("strict named-pipe write must be rejected");
+ Ok(())
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn file_system_remote_fs_helper_respects_windows_sandbox_write_policy() -> Result<()> {
let context = create_file_system_context(FileSystemImplementation::Remote).await?;
@@ -76,6 +346,7 @@ async fn file_system_remote_fs_helper_respects_windows_sandbox_write_policy() ->
let read_result = file_system
.read_file(
&PathUri::from_host_native_path(&readable_file)?,
+ ReadFileOptions::default(),
Some(&sandbox),
)
.await;
@@ -92,6 +363,7 @@ async fn file_system_remote_fs_helper_respects_windows_sandbox_write_policy() ->
.write_file(
&PathUri::from_host_native_path(&blocked_file)?,
b"blocked".to_vec(),
+ WriteFileOptions::default(),
Some(&sandbox),
)
.await
diff --git a/codex-rs/exec-server/tests/forward.rs b/codex-rs/exec-server/tests/forward.rs
index c51eb561eb..33f7bec91e 100644
--- a/codex-rs/exec-server/tests/forward.rs
+++ b/codex-rs/exec-server/tests/forward.rs
@@ -115,6 +115,7 @@ async fn forwarder_runs_commands_and_transfers_files() -> Result<()> {
TEST_TIMEOUT,
client.fs_write_file(FsWriteFileParams {
path: PathUri::from_host_native_path(&path)?,
+ follow_symlinks: None,
data_base64: STANDARD.encode(&contents),
sandbox: None,
}),
@@ -124,6 +125,7 @@ async fn forwarder_runs_commands_and_transfers_files() -> Result<()> {
let read_response = client
.fs_read_file(FsReadFileParams {
path: PathUri::from_host_native_path(path)?,
+ follow_symlinks: None,
sandbox: None,
})
.await?;
diff --git a/codex-rs/exec-server/tests/relay.rs b/codex-rs/exec-server/tests/relay.rs
index ca8bc9fe1d..119fe9f2cd 100644
--- a/codex-rs/exec-server/tests/relay.rs
+++ b/codex-rs/exec-server/tests/relay.rs
@@ -355,6 +355,7 @@ async fn remote_environment_routes_encrypted_exec_server_rpc() -> Result<()> {
let read_response = client
.fs_read_file(FsReadFileParams {
path: PathUri::from_host_native_path(large_file_path)?,
+ follow_symlinks: None,
sandbox: None,
})
.await?;
diff --git a/codex-rs/ext/connectors/Cargo.toml b/codex-rs/ext/connectors/Cargo.toml
index 044d8264b2..1aead72773 100644
--- a/codex-rs/ext/connectors/Cargo.toml
+++ b/codex-rs/ext/connectors/Cargo.toml
@@ -16,6 +16,7 @@ workspace = true
[dependencies]
codex-connectors = { workspace = true }
codex-core-plugins = { workspace = true }
+codex-file-system = { workspace = true }
codex-plugin = { workspace = true }
codex-utils-path-uri = { workspace = true }
serde_json = { workspace = true }
diff --git a/codex-rs/ext/connectors/src/executor_plugin.rs b/codex-rs/ext/connectors/src/executor_plugin.rs
index 0436c5429b..c8d51e80ec 100644
--- a/codex-rs/ext/connectors/src/executor_plugin.rs
+++ b/codex-rs/ext/connectors/src/executor_plugin.rs
@@ -1,5 +1,6 @@
use codex_connectors::parse_plugin_app_config;
use codex_core_plugins::ResolvedExecutorPlugin;
+use codex_file_system::ReadFileOptions;
use codex_plugin::AppDeclaration;
use codex_plugin::PluginResourceLocator;
use codex_utils_path_uri::PathUri;
@@ -46,7 +47,11 @@ impl ExecutorPluginConnectorProvider {
};
let contents = plugin
.file_system()
- .read_file_text(config_path, /*sandbox*/ None)
+ .read_file_text(
+ config_path,
+ ReadFileOptions::default(),
+ /*sandbox*/ None,
+ )
.await
.map_err(|source| ExecutorPluginConnectorProviderError::ReadConfig {
plugin_id: plugin_id.to_string(),
diff --git a/codex-rs/ext/image-generation/src/tool.rs b/codex-rs/ext/image-generation/src/tool.rs
index d71f6d2b30..1c916fc4d4 100644
--- a/codex-rs/ext/image-generation/src/tool.rs
+++ b/codex-rs/ext/image-generation/src/tool.rs
@@ -278,13 +278,21 @@ async fn save_image_generation_result(
LOCAL_FS
.create_directory(
&PathUri::from_abs_path(&parent),
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
/*sandbox*/ None,
)
.await?;
}
LOCAL_FS
- .write_file(&PathUri::from_abs_path(&path), bytes, /*sandbox*/ None)
+ .write_file(
+ &PathUri::from_abs_path(&path),
+ bytes,
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await?;
Ok(path)
}
@@ -322,7 +330,10 @@ async fn save_image_generation_result(
.file_system
.create_directory(
&parent_uri,
- CreateDirectoryOptions { recursive: true },
+ CreateDirectoryOptions {
+ recursive: true,
+ follow_symlinks: true,
+ },
sandbox,
)
.await?;
@@ -330,7 +341,7 @@ async fn save_image_generation_result(
// Full-access executor contexts do not prevent symlinked output directories.
let metadata = environment
.file_system
- .get_metadata(&parent_uri, sandbox)
+ .get_metadata(&parent_uri, Default::default(), sandbox)
.await?;
if metadata.is_symlink || !metadata.is_directory {
return Err(io::Error::new(
@@ -344,7 +355,7 @@ async fn save_image_generation_result(
let path_uri = PathUri::from_abs_path(&path);
match environment
.file_system
- .get_metadata(&path_uri, sandbox)
+ .get_metadata(&path_uri, Default::default(), sandbox)
.await
{
Ok(_) => {
@@ -359,7 +370,7 @@ async fn save_image_generation_result(
environment
.file_system
- .write_file(&path_uri, bytes, sandbox)
+ .write_file(&path_uri, bytes, Default::default(), sandbox)
.await?;
Ok(path)
}
@@ -563,7 +574,7 @@ async fn image_url(
let sandbox = environment.file_system_sandbox_context.clone();
let bytes = environment
.file_system
- .read_file(&path_uri, Some(&sandbox))
+ .read_file(&path_uri, Default::default(), Some(&sandbox))
.await
.map_err(|error| {
FunctionCallError::RespondToModel(format!(
diff --git a/codex-rs/ext/mcp/src/executor_plugin/provider.rs b/codex-rs/ext/mcp/src/executor_plugin/provider.rs
index 58b5e9f63b..0ab3d5d3ba 100644
--- a/codex-rs/ext/mcp/src/executor_plugin/provider.rs
+++ b/codex-rs/ext/mcp/src/executor_plugin/provider.rs
@@ -1,6 +1,7 @@
use codex_config::McpServerConfig;
use codex_core_plugins::ResolvedExecutorPlugin;
use codex_exec_server::ExecutorFileSystem;
+use codex_exec_server::ReadFileOptions;
use codex_mcp::parse_executor_plugin_mcp_config;
use codex_plugin::PluginResourceLocator;
use codex_plugin::ResolvedPlugin;
@@ -72,7 +73,7 @@ async fn load_from_file_system(
})) => {
(
file_system
- .read_file_text(path, /*sandbox*/ None)
+ .read_file_text(path, ReadFileOptions::default(), /*sandbox*/ None)
.await
.map_err(|source| ExecutorPluginMcpProviderError::ReadConfig {
plugin_id: plugin_id.to_string(),
@@ -96,7 +97,11 @@ async fn load_from_file_system(
source,
})?;
let contents = match file_system
- .read_file_text(&config_path, /*sandbox*/ None)
+ .read_file_text(
+ &config_path,
+ ReadFileOptions::default(),
+ /*sandbox*/ None,
+ )
.await
{
Ok(contents) => contents,
diff --git a/codex-rs/ext/mcp/src/executor_plugin/provider_tests.rs b/codex-rs/ext/mcp/src/executor_plugin/provider_tests.rs
index d08c8d4975..7870d92a2a 100644
--- a/codex-rs/ext/mcp/src/executor_plugin/provider_tests.rs
+++ b/codex-rs/ext/mcp/src/executor_plugin/provider_tests.rs
@@ -11,8 +11,11 @@ use codex_exec_server::FileMetadata;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::FileSystemResult;
use codex_exec_server::FileSystemSandboxContext;
+use codex_exec_server::GetMetadataOptions;
use codex_exec_server::ReadDirectoryEntry;
+use codex_exec_server::ReadFileOptions;
use codex_exec_server::RemoveOptions;
+use codex_exec_server::WriteFileOptions;
use codex_plugin::ResolvedPlugin;
use codex_plugin::manifest::PluginManifest;
use codex_plugin::manifest::PluginManifestMcpServers;
@@ -59,6 +62,7 @@ impl ExecutorFileSystem for SyntheticExecutorFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ _options: ReadFileOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
Box::pin(async move {
@@ -88,6 +92,7 @@ impl ExecutorFileSystem for SyntheticExecutorFileSystem {
&'a self,
_path: &'a PathUri,
_contents: Vec<u8>,
+ _options: WriteFileOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
Box::pin(async { Self::unsupported() })
@@ -105,6 +110,7 @@ impl ExecutorFileSystem for SyntheticExecutorFileSystem {
fn get_metadata<'a>(
&'a self,
_path: &'a PathUri,
+ _options: GetMetadataOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(async { Self::unsupported() })
diff --git a/codex-rs/ext/skills/src/host_outcome.rs b/codex-rs/ext/skills/src/host_outcome.rs
index 2a63fa6d0f..79f4f2b453 100644
--- a/codex-rs/ext/skills/src/host_outcome.rs
+++ b/codex-rs/ext/skills/src/host_outcome.rs
@@ -6,6 +6,7 @@ use std::sync::Arc;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::LOCAL_FS;
+use codex_exec_server::ReadFileOptions;
use codex_skills::SkillError;
use codex_skills::SkillMetadata;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -117,7 +118,8 @@ impl SkillLoadOutcome {
.file_system_for_skill(skill)
.unwrap_or_else(|| Arc::clone(&LOCAL_FS));
let path = PathUri::from_abs_path(&skill.path_to_skills_md);
- fs.read_file_text(&path, /*sandbox*/ None).await
+ fs.read_file_text(&path, ReadFileOptions::default(), /*sandbox*/ None)
+ .await
}
}
diff --git a/codex-rs/ext/skills/src/host_roots.rs b/codex-rs/ext/skills/src/host_roots.rs
index df9c419fbe..ac2bf3e9cd 100644
--- a/codex-rs/ext/skills/src/host_roots.rs
+++ b/codex-rs/ext/skills/src/host_roots.rs
@@ -8,6 +8,7 @@ use codex_config::default_project_root_markers;
use codex_config::merge_toml_values;
use codex_config::project_root_markers_from_config;
use codex_exec_server::ExecutorFileSystem;
+use codex_exec_server::GetMetadataOptions;
use codex_exec_server::LOCAL_FS;
use codex_protocol::protocol::SkillScope;
use codex_skills::system_cache_root_dir;
@@ -153,7 +154,11 @@ async fn repo_agents_skill_roots(
let agents_skills = directory.join(AGENTS_DIR_NAME).join(SKILLS_DIR_NAME);
let agents_skills_uri = PathUri::from_abs_path(&agents_skills);
let result = repository_file_system
- .get_metadata(&agents_skills_uri, /*sandbox*/ None)
+ .get_metadata(
+ &agents_skills_uri,
+ GetMetadataOptions::default(),
+ /*sandbox*/ None,
+ )
.await;
(agents_skills, result)
}
@@ -217,7 +222,11 @@ async fn find_project_root(
.map(|(ancestor, marker_path)| async move {
let marker_path_uri = PathUri::from_abs_path(&marker_path);
let result = repository_file_system
- .get_metadata(&marker_path_uri, /*sandbox*/ None)
+ .get_metadata(
+ &marker_path_uri,
+ GetMetadataOptions::default(),
+ /*sandbox*/ None,
+ )
.await;
(ancestor, marker_path, result)
})
diff --git a/codex-rs/ext/skills/src/host_roots_tests.rs b/codex-rs/ext/skills/src/host_roots_tests.rs
index d7a1ba22c4..fee6c1a039 100644
--- a/codex-rs/ext/skills/src/host_roots_tests.rs
+++ b/codex-rs/ext/skills/src/host_roots_tests.rs
@@ -14,11 +14,14 @@ use codex_exec_server::ExecutorFileSystemFuture;
use codex_exec_server::FileMetadata;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::FileSystemSandboxContext;
+use codex_exec_server::GetMetadataOptions;
use codex_exec_server::LOCAL_FS;
use codex_exec_server::ReadDirectoryEntry;
+use codex_exec_server::ReadFileOptions;
use codex_exec_server::RemoveOptions;
use codex_exec_server::WalkOptions;
use codex_exec_server::WalkOutcome;
+use codex_exec_server::WriteFileOptions;
use codex_protocol::protocol::SkillScope;
use codex_skills::SkillMetadata;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -70,9 +73,10 @@ impl ExecutorFileSystem for BlockingMetadataFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ options: ReadFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
- self.inner.read_file(path, sandbox)
+ self.inner.read_file(path, options, sandbox)
}
fn read_file_stream<'a>(
@@ -87,9 +91,10 @@ impl ExecutorFileSystem for BlockingMetadataFileSystem {
&'a self,
path: &'a PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
- self.inner.write_file(path, contents, sandbox)
+ self.inner.write_file(path, contents, options, sandbox)
}
fn create_directory<'a>(
@@ -104,14 +109,15 @@ impl ExecutorFileSystem for BlockingMetadataFileSystem {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
let Ok(path_abs) = path.to_abs_path() else {
- return self.inner.get_metadata(path, sandbox);
+ return self.inner.get_metadata(path, options, sandbox);
};
let repo_skill_root_suffix = Path::new(".agents").join("skills");
if !path_abs.ends_with(repo_skill_root_suffix) {
- return self.inner.get_metadata(path, sandbox);
+ return self.inner.get_metadata(path, options, sandbox);
}
self.calls
@@ -127,7 +133,7 @@ impl ExecutorFileSystem for BlockingMetadataFileSystem {
.await
.expect("metadata release semaphore")
.forget();
- self.inner.get_metadata(path, sandbox).await
+ self.inner.get_metadata(path, options, sandbox).await
})
}
diff --git a/codex-rs/ext/skills/src/loader/environment.rs b/codex-rs/ext/skills/src/loader/environment.rs
index 89f8c49b9c..3b7ca9ed2b 100644
--- a/codex-rs/ext/skills/src/loader/environment.rs
+++ b/codex-rs/ext/skills/src/loader/environment.rs
@@ -3,6 +3,8 @@ use std::io;
use codex_exec_server::CapabilityRootDiscovery;
use codex_exec_server::ExecutorFileSystem;
+use codex_exec_server::GetMetadataOptions;
+use codex_exec_server::ReadFileOptions;
use codex_protocol::protocol::Product;
use codex_skills::EnvironmentSkillMetadata;
use codex_skills::ParsedSkillFrontmatter;
@@ -326,7 +328,11 @@ async fn read_skill_contents(
skill_path: &PathUri,
) -> Result<String, String> {
file_system
- .read_file_text(skill_path, /*sandbox*/ None)
+ .read_file_text(
+ skill_path,
+ ReadFileOptions::default(),
+ /*sandbox*/ None,
+ )
.await
.map_err(|err| format!("failed to read file: {err}"))
}
@@ -336,7 +342,11 @@ async fn probe_skill_metadata(
metadata_path: &PathUri,
) -> (Option<SkillDependencies>, Option<SkillPolicy>) {
match file_system
- .get_metadata(metadata_path, /*sandbox*/ None)
+ .get_metadata(
+ metadata_path,
+ GetMetadataOptions::default(),
+ /*sandbox*/ None,
+ )
.await
{
Ok(metadata) if metadata.is_file => {}
@@ -355,7 +365,11 @@ async fn read_skill_metadata(
metadata_path: &PathUri,
) -> (Option<SkillDependencies>, Option<SkillPolicy>) {
let contents = match file_system
- .read_file_text(metadata_path, /*sandbox*/ None)
+ .read_file_text(
+ metadata_path,
+ ReadFileOptions::default(),
+ /*sandbox*/ None,
+ )
.await
{
Ok(contents) => contents,
diff --git a/codex-rs/ext/skills/src/loader/host.rs b/codex-rs/ext/skills/src/loader/host.rs
index 41b54fd6d8..bf28797a2a 100644
--- a/codex-rs/ext/skills/src/loader/host.rs
+++ b/codex-rs/ext/skills/src/loader/host.rs
@@ -2,6 +2,8 @@ use std::collections::HashMap;
use std::sync::Arc;
use codex_exec_server::ExecutorFileSystem;
+use codex_exec_server::GetMetadataOptions;
+use codex_exec_server::ReadFileOptions;
use codex_protocol::protocol::SkillScope;
use codex_skills::ParsedSkillFrontmatter;
use codex_skills::SkillError;
@@ -219,7 +221,14 @@ async fn load_skills_under_root(
);
return None;
}
- match file_system.get_metadata(&path_uri, /*sandbox*/ None).await {
+ match file_system
+ .get_metadata(
+ &path_uri,
+ GetMetadataOptions::default(),
+ /*sandbox*/ None,
+ )
+ .await
+ {
Ok(metadata) if metadata.is_file => {}
Ok(_) => {
error!(
@@ -348,7 +357,7 @@ async fn parse_skill_file(
}
.unwrap_or(SkillMetadataDiscovery::Absent);
let (contents, loaded_metadata) = tokio::join!(
- file_system.read_file_text(path_uri, /*sandbox*/ None),
+ file_system.read_file_text(path_uri, ReadFileOptions::default(), /*sandbox*/ None,),
load_host_skill_metadata(file_system, path, &metadata, plugin_root),
);
let contents = contents.map_err(|error| format!("failed to read file: {error}"))?;
diff --git a/codex-rs/ext/skills/src/loader/io_test_support.rs b/codex-rs/ext/skills/src/loader/io_test_support.rs
index 4972cffdcf..3abebbe5e6 100644
--- a/codex-rs/ext/skills/src/loader/io_test_support.rs
+++ b/codex-rs/ext/skills/src/loader/io_test_support.rs
@@ -10,10 +10,13 @@ use codex_exec_server::ExecutorFileSystemFuture;
use codex_exec_server::FileMetadata;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::FileSystemSandboxContext;
+use codex_exec_server::GetMetadataOptions;
use codex_exec_server::ReadDirectoryEntry;
+use codex_exec_server::ReadFileOptions;
use codex_exec_server::RemoveOptions;
use codex_exec_server::WalkOptions;
use codex_exec_server::WalkOutcome;
+use codex_exec_server::WriteFileOptions;
use codex_utils_path_uri::PathUri;
use tokio::sync::Notify;
use tokio::sync::Semaphore;
@@ -96,6 +99,7 @@ impl ExecutorFileSystem for RecordingFileSystem<'_> {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ options: ReadFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
self.read_files
@@ -106,7 +110,7 @@ impl ExecutorFileSystem for RecordingFileSystem<'_> {
self.skill_read_started.store(true, Ordering::Release);
self.skill_read_started_notify.notify_waiters();
}
- self.inner.read_file(path, sandbox)
+ self.inner.read_file(path, options, sandbox)
}
fn read_file_stream<'a>(
@@ -121,9 +125,10 @@ impl ExecutorFileSystem for RecordingFileSystem<'_> {
&'a self,
path: &'a PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
- self.inner.write_file(path, contents, sandbox)
+ self.inner.write_file(path, contents, options, sandbox)
}
fn create_directory<'a>(
@@ -138,6 +143,7 @@ impl ExecutorFileSystem for RecordingFileSystem<'_> {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
self.metadata_files
@@ -157,10 +163,10 @@ impl ExecutorFileSystem for RecordingFileSystem<'_> {
}
notified.await;
}
- self.inner.get_metadata(path, sandbox).await
+ self.inner.get_metadata(path, options, sandbox).await
});
}
- self.inner.get_metadata(path, sandbox)
+ self.inner.get_metadata(path, options, sandbox)
}
fn read_directory<'a>(
diff --git a/codex-rs/ext/skills/src/loader/metadata.rs b/codex-rs/ext/skills/src/loader/metadata.rs
index 030106c32e..0527b3c881 100644
--- a/codex-rs/ext/skills/src/loader/metadata.rs
+++ b/codex-rs/ext/skills/src/loader/metadata.rs
@@ -1,6 +1,8 @@
use std::io;
use codex_exec_server::ExecutorFileSystem;
+use codex_exec_server::GetMetadataOptions;
+use codex_exec_server::ReadFileOptions;
use codex_protocol::protocol::Product;
use codex_skills::SkillDependencies;
use codex_skills::SkillInterface;
@@ -86,7 +88,10 @@ pub(super) async fn load_host_skill_metadata(
SkillMetadataDiscovery::Present(path) => path,
SkillMetadataDiscovery::Absent => return LoadedSkillMetadata::default(),
SkillMetadataDiscovery::Probe(path) => {
- match file_system.get_metadata(path, /*sandbox*/ None).await {
+ match file_system
+ .get_metadata(path, GetMetadataOptions::default(), /*sandbox*/ None)
+ .await
+ {
Ok(metadata) if metadata.is_file => {}
Ok(_) => return LoadedSkillMetadata::default(),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
@@ -105,7 +110,11 @@ pub(super) async fn load_host_skill_metadata(
};
let contents = match file_system
- .read_file_text(metadata_path, /*sandbox*/ None)
+ .read_file_text(
+ metadata_path,
+ ReadFileOptions::default(),
+ /*sandbox*/ None,
+ )
.await
{
Ok(contents) => contents,
diff --git a/codex-rs/ext/skills/tests/executor_file_system_authority.rs b/codex-rs/ext/skills/tests/executor_file_system_authority.rs
index 3b9cbf7448..0f0af7cb64 100644
--- a/codex-rs/ext/skills/tests/executor_file_system_authority.rs
+++ b/codex-rs/ext/skills/tests/executor_file_system_authority.rs
@@ -21,8 +21,11 @@ use codex_exec_server::ExecutorFileSystemFuture;
use codex_exec_server::FileMetadata;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::FileSystemSandboxContext;
+use codex_exec_server::GetMetadataOptions;
use codex_exec_server::ReadDirectoryEntry;
+use codex_exec_server::ReadFileOptions;
use codex_exec_server::RemoveOptions;
+use codex_exec_server::WriteFileOptions;
use codex_protocol::capabilities::CapabilityRootLocation;
use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_protocol::models::PermissionProfile;
@@ -133,6 +136,7 @@ impl ExecutorFileSystem for SyntheticFileSystem {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ _options: ReadFileOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
Box::pin(SyntheticFileSystem::read_file(self, path))
@@ -155,6 +159,7 @@ impl ExecutorFileSystem for SyntheticFileSystem {
&'a self,
_path: &'a PathUri,
_contents: Vec<u8>,
+ _options: WriteFileOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()> {
Box::pin(async move { Err(io::Error::new(io::ErrorKind::Unsupported, "read only")) })
@@ -172,6 +177,7 @@ impl ExecutorFileSystem for SyntheticFileSystem {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ _options: GetMetadataOptions,
_sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(async move { self.metadata(path) })
diff --git a/codex-rs/file-system/src/find_up.rs b/codex-rs/file-system/src/find_up.rs
index b28ca504a6..a5a071d284 100644
--- a/codex-rs/file-system/src/find_up.rs
+++ b/codex-rs/file-system/src/find_up.rs
@@ -103,7 +103,10 @@ where
let mut results = futures::stream::iter(probes)
.map(|(ancestor, marker_path)| async move {
let marker_path = marker_path?;
- match file_system.get_metadata(&marker_path, sandbox).await {
+ match file_system
+ .get_metadata(&marker_path, crate::GetMetadataOptions::default(), sandbox)
+ .await
+ {
Ok(_) => Ok(Some(ancestor)),
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None),
Err(err) => match error_policy {
diff --git a/codex-rs/file-system/src/lib.rs b/codex-rs/file-system/src/lib.rs
index 12ab7a7f88..833e68926e 100644
--- a/codex-rs/file-system/src/lib.rs
+++ b/codex-rs/file-system/src/lib.rs
@@ -40,15 +40,56 @@ const MAX_WALK_ENTRIES: usize = 50_000;
const MAX_WALK_RESPONSE_BYTES: usize = 4 * 1024 * 1024;
const WALK_RESPONSE_ITEM_OVERHEAD_BYTES: usize = 64;
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct ReadFileOptions {
+ pub follow_symlinks: bool,
+}
+
+impl Default for ReadFileOptions {
+ fn default() -> Self {
+ Self {
+ follow_symlinks: true,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct WriteFileOptions {
+ pub follow_symlinks: bool,
+}
+
+impl Default for WriteFileOptions {
+ fn default() -> Self {
+ Self {
+ follow_symlinks: true,
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct GetMetadataOptions {
+ pub follow_symlinks: bool,
+}
+
+impl Default for GetMetadataOptions {
+ fn default() -> Self {
+ Self {
+ follow_symlinks: true,
+ }
+ }
+}
+
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CreateDirectoryOptions {
pub recursive: bool,
+ pub follow_symlinks: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RemoveOptions {
pub recursive: bool,
pub force: bool,
+ pub follow_symlinks: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -420,6 +461,7 @@ pub trait ExecutorFileSystem: Send + Sync {
fn read_file<'a>(
&'a self,
path: &'a PathUri,
+ options: ReadFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>>;
@@ -434,10 +476,11 @@ pub trait ExecutorFileSystem: Send + Sync {
fn read_file_text<'a>(
&'a self,
path: &'a PathUri,
+ options: ReadFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, String> {
Box::pin(async move {
- let bytes = self.read_file(path, sandbox).await?;
+ let bytes = self.read_file(path, options, sandbox).await?;
String::from_utf8(bytes).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
})
}
@@ -446,6 +489,7 @@ pub trait ExecutorFileSystem: Send + Sync {
&'a self,
path: &'a PathUri,
contents: Vec<u8>,
+ options: WriteFileOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, ()>;
@@ -459,6 +503,7 @@ pub trait ExecutorFileSystem: Send + Sync {
fn get_metadata<'a>(
&'a self,
path: &'a PathUri,
+ options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata>;
@@ -530,7 +575,9 @@ async fn walk_via_directory_reads<F: ExecutorFileSystem + ?Sized>(
));
}
- let root_metadata = file_system.get_metadata(root, sandbox).await?;
+ let root_metadata = file_system
+ .get_metadata(root, GetMetadataOptions::default(), sandbox)
+ .await?;
if !root_metadata.is_directory
|| (root_metadata.is_symlink && !options.follow_directory_symlinks)
{
@@ -587,7 +634,10 @@ async fn walk_via_directory_reads<F: ExecutorFileSystem + ?Sized>(
continue;
}
};
- let metadata = match file_system.get_metadata(&path, sandbox).await {
+ let metadata = match file_system
+ .get_metadata(&path, GetMetadataOptions::default(), sandbox)
+ .await
+ {
Ok(metadata) => metadata,
Err(error) => {
if !push_walk_error(&mut outcome, &mut response_bytes, path, error.to_string())
diff --git a/codex-rs/git-utils/src/trust.rs b/codex-rs/git-utils/src/trust.rs
index b5c0150017..34dfdfb244 100644
--- a/codex-rs/git-utils/src/trust.rs
+++ b/codex-rs/git-utils/src/trust.rs
@@ -15,7 +15,10 @@ pub async fn resolve_root_git_project_for_trust(
cwd: &AbsolutePathBuf,
) -> Option<AbsolutePathBuf> {
let cwd_uri = PathUri::from_abs_path(cwd);
- let base = match fs.get_metadata(&cwd_uri, /*sandbox*/ None).await {
+ let base = match fs
+ .get_metadata(&cwd_uri, Default::default(), /*sandbox*/ None)
+ .await
+ {
Ok(metadata) if metadata.is_directory => cwd.clone(),
_ => cwd.parent()?,
};
@@ -32,13 +35,18 @@ pub async fn resolve_root_git_project_for_trust(
.ok()??;
let dot_git = candidate.join(".git");
let metadata = fs
- .get_metadata(&PathUri::from_abs_path(&dot_git), /*sandbox*/ None)
+ .get_metadata(
+ &PathUri::from_abs_path(&dot_git),
+ Default::default(),
+ /*sandbox*/ None,
+ )
.await
.ok()?;
if !metadata.is_directory
|| fs
.get_metadata(
&PathUri::from_abs_path(&dot_git.join("HEAD")),
+ Default::default(),
/*sandbox*/ None,
)
.await
@@ -50,7 +58,10 @@ pub async fn resolve_root_git_project_for_trust(
};
let dot_git = repo_root.join(".git");
let dot_git_uri = PathUri::from_abs_path(&dot_git);
- let dot_git_metadata = fs.get_metadata(&dot_git_uri, /*sandbox*/ None).await.ok()?;
+ let dot_git_metadata = fs
+ .get_metadata(&dot_git_uri, Default::default(), /*sandbox*/ None)
+ .await
+ .ok()?;
if dot_git_metadata.is_directory {
return Some(repo_root);
}
@@ -63,7 +74,10 @@ pub async fn resolve_root_git_project_for_trust(
let git_dir_uri = read_gitdir_file(fs, &dot_git_uri).await?;
let git_dir_path = git_dir_uri.to_abs_path().ok()?;
- let git_dir_metadata = fs.get_metadata(&git_dir_uri, /*sandbox*/ None).await.ok()?;
+ let git_dir_metadata = fs
+ .get_metadata(&git_dir_uri, Default::default(), /*sandbox*/ None)
+ .await
+ .ok()?;
if !git_dir_metadata.is_directory || git_dir_metadata.is_symlink {
return None;
}
@@ -122,7 +136,7 @@ pub async fn resolve_root_git_project_for_trust(
let main_root = common_dir.parent()?;
let main_dot_git_uri = PathUri::from_abs_path(&main_root.join(".git"));
let main_metadata = fs
- .get_metadata(&main_dot_git_uri, /*sandbox*/ None)
+ .get_metadata(&main_dot_git_uri, Default::default(), /*sandbox*/ None)
.await
.ok()?;
let main_git_dir_uri = if main_metadata.is_directory {
@@ -152,12 +166,18 @@ async fn read_gitdir_file(fs: &dyn ExecutorFileSystem, path: &PathUri) -> Option
}
async fn read_metadata_file(fs: &dyn ExecutorFileSystem, path: &PathUri) -> Option<Vec<u8>> {
- let metadata = fs.get_metadata(path, /*sandbox*/ None).await.ok()?;
+ let metadata = fs
+ .get_metadata(path, Default::default(), /*sandbox*/ None)
+ .await
+ .ok()?;
if !metadata.is_file || metadata.is_symlink || metadata.size > MAX_GIT_METADATA_FILE_BYTES {
return None;
}
// Keep using fs/readFile for independently deployed older exec-servers.
// Their streaming fs/open API is not universally available yet.
- let bytes = fs.read_file(path, /*sandbox*/ None).await.ok()?;
+ let bytes = fs
+ .read_file(path, Default::default(), /*sandbox*/ None)
+ .await
+ .ok()?;
(bytes.len() as u64 <= MAX_GIT_METADATA_FILE_BYTES).then_some(bytes)
}
diff --git a/codex-rs/utils/plugins/src/plugin_namespace.rs b/codex-rs/utils/plugins/src/plugin_namespace.rs
index 60aa977900..4a905d4827 100644
--- a/codex-rs/utils/plugins/src/plugin_namespace.rs
+++ b/codex-rs/utils/plugins/src/plugin_namespace.rs
@@ -1,6 +1,8 @@
//! Resolve plugin namespace from skill file paths by walking ancestors for `plugin.json`.
use codex_exec_server::ExecutorFileSystem;
+use codex_exec_server::GetMetadataOptions;
+use codex_exec_server::ReadFileOptions;
use codex_exec_server_protocol::DISCOVERABLE_PLUGIN_MANIFEST_PATHS;
use codex_utils_path_uri::PathUri;
use std::path::Path;
@@ -91,7 +93,14 @@ pub async fn plugin_namespace_for_root_uri(
let mut manifest_path = None;
for relative_path in DISCOVERABLE_PLUGIN_MANIFEST_PATHS {
let candidate = plugin_root.join(relative_path).ok()?;
- match fs.get_metadata(&candidate, /*sandbox*/ None).await {
+ match fs
+ .get_metadata(
+ &candidate,
+ GetMetadataOptions::default(),
+ /*sandbox*/ None,
+ )
+ .await
+ {
Ok(metadata) if metadata.is_file => {
manifest_path = Some(candidate);
break;
@@ -100,7 +109,11 @@ pub async fn plugin_namespace_for_root_uri(
}
}
let contents = fs
- .read_file_text(&manifest_path?, /*sandbox*/ None)
+ .read_file_text(
+ &manifest_path?,
+ ReadFileOptions::default(),
+ /*sandbox*/ None,
+ )
.await
.ok()?;
let RawPluginManifestName { name: raw_name } = serde_json::from_str(&contents).ok()?;