From 12c267d17b8223e8d6f7f57a1ce78462f6fef576 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Fri, 1 Aug 2025 11:31:24 -0700 Subject: [PATCH] feat: make .git read-only within a writable root when using Seatbelt --- codex-rs/core/src/seatbelt.rs | 36 +++-- codex-rs/core/tests/seatbelt.rs | 270 ++++++++++++++++++++++++++++++++ 2 files changed, 296 insertions(+), 10 deletions(-) create mode 100644 codex-rs/core/tests/seatbelt.rs diff --git a/codex-rs/core/src/seatbelt.rs b/codex-rs/core/src/seatbelt.rs index be2acb1bdc..db2315b95d 100644 --- a/codex-rs/core/src/seatbelt.rs +++ b/codex-rs/core/src/seatbelt.rs @@ -50,16 +50,31 @@ fn create_seatbelt_command_args( ) } else { let writable_roots = sandbox_policy.get_writable_roots_with_cwd(cwd); - let (writable_folder_policies, cli_args): (Vec, Vec) = writable_roots - .iter() - .enumerate() - .map(|(index, root)| { - let param_name = format!("WRITABLE_ROOT_{index}"); - let policy: String = format!("(subpath (param \"{param_name}\"))"); - let cli_arg = format!("-D{param_name}={}", root.to_string_lossy()); - (policy, cli_arg) - }) - .unzip(); + + let mut writable_folder_policies: Vec = Vec::new(); + let mut cli_args: Vec = Vec::new(); + + for (index, root) in writable_roots.iter().enumerate() { + // Canonicalize to avoid mismatches like /var vs /private/var on macOS. + let canonical_root = root.canonicalize().unwrap_or_else(|_| root.clone()); + let param_name = format!("WRITABLE_ROOT_{index}"); + cli_args.push(format!( + "-D{param_name}={}", + canonical_root.to_string_lossy() + )); + + let policy_component = if let SandboxPolicy::WorkspaceWrite { .. } = sandbox_policy + { + let root_str = canonical_root.to_string_lossy(); + format!( + "(require-all (subpath (param \"{param_name}\")) (require-not (regex #\"^{root_str}/(.*/)?\\\\.git(/|$)\")))" + ) + } else { + format!("(subpath (param \"{param_name}\"))") + }; + writable_folder_policies.push(policy_component); + } + if writable_folder_policies.is_empty() { ("".to_string(), Vec::::new()) } else { @@ -88,6 +103,7 @@ fn create_seatbelt_command_args( let full_policy = format!( "{MACOS_SEATBELT_BASE_POLICY}\n{file_read_policy}\n{file_write_policy}\n{network_policy}" ); + let mut seatbelt_args: Vec = vec!["-p".to_string(), full_policy]; seatbelt_args.extend(extra_cli_args); seatbelt_args.push("--".to_string()); diff --git a/codex-rs/core/tests/seatbelt.rs b/codex-rs/core/tests/seatbelt.rs new file mode 100644 index 0000000000..4426ec1f45 --- /dev/null +++ b/codex-rs/core/tests/seatbelt.rs @@ -0,0 +1,270 @@ +#![cfg(target_os = "macos")] +#![expect(clippy::unwrap_used)] + +use std::collections::HashMap; +use std::path::Path; + +use codex_core::protocol::SandboxPolicy; +use codex_core::seatbelt::spawn_command_under_seatbelt; +use codex_core::spawn::StdioPolicy; +use tempfile::TempDir; + +#[tokio::test] +async fn workspace_write_restricts_git_and_parent() { + let outer = TempDir::new().unwrap(); + let repo = outer.path().join("repo"); + std::fs::create_dir(&repo).unwrap(); + std::fs::create_dir(repo.join(".git")).unwrap(); + + assert!( + preflight_can_write(&repo).await, + "seatbelt preflight failed: sandbox unusable or policy not permitting write" + ); + + let policy = SandboxPolicy::new_workspace_write_policy(); + + assert!(touch("file", &repo, &policy).await); + assert!(repo.join("file").exists()); + + let blocked_git = repo.join(".git/blocked"); + assert!(!touch_abs(&blocked_git, &repo, &policy).await); + assert!(!repo.join(".git/blocked").exists()); + let parent_path = outer.path().join("parent"); + assert!(!touch_abs(&parent_path, &repo, &policy).await); + assert!(!outer.path().join("parent").exists()); +} + +#[tokio::test] +async fn danger_full_access_allows_git_and_parent() { + let outer = TempDir::new().unwrap(); + let repo = outer.path().join("repo"); + std::fs::create_dir(&repo).unwrap(); + std::fs::create_dir(repo.join(".git")).unwrap(); + + assert!( + preflight_can_write(&repo).await, + "seatbelt preflight failed: sandbox unusable or policy not permitting write" + ); + + let policy = SandboxPolicy::DangerFullAccess; + + assert!(touch(".git/allowed", &repo, &policy).await); + assert!(repo.join(".git/allowed").exists()); + + assert!(touch("../parent_ok", &repo, &policy).await); + assert!(outer.path().join("parent_ok").exists()); +} + +#[tokio::test] +async fn read_only_forbids_writing() { + let outer = TempDir::new().unwrap(); + let repo = outer.path().join("repo"); + std::fs::create_dir(&repo).unwrap(); + + assert!( + preflight_can_write(&repo).await, + "seatbelt preflight failed: sandbox unusable or policy not permitting write" + ); + + let policy = SandboxPolicy::ReadOnly; + + assert!(!touch("file", &repo, &policy).await); + assert!(!repo.join("file").exists()); +} + +#[tokio::test] +async fn workspace_write_allows_repo_but_blocks_sub_git_and_parent() { + let outer = TempDir::new().unwrap(); + let repo = outer.path().join("repo"); + std::fs::create_dir(&repo).unwrap(); + // Create .git at the repo root so writes under it are denied. + std::fs::create_dir(repo.join(".git")).unwrap(); + // Also create a subdirectory that looks like a nested repo to verify that + // writes to any ".git" subtree under the repo are denied. + std::fs::create_dir_all(repo.join("subdir/.git")).unwrap(); + + assert!( + preflight_can_write(&repo).await, + "seatbelt preflight failed: sandbox unusable or policy not permitting write" + ); + + let policy = SandboxPolicy::new_workspace_write_policy(); + + // Writing at repo root is allowed. + assert!(touch("ok_at_root", &repo, &policy).await); + assert!(repo.join("ok_at_root").exists()); + + // Writing in a regular subdir is allowed. + assert!(touch("subdir/ok", &repo, &policy).await); + assert!(repo.join("subdir/ok").exists()); + + // But writing anywhere under .git (root) is blocked. + let blocked_root = repo.join(".git/blocked_root"); + assert!(!touch_abs(&blocked_root, &repo, &policy).await); + assert!(!repo.join(".git/blocked_root").exists()); + + // And writing under a nested .git directory is blocked. + let blocked_nested = repo.join("subdir/.git/blocked_nested"); + assert!(!touch_abs(&blocked_nested, &repo, &policy).await); + assert!(!repo.join("subdir/.git/blocked_nested").exists()); + + // Parent of the repo must not be writable via WorkspaceWrite. + let parent_blocked = outer.path().join("parent_should_be_blocked"); + assert!(!touch_abs(&parent_blocked, &repo, &policy).await); + assert!(!outer.path().join("parent_should_be_blocked").exists()); +} + +#[tokio::test] +async fn workspace_write_allows_tmpdir() { + let repo_dir = TempDir::new().unwrap(); + let repo_path = repo_dir.path(); + // Ensure repo root exists but no actual .git required for this test. + let policy = SandboxPolicy::new_workspace_write_policy(); + + assert!( + preflight_can_write(repo_path).await, + "seatbelt preflight failed: sandbox unusable or policy not permitting write" + ); + + let tmp = std::env::temp_dir(); + // Attempt to write into the system temp dir which should be writable on macOS + // because TMPDIR is whitelisted by the WorkspaceWrite policy. + let dest = tmp.join("codex_workspace_write_tmp_test_file"); + let rel = dest.to_string_lossy().to_string(); + let mut child = spawn_command_under_seatbelt( + vec!["/usr/bin/touch".to_string(), rel], + &policy, + repo_path.to_path_buf(), + StdioPolicy::RedirectForShellTool, + HashMap::new(), + ) + .await + .unwrap(); + assert!(child.wait().await.unwrap().success()); + assert!(dest.exists()); +} + +#[tokio::test] +async fn workspace_write_extra_root_git_protected() { + let parent = TempDir::new().unwrap(); + let repo = parent.path().join("repo"); + std::fs::create_dir(&repo).unwrap(); + std::fs::create_dir(repo.join(".git")).unwrap(); + + assert!( + preflight_can_write(&repo).await, + "seatbelt preflight failed: sandbox unusable or policy not permitting write" + ); + + let other = TempDir::new().unwrap(); + let other_root = other.path().to_path_buf(); + std::fs::create_dir_all(other_root.join(".git")).unwrap(); + + let policy = SandboxPolicy::WorkspaceWrite { + writable_roots: vec![other_root.clone()], + network_access: false, + use_exact_writable_roots: true, + }; + + // Run from repo so cwd is writable and .git protected there as well. + assert!(touch("ok", &repo, &policy).await); + assert!(repo.join("ok").exists()); + let blocked_git = repo.join(".git/blocked"); + assert!(!touch_abs(&blocked_git, &repo, &policy).await); + assert!(!repo.join(".git/blocked").exists()); + + // The additional writable root should also be writable, but its .git should be blocked. + let ok_in_other = other.path().join("allowed"); + let blocked_in_other = other.path().join(".git/blocked"); + + let mut child = spawn_command_under_seatbelt( + vec![ + "/usr/bin/touch".to_string(), + ok_in_other.to_string_lossy().to_string(), + ], + &policy, + repo.clone(), + StdioPolicy::RedirectForShellTool, + HashMap::new(), + ) + .await + .unwrap(); + assert!(child.wait().await.unwrap().success()); + assert!(ok_in_other.exists()); + + let mut child = spawn_command_under_seatbelt( + vec![ + "/usr/bin/touch".to_string(), + blocked_in_other.to_string_lossy().to_string(), + ], + &policy, + repo, + StdioPolicy::RedirectForShellTool, + HashMap::new(), + ) + .await + .unwrap(); + assert!(!child.wait().await.unwrap().success()); + assert!(!blocked_in_other.exists()); +} + +fn sandbox_exec_present() -> bool { + std::path::Path::new("/usr/bin/sandbox-exec").exists() +} + +fn sandbox_exec_usable() -> bool { + if !sandbox_exec_present() { + return false; + } + match std::process::Command::new("/usr/bin/sandbox-exec") + .args(["-p", "(version 1)\n(allow default)", "--", "/usr/bin/true"]) + .status() + { + Ok(status) => status.success(), + Err(_) => false, + } +} + +async fn preflight_can_write(cwd: &Path) -> bool { + if !sandbox_exec_usable() { + return false; + } + // Verify a simple write under a standard WorkspaceWrite policy. If even this + // fails in the environment, skip the rest of the suite. + let policy = SandboxPolicy::new_workspace_write_policy(); + let probe = "__codex_seatbelt_preflight__"; + let ok = touch(probe, cwd, &policy).await; + if ok { + let _ = std::fs::remove_file(cwd.join(probe)); + } + ok +} + +async fn touch(path: &str, cwd: &Path, policy: &SandboxPolicy) -> bool { + let mut child = spawn_command_under_seatbelt( + vec!["/usr/bin/touch".to_string(), path.to_string()], + policy, + cwd.to_path_buf(), + StdioPolicy::RedirectForShellTool, + HashMap::new(), + ) + .await + .unwrap(); + child.wait().await.unwrap().success() +} + +async fn touch_abs(path: &Path, cwd: &Path, policy: &SandboxPolicy) -> bool { + let mut child = spawn_command_under_seatbelt( + vec![ + "/usr/bin/touch".to_string(), + path.to_string_lossy().to_string(), + ], + policy, + cwd.to_path_buf(), + StdioPolicy::RedirectForShellTool, + HashMap::new(), + ) + .await + .unwrap(); + child.wait().await.unwrap().success() +}