diff --git a/codex-rs/linux-sandbox/src/bwrap.rs b/codex-rs/linux-sandbox/src/bwrap.rs index 1218496aba..bcc7dcbaa3 100644 --- a/codex-rs/linux-sandbox/src/bwrap.rs +++ b/codex-rs/linux-sandbox/src/bwrap.rs @@ -646,24 +646,63 @@ fn create_filesystem_args( .filter(|path| !unreadable_paths.contains(path)) .filter(|path| !missing_auto_metadata_read_only_project_root_subpaths.contains(path)) .collect(); - let protected_metadata_names = writable_root.protected_metadata_names.clone(); + // Remember which mounts belong to a deeper writable root without dropping + // their paths: every path must still be remapped and validated below. + let mut deferred_read_only_subpaths: Vec = read_only_subpaths + .iter() + .filter(|path| { + sorted_writable_roots.iter().any(|nested_root| { + let nested_path = nested_root.root.as_path(); + nested_path != root + && nested_path.starts_with(root) + && path.starts_with(nested_path) + && nested_root + .read_only_subpaths + .iter() + .any(|nested_subpath| nested_subpath.as_path() == path.as_path()) + }) + }) + .cloned() + .collect(); + let protected_metadata_names = &writable_root.protected_metadata_names; append_metadata_path_masks_for_writable_root( &mut read_only_subpaths, root, - &protected_metadata_names, + protected_metadata_names, ); if let Some(target) = &symlink_target { read_only_subpaths = remap_paths_for_symlink_target(read_only_subpaths, root, target); + deferred_read_only_subpaths = + remap_paths_for_symlink_target(deferred_read_only_subpaths, root, target); } append_protected_create_targets_for_writable_root( &mut bwrap_args, - &protected_metadata_names, + protected_metadata_names, root, symlink_target.as_deref(), &read_only_subpaths, ); read_only_subpaths.sort_by_key(|path| path_depth(path)); for subpath in read_only_subpaths { + if let Some(symlink) = + first_writable_symlink_component_in_path(&subpath, &allowed_write_paths) + { + /* + * A read-only carveout under a writable symlink cannot be made reliable + * with bwrap path arguments. Binding the symlink's current target would + * only protect a startup-time snapshot; the sandboxed process could + * replace the writable symlink before it reads through the logical path. + */ + return Err(CodexErr::Fatal(format!( + "cannot enforce sandbox read-only path {} because it crosses writable symlink {}", + subpath.display(), + symlink.display() + ))); + } + // Defer only the mount, after the same validation as an immediate mount. + if deferred_read_only_subpaths.contains(&subpath) { + continue; + } append_read_only_subpath_args( &mut bwrap_args, &subpath, @@ -1141,26 +1180,13 @@ fn append_mount_target_parent_dir_args(args: &mut Vec, mount_target: &Pa } } +/// Append mounts for a read-only path after writable-symlink validation. fn append_read_only_subpath_args( bwrap_args: &mut BwrapArgs, subpath: &Path, allowed_write_paths: &[PathBuf], daemon_directories: &BTreeSet, ) -> Result<()> { - if let Some(symlink) = first_writable_symlink_component_in_path(subpath, allowed_write_paths) { - /* - * A read-only carveout under a writable symlink cannot be made reliable - * with bwrap path arguments. Binding the symlink's current target would - * only protect a startup-time snapshot; the sandboxed process could - * replace the writable symlink before it reads through the logical path. - */ - return Err(CodexErr::Fatal(format!( - "cannot enforce sandbox read-only path {} because it crosses writable symlink {}", - subpath.display(), - symlink.display() - ))); - } - if let Some(metadata) = transient_empty_metadata_path(subpath) && is_within_allowed_write_paths(subpath, allowed_write_paths) { @@ -2398,23 +2424,18 @@ mod tests { let docs = AbsolutePathBuf::from_absolute_path(&docs).expect("absolute docs"); let docs_public = AbsolutePathBuf::from_absolute_path(&docs_public).expect("absolute docs/public"); - let policy = FileSystemSandboxPolicy::restricted(vec![ - FileSystemSandboxEntry { - path: writable_root.into(), - access: FileSystemAccessMode::Write, - missing_path_behavior: None, - }, - FileSystemSandboxEntry { - path: docs.clone().into(), - access: FileSystemAccessMode::Read, - missing_path_behavior: None, - }, - FileSystemSandboxEntry { - path: docs_public.clone().into(), - access: FileSystemAccessMode::Write, - missing_path_behavior: None, - }, - ]); + let mut entries = vec![ + FileSystemSandboxEntry::new(writable_root.into(), FileSystemAccessMode::Write), + FileSystemSandboxEntry::new(docs.clone().into(), FileSystemAccessMode::Read), + FileSystemSandboxEntry::new(docs_public.clone().into(), FileSystemAccessMode::Write), + ]; + for name in [".git", ".agents", ".codex"] { + entries.push(FileSystemSandboxEntry::skip_missing_path( + docs_public.join(name).into(), + FileSystemAccessMode::Read, + )); + } + let policy = FileSystemSandboxPolicy::restricted(entries); let args = create_filesystem_args(&policy, temp_dir.path(), BwrapOptions::default()) .expect("filesystem args"); @@ -2438,6 +2459,23 @@ mod tests { "expected read-only parent remount before nested writable bind: {:#?}", args.args ); + for name in [".git", ".agents", ".codex"] { + let metadata_path = path_to_string(docs_public.join(name).as_path()); + let mount_indices = args + .args + .windows(2) + .enumerate() + .filter_map(|(index, window)| { + (window == ["--tmpfs", metadata_path.as_str()]).then_some(index) + }) + .collect::>(); + assert_eq!(mount_indices.len(), 1, "one mount for {metadata_path}"); + assert!( + docs_public_rw_index < mount_indices[0], + "metadata must be mounted after its writable root: {:#?}", + args.args + ); + } } #[test] diff --git a/codex-rs/linux-sandbox/tests/suite/landlock.rs b/codex-rs/linux-sandbox/tests/suite/landlock.rs index 878a5a4493..604453ace6 100644 --- a/codex-rs/linux-sandbox/tests/suite/landlock.rs +++ b/codex-rs/linux-sandbox/tests/suite/landlock.rs @@ -28,6 +28,9 @@ use tempfile::NamedTempFile; #[path = "wslg_tests.rs"] mod wslg_tests; +#[path = "nested_metadata_tests.rs"] +mod nested_metadata_tests; + // At least on GitHub CI, the arm64 tests appear to need longer timeouts. #[cfg(not(target_arch = "aarch64"))] diff --git a/codex-rs/linux-sandbox/tests/suite/nested_metadata_tests.rs b/codex-rs/linux-sandbox/tests/suite/nested_metadata_tests.rs new file mode 100644 index 0000000000..74a3538198 --- /dev/null +++ b/codex-rs/linux-sandbox/tests/suite/nested_metadata_tests.rs @@ -0,0 +1,133 @@ +//! Nested writable roots must start while preserving read-only metadata protections. + +use super::LONG_TIMEOUT_MS; +use super::create_env_from_core_vars; +use super::run_cmd_result_with_permission_profile_for_cwd; +use super::should_skip_bwrap_tests; +use codex_protocol::models::PermissionProfile; +use codex_protocol::permissions::FileSystemAccessMode; +use codex_protocol::permissions::FileSystemPath; +use codex_protocol::permissions::FileSystemSandboxEntry; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::FileSystemSpecialPath; +use codex_protocol::permissions::NetworkSandboxPolicy; +use codex_utils_absolute_path::AbsolutePathBuf; +use pretty_assertions::assert_eq; + +enum RootLayout { + Directory, + Symlink, +} + +#[test_case::test_case(RootLayout::Directory, ""; "home_cwd")] +#[test_case::test_case(RootLayout::Directory, ".codex/visualizations/thread"; "visualization_cwd")] +#[test_case::test_case(RootLayout::Symlink, ""; "symlink_home_cwd")] +#[test_case::test_case(RootLayout::Symlink, ".codex/visualizations/thread"; "symlink_visualization_cwd")] +#[tokio::test] +async fn sandbox_starts_with_nested_writable_metadata(layout: RootLayout, relative_cwd: &str) { + if should_skip_bwrap_tests().await { + eprintln!("skipping bwrap test: bwrap sandbox prerequisites are unavailable"); + return; + } + + let temp = tempfile::tempdir().expect("tempdir"); + let home = + AbsolutePathBuf::from_absolute_path(temp.path().join("home")).expect("absolute home"); + match layout { + RootLayout::Directory => std::fs::create_dir(&home).expect("create home"), + RootLayout::Symlink => { + let target = temp.path().join("real-home"); + std::fs::create_dir(&target).expect("create real home"); + std::os::unix::fs::symlink(target, &home).expect("create home alias"); + } + } + let codex_home = home.join(".codex"); + let visualization = codex_home.join("visualizations/thread"); + std::fs::create_dir_all(&visualization).expect("create visualization directory"); + let protected_file = codex_home.join("config.toml"); + std::fs::write(&protected_file, "unchanged").expect("write protected config"); + + let mut entries = vec![ + FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::Root, + }, + FileSystemAccessMode::Read, + ), + FileSystemSandboxEntry::new(home.clone().into(), FileSystemAccessMode::Write), + FileSystemSandboxEntry::new(codex_home.clone().into(), FileSystemAccessMode::Read), + FileSystemSandboxEntry::new(visualization.clone().into(), FileSystemAccessMode::Write), + ]; + // Remote clients expand generated workspace metadata rules to concrete + // paths, including paths that do not yet exist on the executor. + for name in [".git", ".agents", ".codex"] { + entries.push(FileSystemSandboxEntry::skip_missing_path( + visualization.join(name).into(), + FileSystemAccessMode::Read, + )); + } + let permission_profile = PermissionProfile::from_runtime_permissions( + &FileSystemSandboxPolicy::restricted(entries), + NetworkSandboxPolicy::Enabled, + ); + let script = r#" +set -eu +workspace="$1" +visualization="$2" +printf home > "$workspace/allowed.txt" +printf visualization > "$visualization/allowed.txt" +if (rm "$workspace") 2>/dev/null; then + exit 13 +fi +if (printf changed > "$workspace/.codex/config.toml") 2>/dev/null; then + exit 10 +fi +if (touch "$workspace/.codex/forbidden.txt") 2>/dev/null; then + exit 11 +fi +for name in .git .agents .codex; do + test -d "$visualization/$name" + if (touch "$visualization/$name/forbidden.txt") 2>/dev/null; then + exit 12 + fi +done +printf nested-metadata-protected +"#; + let output = run_cmd_result_with_permission_profile_for_cwd( + &[ + "/bin/sh", + "-c", + script, + "nested-metadata-test", + home.to_str().expect("UTF-8 home"), + visualization + .to_str() + .expect("UTF-8 visualization directory"), + ], + home.join(relative_cwd), + permission_profile, + create_env_from_core_vars(), + LONG_TIMEOUT_MS, + /*use_legacy_landlock*/ false, + ) + .await + .expect("nested writable root should start under bubblewrap"); + + assert_eq!( + (output.exit_code, output.stdout.text, output.stderr.text), + (0, "nested-metadata-protected".to_string(), String::new()) + ); + for (path, expected) in [ + (home.join("allowed.txt"), "home"), + (visualization.join("allowed.txt"), "visualization"), + (protected_file, "unchanged"), + ] { + assert_eq!(std::fs::read_to_string(path).expect("read file"), expected); + } + for name in [".git", ".agents", ".codex"] { + assert!( + !visualization.join(name).exists(), + "temporary {name} mountpoint should be cleaned up" + ); + } +}