fix: reject symlinked output-last-message paths

Co-authored-by: Codex noreply@openai.com
This commit is contained in:
viyatb-oai
2026-06-04 00:07:58 -07:00
co-authored by Codex noreply@openai.com
parent ad2012d645
commit 808ea21a5d
7 changed files with 210 additions and 1 deletions
+2
View File
@@ -2751,6 +2751,7 @@ dependencies = [
"codex-utils-cargo-bin",
"codex-utils-cli",
"codex-utils-oss",
"codex-utils-path",
"codex-utils-sandbox-summary",
"core_test_support",
"libc",
@@ -4088,6 +4089,7 @@ version = "0.0.0"
dependencies = [
"codex-utils-absolute-path",
"dunce",
"libc",
"pretty_assertions",
"tempfile",
]
+1
View File
@@ -39,6 +39,7 @@ codex-protocol = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-cli = { workspace = true }
codex-utils-oss = { workspace = true }
codex-utils-path = { workspace = true }
codex-utils-sandbox-summary = { workspace = true }
owo-colors = { workspace = true }
serde = { workspace = true, features = ["derive"] }
+18 -1
View File
@@ -1,3 +1,5 @@
#[cfg(unix)]
use std::io::Write;
use std::path::Path;
use codex_app_server_protocol::ServerNotification;
@@ -41,8 +43,23 @@ pub(crate) fn handle_last_message(last_agent_message: Option<&str>, output_file:
fn write_last_message_file(contents: &str, last_message_path: Option<&Path>) {
if let Some(path) = last_message_path
&& let Err(e) = std::fs::write(path, contents)
&& let Err(e) = write_last_message_to_path(path, contents)
{
eprintln!("Failed to write last message file {path:?}: {e}");
}
}
#[cfg(unix)]
fn write_last_message_to_path(path: &Path, contents: &str) -> std::io::Result<()> {
let mut file = codex_utils_path::open_file_for_write_no_follow(path)?;
file.write_all(contents.as_bytes())
}
#[cfg(not(unix))]
fn write_last_message_to_path(path: &Path, contents: &str) -> std::io::Result<()> {
std::fs::write(path, contents)
}
#[cfg(test)]
#[path = "event_processor_tests.rs"]
mod tests;
@@ -0,0 +1,60 @@
use super::write_last_message_to_path;
use pretty_assertions::assert_eq;
use tempfile::tempdir;
#[test]
fn writes_last_message_to_regular_file() {
let temp_dir = tempdir().expect("tempdir");
let output_path = temp_dir
.path()
.canonicalize()
.expect("canonical tempdir")
.join("output.md");
write_last_message_to_path(&output_path, "hello").expect("write output");
assert_eq!(
std::fs::read_to_string(&output_path).expect("read output"),
"hello"
);
}
#[cfg(unix)]
#[test]
fn rejects_symlinked_last_message_path() {
let temp_dir = tempdir().expect("tempdir");
let temp_dir = temp_dir.path().canonicalize().expect("canonical tempdir");
let target_path = temp_dir.join("target.md");
let output_path = temp_dir.join("output.md");
std::fs::write(&target_path, "original").expect("write target");
std::os::unix::fs::symlink(&target_path, &output_path).expect("create symlink");
let err = write_last_message_to_path(&output_path, "hello").expect_err("symlink should fail");
assert_eq!(err.raw_os_error(), Some(libc::ELOOP));
assert_eq!(
std::fs::read_to_string(&target_path).expect("read target"),
"original"
);
}
#[cfg(unix)]
#[test]
fn rejects_symlinked_last_message_parent_directory() {
let temp_dir = tempdir().expect("tempdir");
let temp_dir = temp_dir.path().canonicalize().expect("canonical tempdir");
let target_dir = temp_dir.join("target");
let symlinked_dir = temp_dir.join("link");
std::fs::create_dir(&target_dir).expect("create target directory");
let target_path = target_dir.join("output.md");
std::fs::write(&target_path, "original").expect("write target");
std::os::unix::fs::symlink(&target_dir, &symlinked_dir).expect("create symlink");
write_last_message_to_path(&symlinked_dir.join("output.md"), "hello")
.expect_err("symlinked parent should fail");
assert_eq!(
std::fs::read_to_string(&target_path).expect("read target"),
"original"
);
}
+3
View File
@@ -12,6 +12,9 @@ codex-utils-absolute-path = { workspace = true }
dunce = { workspace = true }
tempfile = { workspace = true }
[target.'cfg(unix)'.dependencies]
libc = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
tempfile = { workspace = true }
+90
View File
@@ -5,7 +5,19 @@ pub use env::is_wsl;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::collections::HashSet;
#[cfg(unix)]
use std::ffi::CString;
#[cfg(unix)]
use std::fs::File;
use std::io;
#[cfg(unix)]
use std::os::fd::AsRawFd;
#[cfg(unix)]
use std::os::fd::FromRawFd;
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
#[cfg(unix)]
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use tempfile::NamedTempFile;
@@ -132,6 +144,84 @@ pub fn write_atomically(write_path: &Path, contents: &str) -> io::Result<()> {
Ok(())
}
/// Opens a file for writing without following symlinks in any path component.
#[cfg(unix)]
pub fn open_file_for_write_no_follow(path: &Path) -> io::Result<File> {
open_file_no_follow(
path,
libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC,
/*mode*/ 0o666,
)
}
#[cfg(unix)]
fn open_file_no_follow(path: &Path, flags: libc::c_int, mode: libc::mode_t) -> io::Result<File> {
let components = path
.components()
.filter_map(|component| match component {
Component::RootDir | Component::CurDir => None,
Component::ParentDir => Some(Ok(std::ffi::OsStr::new(".."))),
Component::Normal(component) => Some(Ok(component)),
Component::Prefix(_) => Some(Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("unsupported path prefix in {}", path.display()),
))),
})
.collect::<io::Result<Vec<_>>>()?;
let Some((file_name, parent_components)) = components.split_last() else {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("path {} does not name a file", path.display()),
));
};
let mut current_dir = if path.is_absolute() {
File::open("/")?
} else {
File::open(".")?
};
for component in parent_components {
current_dir = openat(
&current_dir,
component,
libc::O_RDONLY | libc::O_CLOEXEC | libc::O_DIRECTORY | libc::O_NOFOLLOW,
/*mode*/ 0,
)?;
}
openat(
&current_dir,
file_name,
flags | libc::O_CLOEXEC | libc::O_NOFOLLOW,
mode,
)
}
#[cfg(unix)]
fn openat(
directory: &File,
path: &std::ffi::OsStr,
flags: libc::c_int,
mode: libc::mode_t,
) -> io::Result<File> {
let path = CString::new(path.as_bytes())
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
// SAFETY: `path` is NUL-terminated, `directory` owns a valid fd, and the
// returned fd is transferred into a `File` exactly once.
let fd = unsafe {
libc::openat(
directory.as_raw_fd(),
path.as_ptr(),
flags,
libc::c_uint::from(mode),
)
};
if fd == -1 {
return Err(io::Error::last_os_error());
}
// SAFETY: `openat` returned a new owned file descriptor.
Ok(unsafe { File::from_raw_fd(fd) })
}
fn normalize_for_wsl(path: PathBuf) -> PathBuf {
normalize_for_wsl_with_flag(path, env::is_wsl())
}
@@ -1,7 +1,9 @@
#[cfg(unix)]
mod symlinks {
use super::super::open_file_for_write_no_follow;
use super::super::resolve_symlink_write_paths;
use pretty_assertions::assert_eq;
use std::io::Write;
use std::os::unix::fs::symlink;
#[test]
@@ -19,6 +21,40 @@ mod symlinks {
assert_eq!(resolved.write_path, a);
Ok(())
}
#[test]
fn no_follow_write_rejects_symlinked_parent_directory() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let dir = dir.path().canonicalize()?;
let target_dir = dir.join("target");
let symlinked_dir = dir.join("link");
std::fs::create_dir(&target_dir)?;
std::fs::write(target_dir.join("payload"), "original")?;
symlink(&target_dir, &symlinked_dir)?;
let err = open_file_for_write_no_follow(&symlinked_dir.join("payload"))
.expect_err("symlinked parent should fail");
assert!(err.raw_os_error().is_some());
assert_eq!(
std::fs::read_to_string(target_dir.join("payload"))?,
"original"
);
Ok(())
}
#[test]
fn no_follow_write_writes_regular_file() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().canonicalize()?.join("payload");
let mut writer = open_file_for_write_no_follow(&path)?;
writer.write_all(b"hello")?;
drop(writer);
assert_eq!(std::fs::read_to_string(&path)?, "hello");
Ok(())
}
}
#[cfg(target_os = "linux")]