From 6dab58d9f793687f9ec1425f0cc4362b9741ba6c Mon Sep 17 00:00:00 2001 From: jif Date: Mon, 30 Nov 2026 22:21:47 +0000 Subject: [PATCH] Preserve read-only permissions across repeated thread resumes (#64829) ## Why A cold resume can save a read-only profile with concrete read paths derived from the current configuration. On the next cold resume, those paths make the saved profile ineligible for direct reuse, so the thread can fall back to a writable default. ## What changed When restoring a saved read-only profile with restricted network access that cannot be reused directly, rebuild its read grants from the current configuration while keeping writes disabled and network access restricted. Preserve read denials from both the saved profile and the current configuration. For deny globs, use the larger scan depth when both contributing policies are bounded and keep the scan unbounded if either contributing policy is unbounded. ## Testing Cover two consecutive cold resumes under a scoped writable default, and test that restoration respects the current read allowlist, preserves saved path and glob denials, merges glob scan depths, and drops the configured network proxy. GitOrigin-RevId: 04c91804e83d396402e1c8a985e4c3ff006f7e91 --- .../tests/suite/v2/thread_resume.rs | 64 +++++++----- codex-rs/core/src/config/config_tests.rs | 57 +++++++++-- codex-rs/core/src/config/mod.rs | 98 ++++++++++++------- 3 files changed, 155 insertions(+), 64 deletions(-) diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index d5097b2366..6e8fc397f4 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -2328,6 +2328,13 @@ async fn cold_resume_permission_overrides_win_over_persisted_profile() -> Result AppSandboxPolicy::ReadOnly { network_access: false }; "saved read-only wins before incompatible default validation" )] +#[cfg_attr(unix, test_case( + SandboxMode::ReadOnly, + "scoped", + "", + AppSandboxPolicy::ReadOnly { network_access: false }; + "repeated resume under scoped writable default" +))] #[tokio::test] async fn cold_resume_without_active_permission_profile_restores_base_permissions( saved_sandbox: SandboxMode, @@ -2338,8 +2345,8 @@ async fn cold_resume_without_active_permission_profile_restores_base_permissions let server = create_mock_responses_server_repeating_assistant("Done").await; let codex_home = TempDir::new()?; mock_responses_config(&server.uri()).write(codex_home.path())?; - // Only deny-read names a path on the app-server host. - let local = requirements.contains("deny_read"); + // Deny-read and scoped permissions use paths on the app-server host. + let local = requirements.contains("deny_read") || configured_default == "scoped"; let thread_id = { let mut builder = TestAppServer::builder() .with_codex_home(codex_home.path()) @@ -2376,29 +2383,40 @@ async fn cold_resume_without_active_permission_profile_restores_base_permissions thread.id }; - MockResponsesConfig::new(&server.uri()) + let mut config = MockResponsesConfig::new(&server.uri()) .with_approval_policy("on-request") - .with_root_config(&format!("default_permissions = \"{configured_default}\"")) - .write(codex_home.path())?; - std::fs::write(codex_home.path().join("requirements.toml"), requirements)?; - let mut builder = TestAppServer::builder().with_codex_home(codex_home.path()); - if local { - builder = builder.without_auto_env(); + .with_root_config(&format!("default_permissions = \"{configured_default}\"")); + if configured_default == "scoped" { + config = config.with_extra_config( + r#"[permissions.scoped.filesystem] +":minimal" = "read" +":workspace_roots" = "write" +"#, + ); + } + config.write(codex_home.path())?; + std::fs::write(codex_home.path().join("requirements.toml"), requirements)?; + for _ in 0..2 { + let mut builder = TestAppServer::builder().with_codex_home(codex_home.path()); + if local { + builder = builder.without_auto_env(); + } + let mut mcp = builder.build_initialized().await?; + let resume_id = mcp + .send_thread_resume_request(ThreadResumeParams { + thread_id: thread_id.clone(), + ..Default::default() + }) + .await?; + let response: ThreadResumeResponse = + timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??; + assert_eq!( + (&response.sandbox, response.approval_policy), + (&expected, AskForApproval::Never), + "requirements: {requirements}" + ); + timeout(DEFAULT_READ_TIMEOUT, mcp.shutdown_gracefully()).await??; } - let mut mcp = builder.build_initialized().await?; - let resume_id = mcp - .send_thread_resume_request(ThreadResumeParams { - thread_id, - ..Default::default() - }) - .await?; - let response: ThreadResumeResponse = - timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??; - assert_eq!( - (response.sandbox, response.approval_policy), - (expected, AskForApproval::Never), - "requirements: {requirements}" - ); Ok(()) } diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index d7938af6a9..1a9eff1133 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -100,6 +100,7 @@ use codex_protocol::permissions::FileSystemSandboxEntry; use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::FileSystemSpecialPath; use codex_protocol::permissions::NetworkSandboxPolicy; +use codex_protocol::permissions::ReadDenyMatcher; use codex_protocol::protocol::MultiAgentVersion; use codex_protocol::protocol::SandboxPolicy; use codex_protocol_test_support::ContentItemTestExt; @@ -2978,27 +2979,57 @@ async fn permission_profile_override_populates_runtime_permissions() -> std::io: Ok(()) } +#[test_case::test_case(false, None, "", None; "canonical")] +#[test_case::test_case(true, None, "", None; "materialized")] +#[test_case::test_case(true, Some(8), "glob_scan_max_depth = 2\n'~/**/*.key' = 'deny'", Some(8); "saved glob depth wins")] +#[test_case::test_case(true, Some(2), "glob_scan_max_depth = 8\n'~/**/*.key' = 'deny'", Some(8); "configured glob depth wins")] +#[test_case::test_case(true, None, "glob_scan_max_depth = 2\n'~/**/*.key' = 'deny'", None; "saved globs stay unbounded")] +#[test_case::test_case(true, Some(8), "'~/**/*.key' = 'deny'", None; "configured globs stay unbounded")] +#[test_case::test_case(true, Some(8), "", Some(8); "saved depth survives absent configured globs")] +#[test_case::test_case(true, Some(8), "glob_scan_max_depth = 2", Some(8); "ignore depth without configured globs")] #[tokio::test] -async fn persisted_read_only_respects_read_allowlist_and_drops_default_proxy() -> anyhow::Result<()> -{ +async fn persisted_read_only_respects_read_allowlist_and_drops_default_proxy( + materialized: bool, + saved_glob_depth: Option, + configured_filesystem: &str, + expected_glob_depth: Option, +) -> anyhow::Result<()> { let codex_home = TempDir::new()?; let cwd = TempDir::new()?; - let config_toml = toml::from_str( + let private = cwd.abs().join("private"); + let saved = if materialized { + let mut file_system = FileSystemSandboxPolicy::restricted(vec![ + FileSystemSandboxEntry::new(codex_home.abs().into(), FileSystemAccessMode::Read), + FileSystemSandboxEntry::new(private.clone().into(), FileSystemAccessMode::Deny), + FileSystemSandboxEntry::new( + FileSystemPath::GlobPattern { + pattern: format!("{}/**/.env", cwd.path().display()), + }, + FileSystemAccessMode::Deny, + ), + ]); + file_system.glob_scan_max_depth = saved_glob_depth; + PermissionProfile::from_runtime_permissions(&file_system, NetworkSandboxPolicy::Restricted) + } else { + PermissionProfile::read_only() + }; + let config_toml = toml::from_str(&format!( r#" default_permissions = "dev" [permissions.dev.filesystem] ":workspace_roots" = "write" +{configured_filesystem} [permissions.dev.network] enabled = true "#, - )?; + ))?; let config = Config::load_from_base_config_with_overrides( config_toml, ConfigOverrides { cwd: Some(cwd.path().to_path_buf()), - persisted_permission_profile: Some(PermissionProfile::read_only()), + persisted_permission_profile: Some(saved), ..Default::default() }, codex_home.abs(), @@ -3009,14 +3040,28 @@ enabled = true .effective_permission_profile() .to_runtime_permissions(); let cwd = cwd.path(); + let denied_reads = + ReadDenyMatcher::try_new_for_local_paths(&file_system, cwd).map_err(anyhow::Error::msg)?; assert_eq!( ( file_system.can_read_local_path_with_cwd(cwd, cwd), file_system.can_write_local_path_with_cwd(cwd, cwd), file_system.can_read_local_path_with_cwd(codex_home.path(), cwd), + file_system.can_read_local_path_with_cwd(private.as_path(), cwd), + denied_reads + .is_some_and(|matcher| matcher.is_local_path_read_denied(&cwd.join("a/b/c/.env"))), + file_system.glob_scan_max_depth, network, ), - (true, false, false, NetworkSandboxPolicy::Restricted) + ( + true, + false, + false, + !materialized, + materialized, + expected_glob_depth, + NetworkSandboxPolicy::Restricted + ) ); assert!(config.permissions.network.is_none()); Ok(()) diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index f85bff7a7d..85647daf79 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -136,6 +136,7 @@ use codex_protocol::openai_models::ModelsResponse; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::permissions::DenyReadValidator; use codex_protocol::permissions::DenyReadViolation; +use codex_protocol::permissions::FileSystemAccessMode; use codex_protocol::permissions::FileSystemPath; use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::FileSystemSandboxPolicyContext; @@ -3834,10 +3835,30 @@ impl Config { && permission_profile.is_none() && default_permissions_override.is_none() && persisted_permission_profile_id.is_none(); - let persisted_read_only = restore_persisted_profile - && persisted_permission_profile - .as_ref() - .is_some_and(|profile| *profile == PermissionProfile::read_only()); + let persisted_permission_profile = + persisted_permission_profile.filter(|_| restore_persisted_profile); + let can_reuse_saved_profile = persisted_permission_profile.as_ref().is_some_and(|profile| { + requirements_toml.allowed_permission_profiles.is_none() + && !matches!(profile, PermissionProfile::External { .. }) + && !profile.file_system_sandbox_policy().entries.iter().any(|entry| { + entry.access.can_read() + && matches!(entry.path, FileSystemPath::Path { .. } | FileSystemPath::GlobPattern { .. }) + }) + && permission_profile_catalog::permission_profile_satisfies_requirements( + &config_layer_stack, + profile, + ) + }); + // A checkpoint can contain concrete reads from a previous read-only recovery. + // When those grants cannot be reused, derive reads from today's configuration + // while keeping the saved restriction on writes and network access. + let persisted_read_only = persisted_permission_profile.as_ref().is_some_and(|profile| { + *profile == PermissionProfile::read_only() + || (!can_reuse_saved_profile + && sandbox_mode_requirement_for_permission_profile(profile) + == SandboxModeRequirement::ReadOnly + && profile.network_sandbox_policy() == NetworkSandboxPolicy::Restricted) + }); if persisted_read_only && !permission_profile_is_allowed( &config_layer_stack, @@ -3850,21 +3871,8 @@ impl Config { "The saved read-only permission profile is disallowed by requirements. Select a permission profile explicitly to continue.", )); } - let persisted_permission_profile = persisted_permission_profile.filter(|profile| { - restore_persisted_profile - && (persisted_read_only || requirements_toml.allowed_permission_profiles.is_none()) - // Executor-owned enforcement and materialized grants are not portable - // thread defaults. Reject the original mode before preserving denials. - && !matches!(profile, PermissionProfile::External { .. }) - && !profile.file_system_sandbox_policy().entries.iter().any(|entry| { - entry.access.can_read() - && matches!(entry.path, FileSystemPath::Path { .. } | FileSystemPath::GlobPattern { .. }) - }) - && permission_profile_catalog::permission_profile_satisfies_requirements( - &config_layer_stack, - profile, - ) - }); + let persisted_permission_profile = persisted_permission_profile + .filter(|_| can_reuse_saved_profile || persisted_read_only); let persisted_permission_profile_id = if sandbox_mode.is_some() || permission_profile.is_some() || default_permissions_override.is_some() @@ -4130,23 +4138,43 @@ impl Config { ) }; if let Some(saved) = persisted_permission_profile { - // Canonical read-only recovery can remove writes without replacing a - // narrower read allowlist from the current configuration. - let saved = if persisted_read_only - && (!file_system_sandbox_policy.has_full_disk_read_access() - || matches!(permission_profile, PermissionProfile::External { .. })) - { - permission_profile.intersect_with_read_only().ok_or_else(|| { - std::io::Error::new( - std::io::ErrorKind::InvalidInput, - "Could not restore the saved read-only permission profile under external enforcement. Select a permission profile explicitly to continue.", - ) - })? - } else { - saved - }; let (mut saved_file_system, saved_network) = saved.to_runtime_permissions(); - saved_file_system.preserve_deny_read_restrictions_from(&file_system_sandbox_policy); + if persisted_read_only { + let read_only = if file_system_sandbox_policy.has_full_disk_read_access() + && !matches!(permission_profile, PermissionProfile::External { .. }) + { + PermissionProfile::read_only() + } else { + permission_profile.intersect_with_read_only().ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "Could not restore the saved read-only permission profile under external enforcement. Select a permission profile explicitly to continue.", + ) + })? + }; + // Only policies with deny globs contribute a scan depth. An + // unbounded scan must stay unbounded; bounded scans use the larger depth. + let glob_scan_max_depth = [&saved_file_system, &file_system_sandbox_policy] + .into_iter() + .filter(|policy| { + policy.entries.iter().any(|entry| { + entry.access == FileSystemAccessMode::Deny + && matches!(entry.path, FileSystemPath::GlobPattern { .. }) + }) + }) + .map(|policy| policy.glob_scan_max_depth) + .reduce(|saved, configured| { + saved.zip(configured).map(|(saved, configured)| saved.max(configured)) + }) + .flatten(); + let mut reads = read_only.file_system_sandbox_policy(); + reads.preserve_deny_read_restrictions_from(&saved_file_system); + reads.preserve_deny_read_restrictions_from(&file_system_sandbox_policy); + reads.glob_scan_max_depth = glob_scan_max_depth; + saved_file_system = reads; + } else { + saved_file_system.preserve_deny_read_restrictions_from(&file_system_sandbox_policy); + } let restored = PermissionProfile::from_runtime_permissions_with_enforcement( saved.enforcement(), &saved_file_system,