Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Preserve Git directory protections across writable roots (#47974)

aionescu-oaia92ccbde5328
diff --git a/codex-rs/linux-sandbox/tests/suite/nested_metadata_tests.rs b/codex-rs/linux-sandbox/tests/suite/nested_metadata_tests.rs
index 74a3538198..6cd9392307 100644
--- a/codex-rs/linux-sandbox/tests/suite/nested_metadata_tests.rs
+++ b/codex-rs/linux-sandbox/tests/suite/nested_metadata_tests.rs
@@ -1,7 +1,8 @@
-//! Nested writable roots must start while preserving read-only metadata protections.
+//! Mounts for writable roots must preserve read-only metadata protections.
use super::LONG_TIMEOUT_MS;
use super::create_env_from_core_vars;
+use super::run_cmd_result_with_cwd_and_writable_roots;
use super::run_cmd_result_with_permission_profile_for_cwd;
use super::should_skip_bwrap_tests;
use codex_protocol::models::PermissionProfile;
@@ -131,3 +132,73 @@ printf nested-metadata-protected
);
}
}
+
+#[test_case::test_case(RootLayout::Directory; "direct")]
+#[test_case::test_case(RootLayout::Symlink; "alias_outside_writable_roots")]
+#[tokio::test]
+async fn workspace_write_protects_resolved_gitdir_in_another_writable_root(layout: RootLayout) {
+ if should_skip_bwrap_tests().await {
+ eprintln!("skipping bwrap test: bwrap sandbox prerequisites are unavailable");
+ return;
+ }
+
+ let temp = tempfile::tempdir().expect("tempdir");
+ // Roots at the same depth keep the workspace mount before the additional writable root.
+ let workspace = temp.path().join("workspace");
+ let writable = temp.path().join("writable");
+ let gitdir = writable.join("gitdir");
+ std::fs::create_dir(&workspace).expect("create workspace");
+ std::fs::create_dir_all(gitdir.join("hooks")).expect("create Git hooks directory");
+ let pointer_target = match layout {
+ RootLayout::Directory => gitdir.clone(),
+ RootLayout::Symlink => {
+ let aliases = temp.path().join("readonly-aliases");
+ std::fs::create_dir(&aliases).expect("create aliases directory");
+ let alias = aliases.join("repo");
+ std::os::unix::fs::symlink(&writable, &alias).expect("create gitdir alias");
+ alias.join("gitdir")
+ }
+ };
+ std::fs::write(
+ workspace.join(".git"),
+ format!("gitdir: {}\n", pointer_target.display()),
+ )
+ .expect("write Git pointer");
+ let hook = gitdir.join("hooks/pre-commit");
+ std::fs::write(&hook, "unchanged").expect("write Git hook");
+
+ let script = r#"
+set -eu
+printf allowed > "$1/allowed.txt"
+if (printf changed > "$1/gitdir/hooks/pre-commit") 2>/dev/null; then
+ exit 10
+fi
+"#;
+ let output = run_cmd_result_with_cwd_and_writable_roots(
+ &[
+ "/bin/sh",
+ "-c",
+ script,
+ "resolved-gitdir-test",
+ writable.to_str().expect("UTF-8 writable root"),
+ ],
+ &workspace,
+ std::slice::from_ref(&writable),
+ LONG_TIMEOUT_MS,
+ /*use_legacy_landlock*/ false,
+ /*network_access*/ true,
+ )
+ .await
+ .expect("sandboxed command should complete");
+
+ assert_eq!(
+ (output.exit_code, output.stdout.text, output.stderr.text),
+ (0, String::new(), String::new())
+ );
+ for (path, expected) in [
+ (writable.join("allowed.txt"), "allowed"),
+ (hook, "unchanged"),
+ ] {
+ assert_eq!(std::fs::read_to_string(path).expect("read file"), expected);
+ }
+}
diff --git a/codex-rs/protocol/src/permissions.rs b/codex-rs/protocol/src/permissions.rs
index 284cc01bb1..9059437b02 100644
--- a/codex-rs/protocol/src/permissions.rs
+++ b/codex-rs/protocol/src/permissions.rs
@@ -1555,12 +1555,54 @@ impl FileSystemSandboxPolicy {
{
return Vec::new();
}
+ // Include resolved gitdirs in the entries used to carve out broader grants.
+ // Seatbelt grants are independent, and later bubblewrap binds cover earlier mounts.
+ let include_resolved_gitdirs = match path_resolution {
+ WritableRootPathResolution::Effective => cfg!(target_os = "linux"),
+ WritableRootPathResolution::PreserveMutableComponents => cfg!(target_os = "macos"),
+ };
+ let resolved_gitdir_entries: Vec<ResolvedFileSystemEntry> = if include_resolved_gitdirs {
+ effective_entries
+ .iter()
+ .filter(|entry| entry.access.can_write())
+ .filter_map(|entry| {
+ let dot_git = path_resolution
+ .resolve(entry.path.clone())
+ .join(PROTECTED_METADATA_GIT_PATH_NAME);
+ is_git_pointer_file(&dot_git)
+ .then(|| resolve_gitdir_from_file(&dot_git))
+ .flatten()
+ })
+ .filter(|path| !has_explicit_resolved_path_entry(&resolved_entries, path))
+ .map(|path| ResolvedFileSystemEntry {
+ path,
+ access: FileSystemAccessMode::Read,
+ })
+ .collect()
+ } else {
+ Vec::new()
+ };
let prepared_entries: Vec<PreparedFileSystemEntry<'_>> = effective_entries
.into_iter()
.map(|entry| PreparedFileSystemEntry {
entry,
effective_path: path_resolution.resolve(entry.path.clone()),
})
+ .chain(resolved_gitdir_entries.iter().map(|entry| {
+ PreparedFileSystemEntry {
+ entry,
+ // Resolve the exclusion target while retaining the logical entry path.
+ effective_path: entry
+ .path
+ .as_path()
+ .canonicalize()
+ .ok()
+ .and_then(|path| AbsolutePathBuf::from_absolute_path(path).ok())
+ .unwrap_or_else(|| {
+ WritableRootPathResolution::Effective.resolve(entry.path.clone())
+ }),
+ }
+ }))
.collect();
let writable_entries: Vec<&PreparedFileSystemEntry<'_>> = prepared_entries
.iter()
@@ -2534,6 +2576,53 @@ mod tests {
std::os::unix::fs::symlink(original, link)
}
+ #[cfg(any(target_os = "linux", target_os = "macos"))]
+ #[test]
+ fn writable_roots_protect_gitdir_target_outside_alias_root() {
+ let temp = TempDir::new().expect("tempdir");
+ let base = temp.path().canonicalize().expect("canonical tempdir");
+ let workspace = base.join("workspace");
+ let writable = base.join("writable");
+ let aliases = base.join("readonly-aliases");
+ let gitdir = writable.join("gitdir");
+ fs::create_dir(&workspace).expect("create workspace");
+ fs::create_dir_all(&gitdir).expect("create gitdir");
+ fs::create_dir(&aliases).expect("create aliases");
+ let alias = aliases.join("repo");
+ symlink_dir(&writable, &alias).expect("create alias");
+ fs::write(
+ workspace.join(".git"),
+ format!("gitdir: {}\n", alias.join("gitdir").display()),
+ )
+ .expect("write Git pointer");
+ let policy = FileSystemSandboxPolicy::restricted(
+ [&workspace, &writable]
+ .into_iter()
+ .map(|path| {
+ FileSystemSandboxEntry::new(
+ AbsolutePathBuf::from_absolute_path(path)
+ .expect("absolute root")
+ .into(),
+ FileSystemAccessMode::Write,
+ )
+ })
+ .collect(),
+ );
+ let roots = if cfg!(target_os = "macos") {
+ policy.get_writable_roots_with_cwd_preserving_mutable_paths(&workspace)
+ } else {
+ policy.get_writable_roots_with_cwd(&workspace)
+ };
+ let root = roots
+ .iter()
+ .find(|root| root.root.as_path() == writable)
+ .expect("additional writable root");
+ assert_eq!(
+ root.read_only_subpaths,
+ vec![AbsolutePathBuf::from_absolute_path(gitdir).expect("absolute gitdir")],
+ );
+ }
+
#[test]
fn permission_paths_preserve_native_strings_across_path_conventions() {
for path in [
diff --git a/codex-rs/sandboxing/src/seatbelt_tests.rs b/codex-rs/sandboxing/src/seatbelt_tests.rs
index 2b952d43c0..374205440b 100644
--- a/codex-rs/sandboxing/src/seatbelt_tests.rs
+++ b/codex-rs/sandboxing/src/seatbelt_tests.rs
@@ -2741,6 +2741,69 @@ fn create_seatbelt_args_with_read_only_git_pointer_file() {
assert_seatbelt_denied(&output.stderr, &gitdir_config);
}
+#[test]
+fn workspace_write_protects_linked_worktree_gitdir_under_tmp() {
+ let tmp = TempDir::new_in("/private/tmp").expect("tempdir");
+ let worktree = tmp.path().join("worktree");
+ let gitdir = tmp.path().join("common/.git/worktrees/worktree");
+ fs::create_dir(&worktree).expect("create worktree");
+ fs::create_dir_all(&gitdir).expect("create gitdir");
+ fs::write(
+ worktree.join(".git"),
+ format!("gitdir: {}\n", gitdir.display()),
+ )
+ .expect("write .git pointer");
+ let commondir = gitdir.join("commondir");
+ fs::write(&commondir, "../..\n").expect("write commondir");
+ let allowed = tmp.path().join("allowed");
+ let policy = FileSystemSandboxPolicy::workspace_write(
+ &[],
+ /*exclude_tmpdir_env_var*/ false,
+ /*exclude_slash_tmp*/ false,
+ );
+ let args = create_seatbelt_command_args(CreateSeatbeltCommandArgsParams {
+ command: vec![
+ "/bin/sh".to_string(),
+ "-c".to_string(),
+ "printf allowed > \"$1\" && printf changed > \"$2\"".to_string(),
+ "sh".to_string(),
+ allowed.display().to_string(),
+ commondir.display().to_string(),
+ ],
+ file_system_sandbox_policy: &policy,
+ network_sandbox_policy: NetworkSandboxPolicy::Restricted,
+ sandbox_policy_cwd: &worktree,
+ enforce_managed_network: false,
+ managed_network: None,
+ environment_id: None,
+ network: None,
+ extra_allow_unix_sockets: &[],
+ })
+ .expect("create seatbelt args");
+ let output = Command::new(MACOS_PATH_TO_SEATBELT_EXECUTABLE)
+ .args(args)
+ .current_dir(&worktree)
+ .output()
+ .expect("execute seatbelt command");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ if stderr.contains("sandbox-exec: sandbox_apply: Operation not permitted") {
+ return;
+ }
+
+ assert_eq!(
+ fs::read_to_string(allowed).expect("read allowed file"),
+ "allowed"
+ );
+ assert!(
+ !output.status.success(),
+ "gitdir write succeeded: {output:?}"
+ );
+ assert_eq!(
+ fs::read_to_string(commondir).expect("read commondir"),
+ "../..\n"
+ );
+}
+
#[test]
fn create_seatbelt_args_for_cwd_as_git_repo() {
// Create a temporary workspace with two writable roots: one containing