fix(sandbox): preserve symlinked project config

Co-authored-by: Codex noreply@openai.com
This commit is contained in:
viyatb-oai
2026-06-08 22:19:01 -07:00
co-authored by Codex noreply@openai.com
parent fa73ec83f3
commit b32bd8d514
20 changed files with 171 additions and 495 deletions
-2
View File
@@ -2845,7 +2845,6 @@ dependencies = [
"codex-shell-command",
"codex-test-binary-support",
"codex-utils-absolute-path",
"codex-utils-path",
"codex-utils-pty",
"codex-utils-rustls-provider",
"ctor 0.6.3",
@@ -4149,7 +4148,6 @@ version = "0.0.0"
dependencies = [
"codex-utils-absolute-path",
"dunce",
"libc",
"pretty_assertions",
"tempfile",
]
+7 -49
View File
@@ -1206,17 +1206,12 @@ async fn load_project_layers(
let mut startup_warnings = Vec::new();
for dir in dirs {
let dot_codex_abs = dir.join(".codex");
let Ok(dot_codex_metadata) = fs.get_metadata(&dot_codex_abs, /*sandbox*/ None).await else {
continue;
};
if dot_codex_metadata.is_symlink {
let dot_codex_display = dot_codex_abs.as_path().display();
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Project config directory {dot_codex_display} must not be a symlink"),
));
}
if !dot_codex_metadata.is_directory {
if !fs
.get_metadata(&dot_codex_abs, /*sandbox*/ None)
.await
.map(|metadata| metadata.is_directory)
.unwrap_or(false)
{
continue;
}
@@ -1229,44 +1224,7 @@ async fn load_project_layers(
continue;
}
let config_file = dot_codex_abs.join(CONFIG_TOML_FILE);
let config_file_for_read = fs
.canonicalize(&dir, /*sandbox*/ None)
.await
.map_err(|err| {
let dir_display = dir.as_path().display();
io::Error::new(
err.kind(),
format!("Failed to resolve project directory {dir_display}: {err}"),
)
})?
.join(".codex")
.join(CONFIG_TOML_FILE);
match fs.get_metadata(&config_file, /*sandbox*/ None).await {
Ok(metadata) => {
if metadata.is_symlink {
let config_file_display = config_file.as_path().display();
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("Project config file {config_file_display} must not be a symlink"),
));
}
}
Err(err) => {
if err.kind() != io::ErrorKind::NotFound {
let config_file_display = config_file.as_path().display();
return Err(io::Error::new(
err.kind(),
format!(
"Failed to inspect project config file {config_file_display}: {err}"
),
));
}
}
}
match fs
.read_file_text_no_follow(&config_file_for_read, /*sandbox*/ None)
.await
{
match fs.read_file_text(&config_file, /*sandbox*/ None).await {
Ok(contents) => {
let config: TomlValue = match toml::from_str(&contents) {
Ok(config) => config,
-21
View File
@@ -10,8 +10,6 @@ use codex_file_system::RemoveOptions;
use pretty_assertions::assert_eq;
use std::path::Path;
use tempfile::tempdir;
#[cfg(unix)]
use tokio::io::AsyncReadExt;
struct TestFileSystem;
@@ -45,25 +43,6 @@ impl ExecutorFileSystem for TestFileSystem {
tokio::fs::read(path.as_path()).await
}
async fn read_file_no_follow(
&self,
path: &AbsolutePathBuf,
_sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>> {
#[cfg(unix)]
{
let file = codex_utils_path::open_file_for_read_no_follow(path.as_path())?;
let mut file = tokio::fs::File::from_std(file);
let mut contents = Vec::new();
file.read_to_end(&mut contents).await?;
Ok(contents)
}
#[cfg(not(unix))]
{
self.read_file(path, /*sandbox*/ None).await
}
}
async fn write_file(
&self,
_path: &AbsolutePathBuf,
+32 -79
View File
@@ -3027,6 +3027,37 @@ wire_api = "responses"
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn symlinked_project_config_is_loaded() -> std::io::Result<()> {
let tmp = tempdir()?;
let project_root = tmp.path().join("project");
let dot_codex = project_root.join(".codex");
let codex_home = tmp.path().join("home");
let config_target = project_root.join("project-config.toml");
tokio::fs::create_dir_all(&dot_codex).await?;
tokio::fs::create_dir_all(&codex_home).await?;
tokio::fs::write(project_root.join(".git"), "gitdir: here").await?;
tokio::fs::write(&config_target, "model = \"symlink-model\"\n").await?;
symlink("../project-config.toml", dot_codex.join(CONFIG_TOML_FILE))?;
make_config_for_test(
&codex_home,
&project_root,
TrustLevel::Trusted,
/*project_root_markers*/ None,
)
.await?;
let config = ConfigBuilder::default()
.codex_home(codex_home)
.fallback_cwd(Some(project_root))
.build()
.await?;
assert_eq!(config.model.as_deref(), Some("symlink-model"));
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn project_trust_does_not_match_configured_alias_for_canonical_cwd() -> std::io::Result<()> {
@@ -3264,84 +3295,6 @@ async fn invalid_project_config_ignored_when_untrusted_or_unknown() -> std::io::
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn symlinked_project_config_is_rejected() -> std::io::Result<()> {
let tmp = tempdir()?;
let project_root = tmp.path().join("project");
let dot_codex = project_root.join(".codex");
let codex_home = tmp.path().join("home");
let payload = project_root.join("payload.toml");
tokio::fs::create_dir_all(&dot_codex).await?;
tokio::fs::create_dir_all(&codex_home).await?;
tokio::fs::write(project_root.join(".git"), "gitdir: here").await?;
tokio::fs::write(&payload, "sandbox_mode = \"danger-full-access\"\n").await?;
symlink(&payload, dot_codex.join(CONFIG_TOML_FILE)).expect("create config symlink");
make_config_for_test(
&codex_home,
&project_root,
TrustLevel::Trusted,
/*project_root_markers*/ None,
)
.await?;
let err = ConfigBuilder::default()
.codex_home(codex_home)
.fallback_cwd(Some(project_root))
.build()
.await
.expect_err("symlinked project config should fail");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
assert!(
err.to_string().contains("must not be a symlink"),
"unexpected error: {err}"
);
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn symlinked_project_config_directory_is_rejected() -> std::io::Result<()> {
let tmp = tempdir()?;
let project_root = tmp.path().join("project");
let codex_home = tmp.path().join("home");
let payload_dir = tmp.path().join("payload");
tokio::fs::create_dir_all(&project_root).await?;
tokio::fs::create_dir_all(&codex_home).await?;
tokio::fs::create_dir_all(&payload_dir).await?;
tokio::fs::write(project_root.join(".git"), "gitdir: here").await?;
tokio::fs::write(
payload_dir.join(CONFIG_TOML_FILE),
"sandbox_mode = \"danger-full-access\"\n",
)
.await?;
symlink(&payload_dir, project_root.join(".codex")).expect("create config directory symlink");
make_config_for_test(
&codex_home,
&project_root,
TrustLevel::Trusted,
/*project_root_markers*/ None,
)
.await?;
let err = ConfigBuilder::default()
.codex_home(codex_home)
.fallback_cwd(Some(project_root))
.build()
.await
.expect_err("symlinked project config directory should fail");
assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
assert!(
err.to_string().contains("must not be a symlink"),
"unexpected error: {err}"
);
Ok(())
}
#[tokio::test]
async fn project_layer_without_config_toml_is_disabled_when_untrusted_or_unknown()
-> std::io::Result<()> {
@@ -3471,7 +3424,7 @@ async fn project_root_markers_supports_alternate_markers() -> std::io::Result<()
&codex_home,
&project_root,
TrustLevel::Trusted,
/*project_root_markers*/ Some(vec![".hg".to_string()]),
Some(vec![".hg".to_string()]),
)
.await?;
-1
View File
@@ -24,7 +24,6 @@ codex-protocol = { workspace = true }
codex-sandboxing = { workspace = true }
codex-shell-command = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-path = { workspace = true }
codex-utils-pty = { workspace = true }
codex-utils-rustls-provider = { workspace = true }
futures = { workspace = true }
@@ -236,14 +236,6 @@ mod tests {
Ok(b"skill contents".to_vec())
}
async fn read_file_no_follow(
&self,
path: &AbsolutePathBuf,
sandbox: Option<&FileSystemSandboxContext>,
) -> io::Result<Vec<u8>> {
self.read_file(path, sandbox).await
}
async fn write_file(
&self,
_path: &AbsolutePathBuf,
+4 -8
View File
@@ -189,14 +189,10 @@ pub(crate) async fn run_direct_request(
let file_system = DirectFileSystem;
match request {
FsHelperRequest::ReadFile(params) => {
let data = if params.no_follow_symlinks {
file_system
.read_file_no_follow(&params.path, /*sandbox*/ None)
.await
} else {
file_system.read_file(&params.path, /*sandbox*/ None).await
}
.map_err(map_fs_error)?;
let data = file_system
.read_file(&params.path, /*sandbox*/ None)
.await
.map_err(map_fs_error)?;
Ok(FsHelperPayload::ReadFile(FsReadFileResponse {
data_base64: STANDARD.encode(data),
}))
@@ -7,8 +7,6 @@ use std::sync::LazyLock;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tokio::io;
#[cfg(unix)]
use tokio::io::AsyncReadExt;
use crate::CopyOptions;
use crate::CreateDirectoryOptions;
@@ -111,15 +109,6 @@ impl ExecutorFileSystem for LocalFileSystem {
file_system.read_file(path, sandbox).await
}
async fn read_file_no_follow(
&self,
path: &AbsolutePathBuf,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>> {
let (file_system, sandbox) = self.file_system_for(sandbox)?;
file_system.read_file_no_follow(path, sandbox).await
}
async fn write_file(
&self,
path: &AbsolutePathBuf,
@@ -214,17 +203,6 @@ impl ExecutorFileSystem for UnsandboxedFileSystem {
self.file_system.read_file(path, /*sandbox*/ None).await
}
async fn read_file_no_follow(
&self,
path: &AbsolutePathBuf,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>> {
reject_platform_sandbox_context(sandbox)?;
self.file_system
.read_file_no_follow(path, /*sandbox*/ None)
.await
}
async fn write_file(
&self,
path: &AbsolutePathBuf,
@@ -339,33 +317,6 @@ impl ExecutorFileSystem for DirectFileSystem {
tokio::fs::read(path.as_path()).await
}
async fn read_file_no_follow(
&self,
path: &AbsolutePathBuf,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>> {
reject_sandbox_context(sandbox)?;
#[cfg(unix)]
{
let file = codex_utils_path::open_file_for_read_no_follow(path.as_path())?;
let metadata = file.metadata()?;
if metadata.len() > MAX_READ_FILE_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("file is too large to read: limit is {MAX_READ_FILE_BYTES} bytes"),
));
}
let mut file = tokio::fs::File::from_std(file);
let mut contents = Vec::new();
file.read_to_end(&mut contents).await?;
Ok(contents)
}
#[cfg(not(unix))]
{
self.read_file(path, /*sandbox*/ None).await
}
}
async fn write_file(
&self,
path: &AbsolutePathBuf,
-3
View File
@@ -183,9 +183,6 @@ pub struct TerminateResponse {
pub struct FsReadFileParams {
pub path: AbsolutePathBuf,
pub sandbox: Option<FileSystemSandboxContext>,
/// Reject symlinks in every path component on Unix executors.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub no_follow_symlinks: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -98,30 +98,6 @@ impl ExecutorFileSystem for RemoteFileSystem {
.fs_read_file(FsReadFileParams {
path: path.clone(),
sandbox: remote_sandbox_context(sandbox),
no_follow_symlinks: false,
})
.await
.map_err(map_remote_error)?;
STANDARD.decode(response.data_base64).map_err(|err| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("remote fs/readFile returned invalid base64 dataBase64: {err}"),
)
})
}
async fn read_file_no_follow(
&self,
path: &AbsolutePathBuf,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>> {
trace!("remote fs read_file_no_follow");
let client = self.client.get().await.map_err(map_remote_error)?;
let response = client
.fs_read_file(FsReadFileParams {
path: path.clone(),
sandbox: remote_sandbox_context(sandbox),
no_follow_symlinks: true,
})
.await
.map_err(map_remote_error)?;
@@ -97,33 +97,6 @@ impl ExecutorFileSystem for SandboxedFileSystem {
FsHelperRequest::ReadFile(FsReadFileParams {
path: path.clone(),
sandbox: None,
no_follow_symlinks: false,
}),
)
.await?
.expect_read_file()
.map_err(map_sandbox_error)?;
STANDARD.decode(response.data_base64).map_err(|err| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("fs/readFile returned invalid base64 dataBase64: {err}"),
)
})
}
async fn read_file_no_follow(
&self,
path: &AbsolutePathBuf,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>> {
let sandbox = require_platform_sandbox(sandbox)?;
let response = self
.run_sandboxed(
sandbox,
FsHelperRequest::ReadFile(FsReadFileParams {
path: path.clone(),
sandbox: None,
no_follow_symlinks: true,
}),
)
.await?
@@ -52,16 +52,11 @@ impl FileSystemHandler {
&self,
params: FsReadFileParams,
) -> Result<FsReadFileResponse, JSONRPCErrorError> {
let bytes = if params.no_follow_symlinks {
self.file_system
.read_file_no_follow(&params.path, params.sandbox.as_ref())
.await
} else {
self.file_system
.read_file(&params.path, params.sandbox.as_ref())
.await
}
.map_err(map_fs_error)?;
let bytes = self
.file_system
.read_file(&params.path, params.sandbox.as_ref())
.await
.map_err(map_fs_error)?;
Ok(FsReadFileResponse {
data_base64: STANDARD.encode(bytes),
})
@@ -274,7 +269,6 @@ mod tests {
sandbox_policy,
sandbox_cwd.clone(),
)),
no_follow_symlinks: false,
})
.await
.expect("read file");
-35
View File
@@ -735,41 +735,6 @@ async fn file_system_sandboxed_read_rejects_symlink_escape(use_remote: bool) ->
Ok(())
}
#[test_case(false ; "local")]
#[test_case(true ; "remote")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn file_system_read_file_no_follow_rejects_symlinked_parent(use_remote: bool) -> Result<()> {
let context = create_file_system_context(use_remote).await?;
let file_system = context.file_system;
let tmp = TempDir::new()?;
let tmp = tmp.path().canonicalize()?;
let target_dir = tmp.join("target");
let symlinked_dir = tmp.join("link");
std::fs::create_dir(&target_dir)?;
let target_path = target_dir.join("payload");
std::fs::write(&target_path, "original")?;
symlink(&target_dir, &symlinked_dir)?;
let contents = file_system
.read_file_no_follow(&absolute_path(target_path), /*sandbox*/ None)
.await
.with_context(|| format!("mode={use_remote}"))?;
assert_eq!(contents, b"original");
if let Ok(contents) = file_system
.read_file_no_follow(
&absolute_path(symlinked_dir.join("payload")),
/*sandbox*/ None,
)
.await
{
anyhow::bail!("symlinked parent should fail, but read {contents:?}");
}
Ok(())
}
#[test_case(false ; "local")]
#[test_case(true ; "remote")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-19
View File
@@ -156,15 +156,6 @@ pub trait ExecutorFileSystem: Send + Sync {
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>>;
/// Reads a file while rejecting symlinks in any path component on Unix.
///
/// Non-Unix executors currently fall back to [`Self::read_file`].
async fn read_file_no_follow(
&self,
path: &AbsolutePathBuf,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<Vec<u8>>;
/// Reads a file and decodes it as UTF-8 text.
async fn read_file_text(
&self,
@@ -175,16 +166,6 @@ pub trait ExecutorFileSystem: Send + Sync {
String::from_utf8(bytes).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
}
/// Reads a file with [`Self::read_file_no_follow`] and decodes it as UTF-8 text.
async fn read_file_text_no_follow(
&self,
path: &AbsolutePathBuf,
sandbox: Option<&FileSystemSandboxContext>,
) -> FileSystemResult<String> {
let bytes = self.read_file_no_follow(path, sandbox).await?;
String::from_utf8(bytes).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
}
async fn write_file(
&self,
path: &AbsolutePathBuf,
+122 -8
View File
@@ -593,8 +593,15 @@ fn create_filesystem_args(
&read_only_subpaths,
);
read_only_subpaths.sort_by_key(|path| path_depth(path));
let mut enforced_read_only_subpaths = Vec::new();
for subpath in read_only_subpaths {
append_read_only_subpath_args(&mut bwrap_args, &subpath, &allowed_write_paths)?;
append_read_only_subpath_args(
&mut bwrap_args,
&subpath,
&allowed_write_paths,
&enforced_read_only_subpaths,
)?;
enforced_read_only_subpaths.push(subpath);
}
let mut nested_unreadable_roots: Vec<PathBuf> = unreadable_roots
.iter()
@@ -1022,8 +1029,15 @@ fn append_read_only_subpath_args(
bwrap_args: &mut BwrapArgs,
subpath: &Path,
allowed_write_paths: &[PathBuf],
enforced_read_only_subpaths: &[PathBuf],
) -> Result<()> {
if let Some(symlink) = first_writable_symlink_component_in_path(subpath, allowed_write_paths) {
if let Some(symlink) = first_writable_symlink_component_in_path(subpath, allowed_write_paths)
&& !read_only_ancestor_stabilizes_symlink_target(
&symlink,
allowed_write_paths,
enforced_read_only_subpaths,
)
{
/*
* A read-only carveout under a writable symlink cannot be made reliable
* with bwrap path arguments. Binding the symlink's current target would
@@ -1071,6 +1085,36 @@ fn append_read_only_subpath_args(
Ok(())
}
/// Returns whether an already-enforced read-only ancestor prevents `symlink`
/// from being retargeted and its current target path contains no other writable
/// symlink components.
fn read_only_ancestor_stabilizes_symlink_target(
symlink: &Path,
allowed_write_paths: &[PathBuf],
enforced_read_only_subpaths: &[PathBuf],
) -> bool {
if !enforced_read_only_subpaths.iter().any(|read_only_path| {
symlink.starts_with(read_only_path)
&& is_within_allowed_write_paths(read_only_path, allowed_write_paths)
}) {
return false;
}
let Ok(target) = fs::read_link(symlink) else {
return false;
};
let target = if target.is_absolute() {
target
} else {
symlink
.parent()
.map_or(target.clone(), |parent| parent.join(target))
};
target.exists()
&& first_writable_symlink_component_in_path(&target, allowed_write_paths).is_none()
}
fn append_empty_file_bind_data_args(bwrap_args: &mut BwrapArgs, path: &Path) -> Result<()> {
if bwrap_args.preserved_files.is_empty() {
bwrap_args.preserved_files.push(File::open("/dev/null")?);
@@ -2226,7 +2270,7 @@ mod tests {
#[cfg(unix)]
#[test]
fn split_policy_rejects_symlinked_project_config_file() {
fn split_policy_protects_symlinked_project_config_file() {
let temp_dir = TempDir::new().expect("temp dir");
let writable_root = temp_dir.path().join("workspace");
let dot_codex = writable_root.join(".codex");
@@ -2237,6 +2281,7 @@ mod tests {
std::os::unix::fs::symlink(&payload, &config).expect("create config symlink");
let writable_root =
AbsolutePathBuf::from_absolute_path(&writable_root).expect("absolute writable root");
let dot_codex_str = path_to_string(&dot_codex);
let config_str = path_to_string(&config);
let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::Path {
@@ -2245,16 +2290,85 @@ mod tests {
access: FileSystemAccessMode::Write,
}]);
let args =
create_filesystem_args(&policy, temp_dir.path(), NO_UNREADABLE_GLOB_SCAN_MAX_DEPTH)
.expect("filesystem args");
let dot_codex_position = args
.args
.windows(3)
.position(|window| {
window == ["--ro-bind", dot_codex_str.as_str(), dot_codex_str.as_str()]
})
.expect(".codex should be remounted read-only");
let config_position = args
.args
.windows(3)
.position(|window| window == ["--ro-bind", config_str.as_str(), config_str.as_str()])
.expect("config target should be remounted read-only");
assert!(dot_codex_position < config_position);
}
#[cfg(unix)]
#[test]
fn split_policy_rejects_project_config_target_through_writable_symlink() {
let temp_dir = TempDir::new().expect("temp dir");
let writable_root = temp_dir.path().join("workspace");
let dot_codex = writable_root.join(".codex");
let payload = writable_root.join("payload.toml");
let mutable_link = writable_root.join("mutable-link.toml");
let config = dot_codex.join("config.toml");
std::fs::create_dir_all(&dot_codex).expect("create .codex");
std::fs::write(&payload, "sandbox_mode = \"danger-full-access\"").expect("write payload");
std::os::unix::fs::symlink(&payload, &mutable_link).expect("create mutable symlink");
std::os::unix::fs::symlink("../mutable-link.toml", &config).expect("create config symlink");
let writable_root =
AbsolutePathBuf::from_absolute_path(&writable_root).expect("absolute writable root");
let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: writable_root,
},
access: FileSystemAccessMode::Write,
}]);
let err =
create_filesystem_args(&policy, temp_dir.path(), NO_UNREADABLE_GLOB_SCAN_MAX_DEPTH)
.expect_err("symlinked config should fail closed");
let message = err.to_string();
.expect_err("mutable target symlink should fail closed");
assert!(
message.contains("cannot enforce sandbox read-only path"),
"{message}"
err.to_string()
.contains("cannot enforce sandbox read-only path"),
"{err}"
);
}
#[cfg(unix)]
#[test]
fn split_policy_rejects_dangling_project_config_symlink() {
let temp_dir = TempDir::new().expect("temp dir");
let writable_root = temp_dir.path().join("workspace");
let dot_codex = writable_root.join(".codex");
let config = dot_codex.join("config.toml");
std::fs::create_dir_all(&dot_codex).expect("create .codex");
std::os::unix::fs::symlink("../missing.toml", &config).expect("create config symlink");
let writable_root =
AbsolutePathBuf::from_absolute_path(&writable_root).expect("absolute writable root");
let policy = FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: writable_root,
},
access: FileSystemAccessMode::Write,
}]);
let err =
create_filesystem_args(&policy, temp_dir.path(), NO_UNREADABLE_GLOB_SCAN_MAX_DEPTH)
.expect_err("dangling config symlink should fail closed");
assert!(
err.to_string()
.contains("cannot enforce sandbox read-only path"),
"{err}"
);
assert!(message.contains(&config_str), "{message}");
}
#[test]
-10
View File
@@ -4425,7 +4425,6 @@ mod tests {
let cwd = TempDir::new().expect("tempdir");
std::fs::create_dir_all(cwd.path().join(".agents")).expect("create .agents");
std::fs::create_dir_all(cwd.path().join(".codex")).expect("create .codex");
std::fs::write(cwd.path().join(".codex/config.toml"), "").expect("create config.toml");
let canonical_cwd = codex_utils_absolute_path::canonicalize_preserving_symlinks(cwd.path())
.expect("canonicalize cwd");
let cwd_absolute =
@@ -4437,9 +4436,6 @@ mod tests {
.expect("canonical .agents");
let expected_codex = AbsolutePathBuf::from_absolute_path(canonical_cwd.join(".codex"))
.expect("canonical .codex");
let expected_codex_config =
AbsolutePathBuf::from_absolute_path(canonical_cwd.join(".codex/config.toml"))
.expect("canonical .codex/config.toml");
let policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry {
path: FileSystemPath::Special {
@@ -4492,12 +4488,6 @@ mod tests {
.iter()
.any(|path| path.as_path() == expected_codex.as_path())
);
assert!(
writable_roots[0]
.read_only_subpaths
.iter()
.any(|path| path.as_path() == expected_codex_config.as_path())
);
}
#[test]
+1 -6
View File
@@ -887,8 +887,7 @@ fn create_seatbelt_args_with_read_only_git_and_codex_subpaths() {
);
assert!(
policy_text.contains("WRITABLE_ROOT_1_EXCLUDED_0")
&& policy_text.contains("WRITABLE_ROOT_1_EXCLUDED_1")
&& policy_text.contains("WRITABLE_ROOT_1_EXCLUDED_2"),
&& policy_text.contains("WRITABLE_ROOT_1_EXCLUDED_1"),
"expected explicit writable root .git/.codex carveouts in policy:\n{policy_text}",
);
assert!(
@@ -950,10 +949,6 @@ fn create_seatbelt_args_with_read_only_git_and_codex_subpaths() {
"-DWRITABLE_ROOT_1_EXCLUDED_1={}",
dot_codex_canonical.to_string_lossy()
),
format!(
"-DWRITABLE_ROOT_1_EXCLUDED_2={}",
dot_codex_canonical.join("config.toml").display()
),
format!(
"-DWRITABLE_ROOT_2={}",
empty_root_canonical.to_string_lossy()
-3
View File
@@ -12,9 +12,6 @@ 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 }
-83
View File
@@ -5,19 +5,7 @@ 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;
@@ -144,77 +132,6 @@ pub fn write_atomically(write_path: &Path, contents: &str) -> io::Result<()> {
Ok(())
}
/// Opens a file for reading without following symlinks in any path component.
///
/// Relative paths are resolved from the process's current directory.
#[cfg(unix)]
pub fn open_file_for_read_no_follow(path: &Path) -> 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,
libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
/*mode*/ 0,
)
}
#[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,9 +1,7 @@
#[cfg(unix)]
mod symlinks {
use super::super::open_file_for_read_no_follow;
use super::super::resolve_symlink_write_paths;
use pretty_assertions::assert_eq;
use std::io::Read;
use std::os::unix::fs::symlink;
#[test]
@@ -21,53 +19,6 @@ mod symlinks {
assert_eq!(resolved.write_path, a);
Ok(())
}
#[test]
fn no_follow_read_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"), "secret")?;
symlink(&target_dir, &symlinked_dir)?;
let err = open_file_for_read_no_follow(&symlinked_dir.join("payload"))
.expect_err("symlinked parent should fail");
assert!(err.raw_os_error().is_some());
Ok(())
}
#[test]
fn no_follow_read_rejects_symlinked_file() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let dir = dir.path().canonicalize()?;
let target = dir.join("target");
let symlink_path = dir.join("link");
std::fs::write(&target, "secret")?;
symlink(&target, &symlink_path)?;
let err =
open_file_for_read_no_follow(&symlink_path).expect_err("symlinked file should fail");
assert_eq!(err.raw_os_error(), Some(libc::ELOOP));
Ok(())
}
#[test]
fn no_follow_read_reads_regular_file() -> std::io::Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().canonicalize()?.join("payload");
std::fs::write(&path, "hello")?;
let mut reader = open_file_for_read_no_follow(&path)?;
let mut contents = String::new();
reader.read_to_string(&mut contents)?;
assert_eq!(contents, "hello");
Ok(())
}
}
#[cfg(target_os = "linux")]