Lightweight coding agent that runs in your terminal
Rust
Resolve permission profiles with explicit execution-host path context (#44676)
Sean Huang9e22e74e8dca
diff --git a/codex-rs/app-server/src/request_processors/catalog_processor.rs b/codex-rs/app-server/src/request_processors/catalog_processor.rsindex 0b2178ea92..ac2ed55997 100644--- a/codex-rs/app-server/src/request_processors/catalog_processor.rs+++ b/codex-rs/app-server/src/request_processors/catalog_processor.rs@@ -1,6 +1,10 @@use super::*;+use codex_config::ConfigPathContext;use codex_core::config::permission_profile_catalog;use codex_hooks::HookListEntryHandler;+use codex_utils_absolute_path::AbsolutePathBufGuard;+use codex_utils_path_uri::PathConvention;+use codex_utils_path_uri::PathUri;use futures::StreamExt;#[derive(Clone)]@@ -413,22 +417,26 @@ impl CatalogRequestProcessor {params: PermissionProfileListParams,) -> Result<PermissionProfileListResponse, JSONRPCErrorError> {let PermissionProfileListParams { cursor, limit, cwd } = params;- let config_layer_stack = match cwd {- Some(cwd) => {- let cwd = PathBuf::from(cwd);- let (_, config_layer_stack) = self- .resolve_cwd_config(&cwd)- .await- .map_err(|err| internal_error(format!("failed to reload config: {err}")))?;- config_layer_stack- }- None => self- .config_manager- .load_config_layers(/*cwd*/ None)+ let (cwd, config_layer_stack) = match cwd {+ Some(cwd) => self+ .resolve_cwd_config(&PathBuf::from(cwd)).await.map_err(|err| internal_error(format!("failed to reload config: {err}")))?,+ None => (+ self.config.cwd.clone(),+ self.config_manager+ .load_config_layers(/*cwd*/ None)+ .await+ .map_err(|err| internal_error(format!("failed to reload config: {err}")))?,+ ),};- let profiles = permission_profile_catalog(&config_layer_stack)+ let context = ConfigPathContext::new(+ PathConvention::native(),+ Some(PathUri::from_abs_path(&cwd)),+ AbsolutePathBufGuard::home_directory()+ .and_then(|home| PathUri::from_host_native_path(home).ok()),+ );+ let profiles = permission_profile_catalog(&config_layer_stack, &context).map_err(|err| internal_error(format!("failed to resolve permission profiles: {err}")))?.into_iter().map(|profile| PermissionProfileSummary {diff --git a/codex-rs/app-server/tests/suite/v2/permission_profile_list.rs b/codex-rs/app-server/tests/suite/v2/permission_profile_list.rsindex 791fc2a73f..e6c1c48d44 100644--- a/codex-rs/app-server/tests/suite/v2/permission_profile_list.rs+++ b/codex-rs/app-server/tests/suite/v2/permission_profile_list.rs@@ -239,6 +239,56 @@ description = "Project-scoped profile."Ok(())}+#[tokio::test]+async fn permission_profile_list_resolves_roots_against_requested_cwd() -> Result<()> {+ let codex_home = TempDir::new()?;+ let workspace = TempDir::new()?;+ let unsafe_cwd = workspace.path().join("[workspace]");+ std::fs::create_dir_all(&unsafe_cwd)?;+ std::fs::write(+ codex_home.path().join("config.toml"),+ r#"+default_permissions = ":workspace"++[permissions.scoped.workspace_roots]+"private/*.env" = true++[permissions.scoped.filesystem]+":workspace_roots" = "write"+"#,+ )?;+ let mut mcp = TestAppServer::builder()+ .with_codex_home(codex_home.path())+ .without_auto_env()+ .build_initialized_with_timeout(DEFAULT_TIMEOUT)+ .await?;++ for (cwd, allowed) in [(unsafe_cwd.as_path(), false), (workspace.path(), true)] {+ let request_id = mcp+ .send_permission_profile_list_request(PermissionProfileListParams {+ cursor: None,+ limit: None,+ cwd: Some(cwd.to_string_lossy().into_owned()),+ })+ .await?;+ let response = read_response::<PermissionProfileListResponse>(&mut mcp, request_id).await?;+ assert_eq!(+ response+ .data+ .into_iter()+ .find(|profile| profile.id == "scoped"),+ Some(PermissionProfileSummary {+ id: "scoped".to_string(),+ description: None,+ allowed,+ }),+ "cwd={}",+ cwd.display(),+ );+ }+ Ok(())+}+async fn read_response<T: serde::de::DeserializeOwned>(mcp: &mut TestAppServer,request_id: i64,diff --git a/codex-rs/config/src/config_requirements.rs b/codex-rs/config/src/config_requirements.rsindex 60aaa455b5..821bbaef2a 100644--- a/codex-rs/config/src/config_requirements.rs+++ b/codex-rs/config/src/config_requirements.rs@@ -716,6 +716,7 @@ impl FilesystemDenyReadPattern {.map_err(|error| error.to_string())?;if !input.chars().any(is_glob_metacharacter) {let path = deserialize_absolute_path(input)?;+ validate_literal_denial_path(&path)?;return Ok(Self(path));}@@ -736,6 +737,9 @@ impl FilesystemDenyReadPattern {} else {deserialize_absolute_path(directory_prefix)?};+ // The prefix is literal even when supplied home/base facts contain+ // glob syntax. Reject it before appending the user's pattern suffix.+ validate_literal_denial_path(&normalized_prefix)?;let normalized = if suffix.is_empty() {normalized_prefix} else if normalized_prefix == "/" {@@ -768,6 +772,14 @@ impl<'de> Deserialize<'de> for FilesystemDenyReadPattern {}}+fn validate_literal_denial_path(path: &str) -> Result<(), String> {+ let convention = crate::path_context::convention();+ codex_utils_path_uri::LegacyAppPathString::from_string(path)+ .to_path_uri(convention)+ .and_then(|path| path.validate_glob_directory(convention))+ .map_err(|error| error.to_string())+}+fn deserialize_absolute_path(input: &str) -> Result<String, String> {crate::path_context::resolve(input)}diff --git a/codex-rs/config/src/path_context.rs b/codex-rs/config/src/path_context.rsindex e30477f081..e570e8a339 100644--- a/codex-rs/config/src/path_context.rs+++ b/codex-rs/config/src/path_context.rs@@ -1,12 +1,13 @@-//! Path facts for filesystem denial parsing. Native callers and callers resolving+//! Path facts for configuration parsing. Native callers and callers resolving//! another platform use the same resolver after fact capture.use codex_utils_absolute_path::AbsolutePathBufGuard;+use codex_utils_path_uri::LegacyAppPathStringError;use codex_utils_path_uri::PathConvention;use codex_utils_path_uri::PathUri;use std::cell::RefCell;-/// The owning environment's path convention, base directory, and home for denials.+/// The owning environment's path convention, base directory, and home for configuration.#[derive(Clone, Debug)]pub struct ConfigPathContext {convention: PathConvention,@@ -29,6 +30,35 @@ impl ConfigPathContext {}}+ /// Returns the path grammar supplied by the owning environment.+ pub fn convention(&self) -> PathConvention {+ self.convention+ }++ /// Resolves configuration text to a URI using the supplied directory and home facts.+ pub fn resolve_path(&self, input: &str) -> Result<PathUri, LegacyAppPathStringError> {+ PathUri::resolve_config_path_uri(+ input,+ self.convention,+ self.base_dir.as_ref(),+ self.user_home_dir.as_ref(),+ )+ }++ /// Resolves against a supplied base using this context's grammar and home.+ pub fn resolve_against(+ &self,+ input: &str,+ base: &PathUri,+ ) -> Result<PathUri, LegacyAppPathStringError> {+ PathUri::resolve_config_path_uri(+ input,+ self.convention,+ Some(base),+ self.user_home_dir.as_ref(),+ )+ }+pub(crate) fn enter(&self) -> PathContextGuard {PathContextGuard(PATH_CONTEXT.with(|current| current.replace(Some(self.clone()))))}@@ -74,13 +104,10 @@ pub(crate) fn resolve(input: &str) -> Result<String, String> {ConfigPathContext::new(convention, base, home)}};- PathUri::resolve_config_path(- input,- context.convention,- context.base_dir.as_ref(),- context.user_home_dir.as_ref(),- )- .map_err(|error| error.to_string())+ context+ .resolve_path(input)+ .and_then(|path| path.to_config_path_string(context.convention()))+ .map_err(|error| error.to_string())}#[cfg(test)]diff --git a/codex-rs/config/src/path_context_tests.rs b/codex-rs/config/src/path_context_tests.rsindex ec82ab89d9..cd78522e52 100644--- a/codex-rs/config/src/path_context_tests.rs+++ b/codex-rs/config/src/path_context_tests.rs@@ -202,3 +202,54 @@ fn missing_supplied_home_does_not_fall_back_to_native_home() {assert!(compose_requirements_for_hostname([layer], /*hostname*/ None).is_err());});}++#[test]+fn denial_resolution_rejects_glob_syntax_in_supplied_facts() {+ for directory in ["file:///home/sam[1]", "file:///C:/Users/sam[1]"] {+ let directory = PathUri::parse(directory).unwrap();+ let context = ConfigPathContext::new(+ directory.infer_path_convention().unwrap(),+ Some(directory.clone()),+ Some(directory),+ );+ // Literal denials also reject metacharacters introduced by path facts.+ for input in [+ "private/*.key",+ "~/private/*.key",+ "private/key",+ "~/private/key",+ ] {+ let layer = RequirementsLayerEntry::from_toml(+ RequirementSource::Unknown,+ format!("[permissions.filesystem]\ndeny_read = ['{input}']"),+ )+ .with_path_context(context.clone());+ assert!(compose_requirements_for_hostname([layer], /*hostname*/ None).is_err());+ }+ }+}++#[test]+fn native_and_supplied_denials_reject_the_same_unsafe_facts() {+ let parent = tempdir().unwrap();+ let directory = parent.path().join("sam[1]");+ let _base_guard = AbsolutePathBufGuard::new(&directory);+ AbsolutePathBufGuard::with_home_directory(&directory, || {+ let inputs = [+ "private/*.key",+ "~/private/*.key",+ "private/key",+ "~/private/key",+ ];+ let native = inputs.map(FilesystemDenyReadPattern::from_input);+ assert!(native.iter().all(Result::is_err));+ let directory = PathUri::from_host_native_path(&directory).unwrap();+ let context = ConfigPathContext::new(+ PathConvention::native(),+ Some(directory.clone()),+ Some(directory),+ );+ let _context_guard = context.enter();+ assert_eq!(inputs.map(FilesystemDenyReadPattern::from_input), native);+ });+}diff --git a/codex-rs/core/src/config/config_loader_tests.rs b/codex-rs/core/src/config/config_loader_tests.rsindex 4bdbfa8a07..f09c2f6cc2 100644--- a/codex-rs/core/src/config/config_loader_tests.rs+++ b/codex-rs/core/src/config/config_loader_tests.rs@@ -11,6 +11,7 @@ use codex_config::ConfigLayerEntry;use codex_config::ConfigLayerSource;use codex_config::ConfigLoadError;use codex_config::ConfigLoadOptions;+use codex_config::ConfigPathContext;use codex_config::ConfigRequirements;use codex_config::ConfigRequirementsToml;use codex_config::ConfigRequirementsWithSources;@@ -41,6 +42,8 @@ use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;use codex_protocol::models::PermissionProfile;use codex_protocol::protocol::AskForApproval;use codex_utils_absolute_path::AbsolutePathBuf;+use codex_utils_path_uri::PathConvention;+use codex_utils_path_uri::PathUri;use pretty_assertions::assert_eq;use std::collections::BTreeMap;use std::collections::HashMap;@@ -2511,7 +2514,14 @@ extends = ":workspace".await?;assert_eq!(- permission_profile_catalog(&config.config_layer_stack)?,+ permission_profile_catalog(+ &config.config_layer_stack,+ &ConfigPathContext::new(+ PathConvention::native(),+ Some(PathUri::from_abs_path(&cwd)),+ /*user_home_dir*/ None,+ ),+ )?,vec![PermissionProfileCatalogEntry {id: ":read-only".to_string(),diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rsindex 71dcff72b7..efcd531899 100644--- a/codex-rs/core/src/config/mod.rs+++ b/codex-rs/core/src/config/mod.rs@@ -12,6 +12,7 @@ use codex_agent_roles::load_agent_roles;use codex_config::CloudConfigBundleLoader;use codex_config::ConfigLayerSource;use codex_config::ConfigLayerStack;+use codex_config::ConfigPathContext;use codex_config::ConfigRequirements;use codex_config::ConfigRequirementsToml;use codex_config::ConstrainedWithSource;@@ -129,6 +130,7 @@ use codex_rmcp_client::McpOAuthRefreshMode;pub use codex_thread_store::ExtraConfig;use codex_utils_absolute_path::AbsolutePathBuf;use codex_utils_absolute_path::AbsolutePathBufGuard;+use codex_utils_path_uri::PathConvention;use codex_utils_path_uri::PathUri;use http::HeaderValue;use rmcp::model::ElicitationCapability;@@ -149,9 +151,6 @@ use std::time::Duration;use crate::config::permissions::BUILT_IN_READ_ONLY_PROFILE;use crate::config::permissions::BUILT_IN_WORKSPACE_PROFILE;use crate::config::permissions::apply_network_proxy_feature_config;-use crate::config::permissions::builtin_permission_profile;-use crate::config::permissions::compile_permission_profile_selection;-use crate::config::permissions::compile_permission_profile_workspace_roots;use crate::config::permissions::default_builtin_permission_profile_name;use crate::config::permissions::get_readable_roots_required_for_codex_runtime;use crate::config::permissions::network_proxy_config_for_profile_selection;@@ -167,6 +166,7 @@ mod managed_features;mod metrics;mod network_proxy_spec;mod otel;+mod permission_path;mod permission_profile_catalog;mod permission_profile_selection;mod permissions;@@ -197,6 +197,8 @@ use permission_profile_catalog::permission_profile_is_allowed;use permission_profile_catalog::validate_permission_profile_for_deny_read;pub use permission_profile_selection::ResolvedPermissionProfileSelection;pub use permission_profile_selection::resolve_permission_profile_selection;+pub use permissions::CompiledPermissionProfile;+pub use permissions::WorkspaceWriteSettings;pub use permissions::compile_permission_profile;pub(crate) use permissions::is_builtin_permission_profile_name;pub use permissions::resolve_permission_profile;@@ -3384,10 +3386,16 @@ impl Config {} else {persisted_permission_profile_id.as_deref()};+ let permission_path_context = ConfigPathContext::new(+ PathConvention::native(),+ Some(PathUri::from_abs_path(&resolved_cwd)),+ AbsolutePathBufGuard::home_directory()+ .and_then(|home| PathUri::from_host_native_path(home).ok()),+ );let effective_permission_selection = resolve_effective_permission_selection(cfg.permissions.as_ref(),default_permissions_override.as_deref(),- persisted_permission_profile_id,+ persisted_permission_profile_id.map(|profile_id| (profile_id, &permission_path_context)),cfg.default_permissions.as_deref(),requirements_toml,&mut startup_warnings,@@ -3423,6 +3431,7 @@ impl Config {let custom_permission_profiles = permission_profile_catalog_from_permissions(&config_layer_stack,effective_permission_selection.profiles.as_ref(),+ &permission_path_context,)?.into_iter().filter(|profile| !is_builtin_permission_profile_name(&profile.id))@@ -3507,7 +3516,12 @@ impl Config {default_builtin_permission_profile_name(&active_project, windows_sandbox_level)});let builtin_workspace_write_settings = if using_implicit_builtin_profile {- cfg.sandbox_workspace_write.as_ref()+ cfg.sandbox_workspace_write.as_ref().map(|settings| WorkspaceWriteSettings {+ writable_roots: settings.writable_roots.iter().map(PathUri::from_abs_path).collect(),+ network_access: settings.network_access,+ exclude_tmpdir_env_var: settings.exclude_tmpdir_env_var,+ exclude_slash_tmp: settings.exclude_slash_tmp,+ })} else {None};@@ -3515,37 +3529,21 @@ impl Config {effective_permission_selection.profiles.as_ref(),default_permissions,)?;- let (mut file_system_sandbox_policy, network_sandbox_policy) =- compile_permission_profile_selection(- effective_permission_selection.profiles.as_ref(),- default_permissions,- builtin_workspace_write_settings,- &mut startup_warnings,- )?;- let mut configured_workspace_roots = compile_permission_profile_workspace_roots(+ let CompiledPermissionProfile {+ permission_profile,+ workspace_roots: configured_workspace_roots,+ } = compile_permission_profile(effective_permission_selection.profiles.as_ref(),default_permissions,- resolved_cwd.as_path(),+ &permission_path_context,+ builtin_workspace_write_settings.as_ref(),+ &mut startup_warnings,)?;- if using_implicit_builtin_profile- && default_permissions == BUILT_IN_WORKSPACE_PROFILE- && let Some(sandbox_workspace_write) = cfg.sandbox_workspace_write.as_ref()- {- configured_workspace_roots.extend(sandbox_workspace_write.writable_roots.clone());- }- dedupe_absolute_paths(&mut configured_workspace_roots);- file_system_sandbox_policy = file_system_sandbox_policy- .with_materialized_project_roots_for_workspace_roots(&configured_workspace_roots);- let permission_profile = if let Some(permission_profile) =- builtin_permission_profile(default_permissions, builtin_workspace_write_settings)- {- permission_profile- } else {- PermissionProfile::from_runtime_permissions(- &file_system_sandbox_policy,- network_sandbox_policy,- )- };+ let file_system_sandbox_policy = permission_profile.file_system_sandbox_policy();+ let configured_workspace_roots = configured_workspace_roots+ .iter()+ .map(PathUri::to_abs_path)+ .collect::<std::io::Result<Vec<_>>>()?;let active_permission_profile = if using_implicit_builtin_profile&& default_permissions == BUILT_IN_WORKSPACE_PROFILE&& cfg.sandbox_workspace_write.is_some()@@ -4620,7 +4618,7 @@ fn merge_managed_permission_profiles(fn resolve_effective_permission_selection<'a>(configured_profiles: Option<&PermissionsToml>,default_permissions_override: Option<&'a str>,- persisted_profile_id: Option<&'a str>,+ persisted_profile_id: Option<(&'a str, &ConfigPathContext)>,configured_default_profile_id: Option<&'a str>,requirements_toml: &'a ConfigRequirementsToml,startup_warnings: &mut Vec<String>,@@ -4628,17 +4626,16 @@ fn resolve_effective_permission_selection<'a>(let profiles = merge_managed_permission_profiles(configured_profiles, requirements_toml)?;validate_user_permission_profile_names(profiles.as_ref())?;validate_required_permission_profile_catalog(requirements_toml, profiles.as_ref())?;- let valid_persisted_profile_id = persisted_profile_id.filter(|profile_id| {- is_builtin_permission_profile_name(profile_id)- || profiles.as_ref().is_some_and(|profiles| {- compile_permission_profile_selection(- Some(profiles),- profile_id,- /*workspace_write*/ None,- &mut Vec::new(),- )- .is_ok()- })+ let valid_persisted_profile_id = persisted_profile_id.and_then(|(profile_id, context)| {+ compile_permission_profile(+ profiles.as_ref(),+ profile_id,+ context,+ /*workspace_write*/ None,+ &mut Vec::new(),+ )+ .is_ok()+ .then_some(profile_id)});let selected_profile_id = resolve_default_permissions(default_permissions_override.or(valid_persisted_profile_id),diff --git a/codex-rs/core/src/config/permission_path.rs b/codex-rs/core/src/config/permission_path.rsnew file mode 100644index 0000000000..0e36c20fd2--- /dev/null+++ b/codex-rs/core/src/config/permission_path.rs@@ -0,0 +1,75 @@+//! Permission-profile path grammar. Path facts and resolution are owned by+//! the shared configuration context; symbolic paths preserve native spelling.++use std::io;++use codex_config::ConfigPathContext;+use codex_utils_absolute_path::normalize_windows_device_path;+use codex_utils_path_uri::LegacyAppPathString;+use codex_utils_path_uri::PathConvention;+use codex_utils_path_uri::PathUri;++pub(super) fn contains_glob(path: &str, context: &ConfigPathContext) -> io::Result<bool> {+ Ok(contains_glob_chars_for_platform(+ path,+ context.convention() == PathConvention::Windows,+ ))+}++pub(super) fn absolute_path(path: &str, context: &ConfigPathContext) -> io::Result<PathUri> {+ let convention = context.convention();+ if convention.home_relative_suffix(path).is_none()+ && LegacyAppPathString::from_string(path)+ .to_path_uri(convention)+ .is_err()+ {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!("filesystem path `{path}` must be absolute, use `~/...`, or start with `:`"),+ ));+ }+ context+ .resolve_path(path)+ .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))+}++pub(super) fn relative_subpath(subpath: &str, context: &ConfigPathContext) -> io::Result<String> {+ let convention = context.convention();+ let mut components = convention.path_segments(subpath);+ let first = components.next();+ let has_drive_prefix = convention == PathConvention::Windows+ && subpath+ .as_bytes()+ .first()+ .is_some_and(u8::is_ascii_alphabetic)+ && subpath.as_bytes().get(1) == Some(&b':');+ if !subpath.is_empty()+ && !matches!(first, Some("" | "." | ".."))+ && !has_drive_prefix+ && !components.any(|component| component == "..")+ {+ // Preserve spelling after the same validation as native components:+ // interior `.` and repeated separators stay in symbolic rules.+ return Ok(subpath.to_string());+ }+ Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!(+ "filesystem subpath `{subpath}` must be a descendant path without `.` or `..` components"+ ),+ ))+}++pub(super) fn contains_glob_chars_for_platform(path: &str, is_windows: bool) -> bool {+ let normalized_windows_path = if is_windows {+ normalize_windows_device_path(path)+ } else {+ None+ };+ let path = normalized_windows_path.as_deref().unwrap_or(path);+ path.chars().any(|ch| matches!(ch, '*' | '?' | '[' | ']'))+}++#[cfg(test)]+#[path = "permission_path_tests.rs"]+mod tests;diff --git a/codex-rs/core/src/config/permission_path_tests.rs b/codex-rs/core/src/config/permission_path_tests.rsnew file mode 100644index 0000000000..34fb5c73e8--- /dev/null+++ b/codex-rs/core/src/config/permission_path_tests.rs@@ -0,0 +1,542 @@+//! Permission compilation preserves executor paths and native policy semantics.++use super::super::permissions::CompiledPermissionProfile;+use super::super::permissions::WorkspaceWriteSettings;+use super::super::permissions::compile_permission_profile;+use super::relative_subpath;+use codex_config::ConfigPathContext;+use codex_config::permissions_toml::FilesystemPermissionToml;+use codex_config::permissions_toml::FilesystemPermissionToml::Access;+use codex_config::permissions_toml::FilesystemPermissionsToml;+use codex_config::permissions_toml::PermissionProfileToml;+use codex_config::permissions_toml::PermissionsToml;+use codex_config::permissions_toml::WorkspaceRootsToml;+use codex_protocol::permissions::FileSystemAccessMode;+use codex_protocol::permissions::FileSystemAccessMode::Deny;+use codex_protocol::permissions::FileSystemAccessMode::Read;+use codex_protocol::permissions::FileSystemAccessMode::Write;+use codex_protocol::permissions::FileSystemPath;+use codex_protocol::permissions::FileSystemSandboxEntry;+use codex_protocol::permissions::FileSystemSandboxPolicy;+use codex_protocol::permissions::FileSystemSandboxPolicyContext;+use codex_protocol::permissions::NetworkSandboxPolicy;+use codex_protocol::permissions::ReadDenyMatcher;+use codex_protocol::permissions::project_roots_glob_pattern;+use codex_utils_absolute_path::AbsolutePathBufGuard;+use codex_utils_path_uri::PathConvention;+use codex_utils_path_uri::PathUri;+use pretty_assertions::assert_eq;+use std::collections::BTreeMap;+use std::path::Path;++struct ExecutorPathFacts {+ base_dir: PathUri,+ user_home_dir: Option<PathUri>,+}++impl ExecutorPathFacts {+ fn context(&self) -> ConfigPathContext {+ ConfigPathContext::new(+ self.base_dir.infer_path_convention().unwrap(),+ Some(self.base_dir.clone()),+ self.user_home_dir.clone(),+ )+ }++ fn policy_context(&self) -> FileSystemSandboxPolicyContext<'_> {+ FileSystemSandboxPolicyContext {+ cwd: &self.base_dir,+ workspace_roots: std::slice::from_ref(&self.base_dir),+ user_home_dir: self.user_home_dir.as_ref(),+ temporary_directories: None,+ }+ }++ fn compile(&self, permissions: &PermissionsToml) -> std::io::Result<CompiledPermissionProfile> {+ compile_permission_profile(+ Some(permissions),+ "remote",+ &self.context(),+ /*workspace_write*/ None,+ &mut Vec::new(),+ )+ }+}++fn executor_contexts() -> impl Iterator<Item = ExecutorPathFacts> {+ [+ ("file:///workspace/project", "file:///home/executor"),+ ("file:///Users/executor/project", "file:///Users/executor"),+ ("file:///C:/workspace/project", "file:///C:/Users/executor"),+ (+ "file://server/share/project",+ "file://server/share/users/executor",+ ),+ ]+ .into_iter()+ .map(|(cwd, home)| ExecutorPathFacts {+ base_dir: PathUri::parse(cwd).unwrap(),+ user_home_dir: Some(PathUri::parse(home).unwrap()),+ })+}++fn permissions_with_rule(+ path: impl Into<String>,+ permission: FilesystemPermissionToml,+) -> PermissionsToml {+ PermissionsToml {+ entries: BTreeMap::from([(+ "remote".to_string(),+ PermissionProfileToml {+ filesystem: Some(FilesystemPermissionsToml {+ glob_scan_max_depth: None,+ entries: BTreeMap::from([(path.into(), permission)]),+ }),+ ..Default::default()+ },+ )]),+ }+}++fn scoped(entries: &[(&str, FileSystemAccessMode)]) -> FilesystemPermissionToml {+ FilesystemPermissionToml::Scoped(+ entries+ .iter()+ .map(|(path, access)| (path.to_string(), *access))+ .collect(),+ )+}++#[track_caller]+fn assert_invalid(result: std::io::Result<CompiledPermissionProfile>) {+ assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::InvalidInput);+}++#[track_caller]+fn assert_read_denials(+ policy: &FileSystemSandboxPolicy,+ context: &FileSystemSandboxPolicyContext<'_>,+ cases: &[(PathUri, bool)],+) {+ let matcher = ReadDenyMatcher::try_new_with_context(policy, context)+ .unwrap()+ .unwrap();+ for (path, denied) in cases {+ assert_eq!(+ matcher.is_read_denied_uri(path, context),+ *denied,+ "path={path}"+ );+ }+}++#[track_caller]+fn assert_executor_rule(+ permissions: &PermissionsToml,+ context: &ConfigPathContext,+ expected: FileSystemSandboxEntry,+) -> CompiledPermissionProfile {+ let mut warnings = Vec::new();+ let compiled = compile_permission_profile(+ Some(permissions),+ "remote",+ context,+ /*workspace_write*/ None,+ &mut warnings,+ )+ .unwrap();+ assert_eq!(+ (+ compiled.permission_profile.to_runtime_permissions(),+ &compiled.workspace_roots+ ),+ (+ (+ FileSystemSandboxPolicy::restricted(vec![expected]),+ NetworkSandboxPolicy::Restricted+ ),+ &Vec::<PathUri>::new(),+ ),+ "permissions={permissions:?}, context={context:?}",+ );+ assert!(warnings.is_empty(), "{warnings:?}");+ compiled+}++fn deny_glob_entry(pattern: impl Into<String>) -> FileSystemSandboxEntry {+ FileSystemSandboxEntry::new(+ FileSystemPath::GlobPattern {+ pattern: pattern.into(),+ },+ Deny,+ )+}++#[test]+fn compiler_uses_shared_resolution_for_literal_and_glob_rules() {+ for facts in executor_contexts() {+ let home = facts.user_home_dir.as_ref().unwrap();+ let root = home.join("shared").unwrap();+ let literal = FileSystemSandboxEntry::new(root.into(), Write);+ let glob = deny_glob_entry(+ home.join("shared/*.env")+ .unwrap()+ .inferred_native_path_string(),+ );+ for (input, permission, expected) in [+ ("~/shared/**".into(), Access(Write), literal.clone()),+ ("~/shared/*.env".into(), Access(Deny), glob.clone()),+ (+ home.inferred_native_path_string(),+ scoped(&[("shared", Write)]),+ literal,+ ),+ (+ home.inferred_native_path_string(),+ scoped(&[("shared/*.env", Deny)]),+ glob,+ ),+ ] {+ assert_executor_rule(+ &permissions_with_rule(input, permission),+ &facts.context(),+ expected,+ );+ }+ }+}++#[test]+fn scoped_home_rules_resolve_and_deny_the_supplied_home() {+ for facts in executor_contexts() {+ let home = facts.user_home_dir.as_ref().unwrap();+ let home_glob = match facts.context().convention() {+ PathConvention::Posix => "~/private/*.env",+ PathConvention::Windows => r"~\private\*.env",+ };+ for outer in [+ facts.base_dir.inferred_native_path_string(),+ ":workspace_roots".into(),+ ":project_roots".into(),+ ] {+ for (subpath, resolved) in [+ ("~", home.clone()),+ ("~/private", home.join("private").unwrap()),+ (home_glob, home.join("private/*.env").unwrap()),+ ] {+ let expected = if subpath.contains('*') {+ deny_glob_entry(resolved.inferred_native_path_string())+ } else {+ FileSystemSandboxEntry::new(resolved.into(), Deny)+ };+ let permissions = permissions_with_rule(&outer, scoped(&[(subpath, Deny)]));+ let compiled = assert_executor_rule(&permissions, &facts.context(), expected);+ assert_read_denials(+ &compiled.permission_profile.file_system_sandbox_policy(),+ &facts.policy_context(),+ &[+ (home.join("private/key.env").unwrap(), true),+ (+ facts.base_dir.join("private/key.env").unwrap(),+ subpath == "~" && facts.base_dir.starts_with(home),+ ),+ ],+ );+ }+ for subpath in ["~/../private", "~/child/../private"] {+ let permissions = permissions_with_rule(&outer, scoped(&[(subpath, Deny)]));+ assert_invalid(facts.compile(&permissions));+ }+ }+ }+}++#[test]+fn inherited_workspace_roots_apply_to_executor_policy_and_read_denials() {+ let permissions: PermissionsToml = toml::from_str(+ r#"+ [base]+ extends = ":read-only"+ [base.workspace_roots]+ "../shared" = true+ "~/scratch" = true+ [remote]+ extends = "base"+ [remote.workspace_roots]+ "../shared" = false+ "./profile-root" = true+ [remote.filesystem]+ glob_scan_max_depth = 3+ [remote.filesystem.":workspace_roots"]+ "." = "write"+ "private/*.env" = "deny"+ [remote.network]+ enabled = true+ "#,+ )+ .unwrap();+ for facts in executor_contexts() {+ let compiled = facts.compile(&permissions).unwrap();+ let (policy, network) = compiled.permission_profile.to_runtime_permissions();+ let roots = compiled.workspace_roots;+ let home = facts.user_home_dir.as_ref().unwrap();+ assert_eq!(+ (&roots, network),+ (+ &vec![+ facts.base_dir.join("profile-root").unwrap(),+ home.join("scratch").unwrap()+ ],+ NetworkSandboxPolicy::Enabled+ ),+ );+ let policy =+ policy.materialize_project_roots_with_path_uris(std::slice::from_ref(&facts.base_dir));+ let context = facts.policy_context();+ for root in std::iter::once(&facts.base_dir).chain(&roots) {+ assert!(policy.can_write_path(&root.join("output").unwrap(), &context));+ assert_read_denials(+ &policy,+ &context,+ &[+ (root.join("private/key.env").unwrap(), true),+ (root.join("private/key.txt").unwrap(), false),+ ],+ );+ }+ }+}++#[test]+fn interior_dot_workspace_glob_fails_closed_for_every_path_convention() {+ let permissions = permissions_with_rule(+ ":workspace_roots",+ scoped(&[(".", Write), ("private/./*.env", Deny)]),+ );+ // Preserve the symbolic spelling; strict materialization rejects dot components.+ let expected = (+ FileSystemSandboxPolicy::restricted(vec![+ FileSystemSandboxEntry::new(+ FileSystemPath::Special {+ value: codex_protocol::permissions::FileSystemSpecialPath::project_roots(+ /*subpath*/ None,+ ),+ },+ Write,+ ),+ deny_glob_entry("codex-project-roots://private/./*.env"),+ ]),+ NetworkSandboxPolicy::Restricted,+ );+ for facts in executor_contexts() {+ let compiled = facts.compile(&permissions).unwrap();+ assert_eq!(+ compiled.permission_profile.to_runtime_permissions(),+ expected+ );+ let policy = compiled+ .permission_profile+ .file_system_sandbox_policy()+ .materialize_project_roots_with_path_uris(std::slice::from_ref(&facts.base_dir));+ let context = facts.policy_context();+ assert!(!policy.can_write_path(&facts.base_dir.join("output").unwrap(), &context));+ assert_read_denials(+ &policy,+ &context,+ &[+ (facts.base_dir.join("private/key.env").unwrap(), true),+ (facts.base_dir.join("private/key.txt").unwrap(), true),+ ],+ );+ }+}++#[test]+fn permission_rules_require_absolute_paths_and_descendant_subpaths() {+ for mut facts in executor_contexts() {+ facts.user_home_dir = None;+ // Unlike the shared resolver, permission rules cannot use cwd-relative paths.+ // Missing executor home must not fall back to this host's home.+ for input in [+ "relative",+ "./relative",+ "~",+ "~/private",+ "C:private",+ r"\private",+ // Preserve raw-text validation even when URI parsing would remove `a:b`.+ r"C:\base\a:b\..\private",+ ] {+ assert_invalid(facts.compile(&permissions_with_rule(input, Access(Read))));+ }+ for outer in [+ facts.base_dir.inferred_native_path_string(),+ ":workspace_roots".into(),+ ] {+ for input in ["../private", "./private", "child/../private"] {+ assert_invalid(+ facts.compile(&permissions_with_rule(&outer, scoped(&[(input, Deny)]))),+ );+ }+ }+ }+}++#[test]+fn executor_scoped_globs_preserve_native_separator_spelling() {+ for facts in+ executor_contexts().filter(|facts| facts.context().convention() == PathConvention::Windows)+ {+ for subpath in ["secrets/*.env", r"secrets\*.env", r"nested/secrets\*.env"] {+ assert_executor_rule(+ &permissions_with_rule(":workspace_roots", scoped(&[(subpath, Deny)])),+ &facts.context(),+ deny_glob_entry(project_roots_glob_pattern(Path::new(subpath))),+ );+ }+ }+}++fn native_context() -> ConfigPathContext {+ ConfigPathContext::new(+ PathConvention::native(),+ std::env::current_dir()+ .ok()+ .and_then(|cwd| PathUri::from_host_native_path(cwd).ok()),+ AbsolutePathBufGuard::home_directory()+ .and_then(|home| PathUri::from_host_native_path(home).ok()),+ )+}++#[test]+fn native_path_grammar_preserves_component_validation_and_spelling() {+ let context = native_context();+ for input in [+ "",+ ".",+ "..",+ "./child",+ "../child",+ "child/../other",+ "child/./other",+ "child//other/",+ "~/child",+ r"~\child",+ r"C:child",+ "/child",+ r"\child",+ "child/.../leaf",+ ] {+ let native_accepts = !input.is_empty()+ && Path::new(input)+ .components()+ .all(|component| matches!(component, std::path::Component::Normal(_)));+ match relative_subpath(input, &context) {+ Ok(actual) => {+ assert!(native_accepts, "{input}");+ assert_eq!(actual, input);+ }+ Err(_) => assert!(!native_accepts, "{input}"),+ }+ }+}++#[cfg(unix)]+#[test]+fn non_unicode_home_is_rejected_by_the_shared_compiler() {+ use std::ffi::OsString;+ use std::os::unix::ffi::OsStringExt;++ let home = std::path::PathBuf::from(OsString::from_vec(b"/home/native-\xff".to_vec()));+ AbsolutePathBufGuard::with_home_directory(&home, || {+ let permissions = permissions_with_rule("~/read", Access(Read));+ assert_invalid(compile_permission_profile(+ Some(&permissions),+ "remote",+ &native_context(),+ /*workspace_write*/ None,+ &mut Vec::new(),+ ));+ });+}++#[test]+fn deny_globs_validate_literal_home_and_scoped_directories() {+ for mut facts in executor_contexts() {+ let directory = facts.base_dir.join("sam[1]").unwrap();+ facts.user_home_dir = Some(directory.clone());+ for (outer, permission) in [+ ("~/private/*.key".into(), Access(Deny)),+ ("~/private".into(), scoped(&[("*.key", Deny)])),+ (+ directory.inferred_native_path_string(),+ scoped(&[("private/*.key", Deny)]),+ ),+ ] {+ assert_invalid(facts.compile(&permissions_with_rule(outer, permission)));+ }+ }+}++#[test]+fn compiler_applies_deny_globs_safely_to_literal_profile_workspace_roots() {+ for facts in executor_contexts() {+ let root = facts.base_dir.join("sam[1]").unwrap();+ let mut permissions = permissions_with_rule(+ ":workspace_roots",+ scoped(&[(".", Write), ("private/*.key", Deny)]),+ );+ permissions+ .entries+ .get_mut("remote")+ .unwrap()+ .workspace_roots = Some(WorkspaceRootsToml {+ entries: BTreeMap::from([(root.inferred_native_path_string(), true)]),+ });+ let compiled = facts.compile(&permissions).unwrap();+ assert_eq!(compiled.workspace_roots, vec![root.clone()]);+ // Infallible materialization conservatively denies the literal root.+ assert_read_denials(+ &compiled.permission_profile.file_system_sandbox_policy(),+ &facts.policy_context(),+ &[+ (root.join("private/a.key").unwrap(), true),+ (root.join("public.txt").unwrap(), true),+ (facts.base_dir.join("sam1/private/a.key").unwrap(), false),+ ],+ );+ }+}++#[test]+fn builtin_workspace_settings_use_executor_roots_in_the_compiled_profile() {+ for facts in executor_contexts() {+ let root = facts.base_dir.join("legacy-root").unwrap();+ let settings = WorkspaceWriteSettings {+ writable_roots: vec![root.clone(), root.clone()],+ network_access: true,+ exclude_tmpdir_env_var: true,+ exclude_slash_tmp: true,+ };+ let compiled = compile_permission_profile(+ /*permissions*/ None,+ ":workspace",+ &facts.context(),+ Some(&settings),+ &mut Vec::new(),+ )+ .unwrap();+ assert_eq!(compiled.workspace_roots, vec![root.clone()]);+ assert_eq!(+ compiled.permission_profile.network_sandbox_policy(),+ NetworkSandboxPolicy::Enabled,+ );+ let policy_context = facts.policy_context();+ assert!(+ compiled+ .permission_profile+ .file_system_sandbox_policy()+ .can_write_path(&root.join("output").unwrap(), &policy_context)+ );+ }+}diff --git a/codex-rs/core/src/config/permission_profile_catalog.rs b/codex-rs/core/src/config/permission_profile_catalog.rsindex 51b34c2640..34262a3bcf 100644--- a/codex-rs/core/src/config/permission_profile_catalog.rs+++ b/codex-rs/core/src/config/permission_profile_catalog.rs@@ -1,4 +1,5 @@use codex_config::ConfigLayerStack;+use codex_config::ConfigPathContext;use codex_config::RequirementSource;use codex_config::SandboxModeRequirement;use codex_config::Sourced;@@ -13,7 +14,7 @@ use super::merge_managed_permission_profiles;use super::permissions::BUILT_IN_DANGER_FULL_ACCESS_PROFILE;use super::permissions::BUILT_IN_READ_ONLY_PROFILE;use super::permissions::BUILT_IN_WORKSPACE_PROFILE;-use super::permissions::compile_permission_profile_selection;+use super::permissions::compile_permission_profile;use super::permissions::validate_user_permission_profile_names;use super::validate_required_permission_profile_catalog;@@ -25,9 +26,10 @@ pub struct PermissionProfileCatalogEntry {pub allowed: bool,}-/// Builds the effective permission profile catalog for a config layer stack.+/// Builds the effective catalog using supplied execution-host path facts.pub fn permission_profile_catalog(config_layer_stack: &ConfigLayerStack,+ context: &ConfigPathContext,) -> std::io::Result<Vec<PermissionProfileCatalogEntry>> {let permissions = config_layer_stack.effective_config()@@ -39,58 +41,50 @@ pub fn permission_profile_catalog(let requirements_toml = config_layer_stack.requirements_toml();let permissions = merge_managed_permission_profiles(permissions.as_ref(), requirements_toml)?;- permission_profile_catalog_from_permissions(config_layer_stack, permissions.as_ref())+ permission_profile_catalog_from_permissions(config_layer_stack, permissions.as_ref(), context)}pub(super) fn permission_profile_catalog_from_permissions(config_layer_stack: &ConfigLayerStack,permissions: Option<&PermissionsToml>,+ context: &ConfigPathContext,) -> std::io::Result<Vec<PermissionProfileCatalogEntry>> {let requirements_toml = config_layer_stack.requirements_toml();validate_user_permission_profile_names(permissions)?;validate_required_permission_profile_catalog(requirements_toml, permissions)?;- let mut catalog = [- (BUILT_IN_READ_ONLY_PROFILE, PermissionProfile::read_only()),- (- BUILT_IN_WORKSPACE_PROFILE,- PermissionProfile::workspace_write(),- ),- (- BUILT_IN_DANGER_FULL_ACCESS_PROFILE,- PermissionProfile::Disabled,- ),+ let entries = [+ BUILT_IN_READ_ONLY_PROFILE,+ BUILT_IN_WORKSPACE_PROFILE,+ BUILT_IN_DANGER_FULL_ACCESS_PROFILE,].into_iter()- .map(|(id, permission_profile)| PermissionProfileCatalogEntry {- id: id.to_string(),- description: None,- allowed: permission_profile_is_allowed(config_layer_stack, id, &permission_profile),- })- .collect::<Vec<_>>();-- if let Some(permissions) = permissions {- catalog.extend(permissions.entries.iter().map(|(id, profile)| {- let mut warnings = Vec::new();- let allowed = compile_permission_profile_selection(- Some(permissions),+ .map(|id| (id, None))+ .chain(+ permissions+ .into_iter()+ .flat_map(|permissions| &permissions.entries)+ .map(|(id, profile)| (id.as_str(), profile.description.clone())),+ );+ let catalog = entries+ .map(|(id, description)| {+ let allowed = compile_permission_profile(+ permissions,id,+ context,/*workspace_write*/ None,- &mut warnings,+ &mut Vec::new(),)- .map(|(file_system, network)| {- PermissionProfile::from_runtime_permissions(&file_system, network)- })- .is_ok_and(|permission_profile| {- permission_profile_is_allowed(config_layer_stack, id, &permission_profile)+ .is_ok_and(|compiled| {+ permission_profile_is_allowed(config_layer_stack, id, &compiled.permission_profile)});PermissionProfileCatalogEntry {- id: id.clone(),- description: profile.description.clone(),+ id: id.to_string(),+ description,allowed,}- }));- }+ })+ .collect();Ok(catalog)}diff --git a/codex-rs/core/src/config/permissions.rs b/codex-rs/core/src/config/permissions.rsindex 61a4d4d060..2207c8f0fb 100644--- a/codex-rs/core/src/config/permissions.rs+++ b/codex-rs/core/src/config/permissions.rs@@ -1,10 +1,10 @@-use std::borrow::Cow;use std::collections::BTreeMap;+use std::collections::HashSet;use std::io;-use std::path::Component;use std::path::Path;use std::path::PathBuf;+use codex_config::ConfigPathContext;use codex_config::permissions_toml::FilesystemPermissionToml;use codex_config::permissions_toml::FilesystemPermissionsToml;use codex_config::permissions_toml::NetworkDomainPermissionToml;@@ -15,7 +15,6 @@ use codex_config::permissions_toml::NetworkUnixSocketPermissionsToml;use codex_config::permissions_toml::PermissionProfileToml;use codex_config::permissions_toml::PermissionsToml;use codex_config::permissions_toml::WorkspaceRootsToml;-use codex_config::types::SandboxWorkspaceWrite;use codex_features::NetworkProxyConfigToml;use codex_features::NetworkProxyDomainPermissionToml;use codex_features::NetworkProxyModeToml;@@ -37,8 +36,12 @@ use codex_protocol::permissions::FileSystemSpecialPath;use codex_protocol::permissions::NetworkSandboxPolicy;use codex_protocol::permissions::project_roots_glob_pattern;use codex_utils_absolute_path::AbsolutePathBuf;+use codex_utils_path_uri::PathUri;use super::ProjectConfig;+use super::permission_path;+#[cfg(test)]+use super::permission_path::contains_glob_chars_for_platform;pub(crate) const BUILT_IN_READ_ONLY_PROFILE: &str = BUILT_IN_PERMISSION_PROFILE_READ_ONLY;pub(crate) const BUILT_IN_WORKSPACE_PROFILE: &str = BUILT_IN_PERMISSION_PROFILE_WORKSPACE;@@ -67,14 +70,14 @@ pub(crate) fn is_builtin_permission_profile_name(profile_name: &str) -> bool {)}-pub(crate) fn builtin_permission_profile(+fn builtin_permission_profile(profile_name: &str,- workspace_write: Option<&SandboxWorkspaceWrite>,+ workspace_write: Option<&WorkspaceWriteSettings>,) -> Option<PermissionProfile> {match profile_name {BUILT_IN_READ_ONLY_PROFILE => Some(PermissionProfile::read_only()),BUILT_IN_WORKSPACE_PROFILE => Some(match workspace_write {- Some(SandboxWorkspaceWrite {+ Some(WorkspaceWriteSettings {writable_roots: _,network_access,exclude_tmpdir_env_var,@@ -351,13 +354,91 @@ pub(crate) fn network_proxy_config_for_profile_selection())}-/// Compiles a named permission profile into filesystem and network policies.+/// Supplied legacy workspace-write settings, using paths owned by the execution host.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct WorkspaceWriteSettings {+ pub writable_roots: Vec<PathUri>,+ pub network_access: bool,+ pub exclude_tmpdir_env_var: bool,+ pub exclude_slash_tmp: bool,+}++/// A compiled profile with configured roots materialized and runtime root symbols retained.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CompiledPermissionProfile {+ pub permission_profile: PermissionProfile,+ pub workspace_roots: Vec<PathUri>,+}++/// Resolves a selected profile and its roots using only supplied execution-host facts.+/// Configured roots are materialized before return; symbolic roots remain available+/// for runtime workspace selection. Local callers only convert the returned URI types.pub fn compile_permission_profile(- permissions: &PermissionsToml,+ permissions: Option<&PermissionsToml>,profile_name: &str,+ context: &ConfigPathContext,+ workspace_write: Option<&WorkspaceWriteSettings>,+ startup_warnings: &mut Vec<String>,+) -> io::Result<CompiledPermissionProfile> {+ let builtin = builtin_permission_profile(profile_name, workspace_write);+ let (file_system, network, mut workspace_roots) = if let Some(builtin) = &builtin {+ let (file_system, network) = builtin.to_runtime_permissions();+ let workspace_roots = if profile_name == BUILT_IN_WORKSPACE_PROFILE {+ workspace_write+ .into_iter()+ .flat_map(|settings| &settings.writable_roots)+ .map(|root| {+ context+ .resolve_against(".", root)+ .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))+ })+ .collect::<io::Result<Vec<_>>>()?+ } else {+ Vec::new()+ };+ (file_system, network, workspace_roots)+ } else {+ reject_unknown_builtin_permission_profile(profile_name)?;+ let permissions = permissions.ok_or_else(|| {+ io::Error::new(+ io::ErrorKind::InvalidInput,+ "default_permissions requires a `[permissions]` table",+ )+ })?;+ let profile = resolve_permission_profile(permissions, profile_name)?;+ let (file_system, network) =+ compile_resolved_permission_profile(&profile, profile_name, context, startup_warnings)?;+ let workspace_roots = profile+ .workspace_roots+ .iter()+ .flat_map(WorkspaceRootsToml::enabled_roots)+ .map(|path| {+ context+ .resolve_path(path)+ .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))+ })+ .collect::<io::Result<Vec<_>>>()?;+ (file_system, network, workspace_roots)+ };+ let mut seen = HashSet::new();+ workspace_roots.retain(|root| seen.insert(root.clone()));+ let file_system = file_system.with_materialized_project_roots_for_path_uris(&workspace_roots);+ let permission_profile = match builtin {+ Some(PermissionProfile::Disabled) => PermissionProfile::Disabled,+ _ => PermissionProfile::from_runtime_permissions(&file_system, network),+ };+ Ok(CompiledPermissionProfile {+ permission_profile,+ workspace_roots,+ })+}++fn compile_resolved_permission_profile(+ profile: &PermissionProfileToml,+ profile_name: &str,+ context: &ConfigPathContext,startup_warnings: &mut Vec<String>,) -> io::Result<(FileSystemSandboxPolicy, NetworkSandboxPolicy)> {- let profile = resolve_permission_profile(permissions, profile_name)?;let mut file_system_sandbox_policy = FileSystemSandboxPolicy::restricted(Vec::new());let base_network_sandbox_policy = NetworkSandboxPolicy::Restricted;if let Some(filesystem) = profile.filesystem.as_ref() {@@ -368,7 +449,7 @@ pub fn compile_permission_profile();} else {if cfg!(not(target_os = "macos")) {- for pattern in unsupported_read_write_glob_paths(filesystem) {+ for pattern in unsupported_read_write_glob_paths(filesystem, context)? {push_warning(startup_warnings,format!(@@ -391,6 +472,7 @@ pub fn compile_permission_profile(.extend(compile_filesystem_permission(path,permission,+ context,startup_warnings,)?);}@@ -415,61 +497,6 @@ pub fn compile_permission_profile(Ok((file_system_sandbox_policy, network_sandbox_policy))}-pub(crate) fn compile_permission_profile_selection(- permissions: Option<&PermissionsToml>,- profile_name: &str,- workspace_write: Option<&SandboxWorkspaceWrite>,- startup_warnings: &mut Vec<String>,-) -> io::Result<(FileSystemSandboxPolicy, NetworkSandboxPolicy)> {- if let Some(permission_profile) = builtin_permission_profile(profile_name, workspace_write) {- return Ok(permission_profile.to_runtime_permissions());- }- reject_unknown_builtin_permission_profile(profile_name)?;-- let permissions = permissions.ok_or_else(|| {- io::Error::new(- io::ErrorKind::InvalidInput,- "default_permissions requires a `[permissions]` table",- )- })?;- compile_permission_profile(permissions, profile_name, startup_warnings)-}--pub(crate) fn compile_permission_profile_workspace_roots(- permissions: Option<&PermissionsToml>,- profile_name: &str,- policy_cwd: &Path,-) -> io::Result<Vec<AbsolutePathBuf>> {- if is_builtin_permission_profile_name(profile_name) {- return Ok(Vec::new());- }- reject_unknown_builtin_permission_profile(profile_name)?;-- let permissions = permissions.ok_or_else(|| {- io::Error::new(- io::ErrorKind::InvalidInput,- "default_permissions requires a `[permissions]` table",- )- })?;- let profile = resolve_permission_profile(permissions, profile_name)?;- Ok(compile_workspace_roots(- profile.workspace_roots.as_ref(),- policy_cwd,- ))-}--fn compile_workspace_roots(- workspace_roots: Option<&WorkspaceRootsToml>,- policy_cwd: &Path,-) -> Vec<AbsolutePathBuf> {- workspace_roots.map_or_else(Vec::new, |workspace_roots| {- workspace_roots- .enabled_roots()- .map(|path| AbsolutePathBuf::resolve_path_against_base(path, policy_cwd))- .collect()- })-}-pub(crate) fn reject_unknown_builtin_permission_profile(profile_name: &str) -> io::Result<()> {if profile_name.starts_with(':') {return Err(io::Error::new(@@ -530,20 +557,39 @@ fn compile_network_sandbox_policy(fn compile_filesystem_permission(path: &str,permission: &FilesystemPermissionToml,+ context: &ConfigPathContext,startup_warnings: &mut Vec<String>,) -> io::Result<Vec<FileSystemSandboxEntry>> {let mut entries = Vec::new();match permission {FilesystemPermissionToml::Access(access) => {entries.push(FileSystemSandboxEntry {- path: compile_filesystem_access_path(path, *access, startup_warnings)?,+ path: compile_filesystem_access_path(path, *access, context, startup_warnings)?,access: *access,missing_path_behavior: None,});}FilesystemPermissionToml::Scoped(scoped_entries) => {for (subpath, access) in scoped_entries {- let has_glob = contains_glob_chars(subpath);+ if matches!(+ parse_special_path(path),+ Some(FileSystemSpecialPath::ProjectRoots { .. })+ ) && context.convention().home_relative_suffix(subpath).is_some()+ {+ permission_path::relative_subpath(subpath, context)?;+ entries.push(FileSystemSandboxEntry {+ path: compile_filesystem_access_path(+ subpath,+ *access,+ context,+ startup_warnings,+ )?,+ access: *access,+ missing_path_behavior: None,+ });+ continue;+ }+ let has_glob = permission_path::contains_glob(subpath, context)?;let can_compile_as_pattern = match parse_special_path(path) {Some(FileSystemSpecialPath::ProjectRoots { .. }) | None => true,Some(_) => false,@@ -554,16 +600,23 @@ fn compile_filesystem_permission(// exact-path parser so existing path semantics stay intact.let entry = FileSystemSandboxEntry {path: FileSystemPath::GlobPattern {- pattern: compile_scoped_filesystem_pattern(path, subpath, *access)?,+ pattern: compile_scoped_filesystem_pattern(+ path, subpath, *access, context,+ )?,},access: *access,missing_path_behavior: None,};entries.push(entry);} else {- let subpath = compile_read_write_glob_path(subpath, *access)?;+ let subpath = compile_read_write_glob_path(subpath, *access, context)?;entries.push(FileSystemSandboxEntry {- path: compile_scoped_filesystem_path(path, subpath, startup_warnings)?,+ path: compile_scoped_filesystem_path(+ path,+ subpath,+ context,+ startup_warnings,+ )?,access: *access,missing_path_behavior: None,});@@ -577,10 +630,11 @@ fn compile_filesystem_permission(fn compile_filesystem_access_path(path: &str,access: FileSystemAccessMode,+ context: &ConfigPathContext,startup_warnings: &mut Vec<String>,) -> io::Result<FileSystemPath> {- if !contains_glob_chars(path) {- return compile_filesystem_path(path, startup_warnings);+ if !permission_path::contains_glob(path, context)? {+ return compile_filesystem_path(path, context, startup_warnings);}if access == FileSystemAccessMode::Deny {@@ -589,16 +643,19 @@ fn compile_filesystem_access_path(// becoming policy patterns; relative project-root glob syntax is// handled by `compile_scoped_filesystem_pattern`.return Ok(FileSystemPath::GlobPattern {- pattern: parse_absolute_path(path)?.to_string_lossy().into_owned(),+ pattern: permission_path::absolute_path(path, context)?+ .to_config_path_string(context.convention())+ .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?,});}- let path = compile_read_write_glob_path(path, access)?;- compile_filesystem_path(path, startup_warnings)+ let path = compile_read_write_glob_path(path, access, context)?;+ compile_filesystem_path(path, context, startup_warnings)}fn compile_filesystem_path(path: &str,+ context: &ConfigPathContext,startup_warnings: &mut Vec<String>,) -> io::Result<FileSystemPath> {if let Some(special) = parse_special_path(path) {@@ -606,23 +663,21 @@ fn compile_filesystem_path(return Ok(FileSystemPath::Special { value: special });}- let path = parse_absolute_path(path)?;- Ok(path.into())+ Ok(permission_path::absolute_path(path, context)?.into())}fn compile_scoped_filesystem_path(path: &str,subpath: &str,+ context: &ConfigPathContext,startup_warnings: &mut Vec<String>,) -> io::Result<FileSystemPath> {if subpath == "." {- return compile_filesystem_path(path, startup_warnings);+ return compile_filesystem_path(path, context, startup_warnings);}if let Some(special) = parse_special_path(path) {- let subpath = parse_relative_subpath(subpath)?- .to_string_lossy()- .into_owned();+ let subpath = permission_path::relative_subpath(subpath, context)?;let special = match special {FileSystemSpecialPath::ProjectRoots { .. } => Ok(FileSystemPath::Special {value: FileSystemSpecialPath::project_roots(Some(subpath)),@@ -641,9 +696,11 @@ fn compile_scoped_filesystem_path(return Ok(special);}- let subpath = parse_relative_subpath(subpath)?;- let base = parse_absolute_path(path)?;- let path = AbsolutePathBuf::resolve_path_against_base(&subpath, base.as_path());+ let subpath = permission_path::relative_subpath(subpath, context)?;+ let base = permission_path::absolute_path(path, context)?;+ let path = context+ .resolve_against(&subpath, &base)+ .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;Ok(path.into())}@@ -651,6 +708,7 @@ fn compile_scoped_filesystem_pattern(path: &str,subpath: &str,access: FileSystemAccessMode,+ context: &ConfigPathContext,) -> io::Result<String> {// Pattern entries currently mean deny-read only. Supporting broader access// modes here would imply glob-based read/write allow semantics that the@@ -661,33 +719,40 @@ fn compile_scoped_filesystem_pattern(format!("filesystem glob subpath `{subpath}` only supports `deny` access"),));}- let subpath = parse_relative_subpath(subpath)?;+ let subpath = permission_path::relative_subpath(subpath, context)?;match parse_special_path(path) {Some(FileSystemSpecialPath::ProjectRoots { .. }) => {// Keep `:workspace_roots` glob patterns symbolic until the active// workspace roots are known, then materialize them for cwd and any// runtime/profile-added workspace roots together.- Ok(project_roots_glob_pattern(&subpath))+ Ok(project_roots_glob_pattern(Path::new(&subpath)))}Some(_) => Err(io::Error::new(io::ErrorKind::InvalidInput,format!("filesystem path `{path}` does not support nested entries"),)),None => {- let base = parse_absolute_path(path)?;- Ok(base.join(&subpath).to_string_lossy().to_string())+ let base = permission_path::absolute_path(path, context)?;+ context+ .resolve_against(&subpath, &base)+ .and_then(|path| path.to_config_path_string(context.convention()))+ .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))}}}-fn compile_read_write_glob_path(path: &str, access: FileSystemAccessMode) -> io::Result<&str> {- if !contains_glob_chars(path) {+fn compile_read_write_glob_path<'a>(+ path: &'a str,+ access: FileSystemAccessMode,+ context: &ConfigPathContext,+) -> io::Result<&'a str> {+ if !permission_path::contains_glob(path, context)? {return Ok(path);}let path_without_trailing_glob = remove_trailing_glob_suffix(path);- if !contains_glob_chars(path_without_trailing_glob) {+ if !permission_path::contains_glob(path_without_trailing_glob, context)? {return Ok(path_without_trailing_glob);}@@ -699,13 +764,16 @@ fn compile_read_write_glob_path(path: &str, access: FileSystemAccessMode) -> io:))}-fn unsupported_read_write_glob_paths(filesystem: &FilesystemPermissionsToml) -> Vec<String> {+fn unsupported_read_write_glob_paths(+ filesystem: &FilesystemPermissionsToml,+ context: &ConfigPathContext,+) -> io::Result<Vec<String>> {let mut patterns = Vec::new();for (path, permission) in &filesystem.entries {match permission {FilesystemPermissionToml::Access(access) => {if *access != FileSystemAccessMode::Deny- && contains_glob_chars(remove_trailing_glob_suffix(path))+ && permission_path::contains_glob(remove_trailing_glob_suffix(path), context)?{patterns.push(path.clone());}@@ -713,7 +781,10 @@ fn unsupported_read_write_glob_paths(filesystem: &FilesystemPermissionsToml) ->FilesystemPermissionToml::Scoped(scoped_entries) => {for (subpath, access) in scoped_entries {if *access != FileSystemAccessMode::Deny- && contains_glob_chars(remove_trailing_glob_suffix(subpath))+ && permission_path::contains_glob(+ remove_trailing_glob_suffix(subpath),+ context,+ )?{patterns.push(format!("{path}/{subpath}"));}@@ -721,7 +792,7 @@ fn unsupported_read_write_glob_paths(filesystem: &FilesystemPermissionsToml) ->}}}- patterns+ Ok(patterns)}fn unbounded_unreadable_globstar_paths(filesystem: &FilesystemPermissionsToml) -> Vec<String> {@@ -760,20 +831,6 @@ fn validate_glob_scan_max_depth(max_depth: Option<usize>) -> io::Result<Option<u}}-fn contains_glob_chars(path: &str) -> bool {- contains_glob_chars_for_platform(path, cfg!(windows))-}--fn contains_glob_chars_for_platform(path: &str, is_windows: bool) -> bool {- let normalized_windows_path = if is_windows {- normalize_windows_device_path(path)- } else {- None- };- let path = normalized_windows_path.as_deref().unwrap_or(path);- path.chars().any(|ch| matches!(ch, '*' | '?' | '[' | ']'))-}-fn remove_trailing_glob_suffix(path: &str) -> &str {path.strip_suffix("/**").unwrap_or(path)}@@ -800,95 +857,6 @@ fn parse_special_path(path: &str) -> Option<FileSystemSpecialPath> {}}-fn parse_absolute_path(path: &str) -> io::Result<AbsolutePathBuf> {- parse_absolute_path_for_platform(path, cfg!(windows))-}--fn parse_absolute_path_for_platform(path: &str, is_windows: bool) -> io::Result<AbsolutePathBuf> {- let path_ref = normalize_absolute_path_for_platform(path, is_windows);- if !is_absolute_path_for_platform(path, path_ref.as_ref(), is_windows)- && path != "~"- && !path.starts_with("~/")- {- return Err(io::Error::new(- io::ErrorKind::InvalidInput,- format!("filesystem path `{path}` must be absolute, use `~/...`, or start with `:`"),- ));- }- AbsolutePathBuf::from_absolute_path(path_ref.as_ref())-}--fn is_absolute_path_for_platform(path: &str, normalized_path: &Path, is_windows: bool) -> bool {- if is_windows {- is_windows_absolute_path(path)- || is_windows_absolute_path(&normalized_path.to_string_lossy())- } else {- normalized_path.is_absolute()- }-}--fn normalize_absolute_path_for_platform(path: &str, is_windows: bool) -> Cow<'_, Path> {- if !is_windows {- return Cow::Borrowed(Path::new(path));- }-- match normalize_windows_device_path(path) {- Some(normalized) => Cow::Owned(PathBuf::from(normalized)),- None => Cow::Borrowed(Path::new(path)),- }-}--fn normalize_windows_device_path(path: &str) -> Option<String> {- if let Some(unc) = path.strip_prefix(r"\\?\UNC\") {- return Some(format!(r"\\{unc}"));- }- if let Some(unc) = path.strip_prefix(r"\\.\UNC\") {- return Some(format!(r"\\{unc}"));- }- if let Some(path) = path.strip_prefix(r"\\?\")- && is_windows_drive_absolute_path(path)- {- return Some(path.to_string());- }- if let Some(path) = path.strip_prefix(r"\\.\")- && is_windows_drive_absolute_path(path)- {- return Some(path.to_string());- }- None-}--fn is_windows_absolute_path(path: &str) -> bool {- is_windows_drive_absolute_path(path) || path.starts_with(r"\\")-}--fn is_windows_drive_absolute_path(path: &str) -> bool {- let bytes = path.as_bytes();- bytes.len() >= 3- && bytes[0].is_ascii_alphabetic()- && bytes[1] == b':'- && matches!(bytes[2], b'\\' | b'/')-}--fn parse_relative_subpath(subpath: &str) -> io::Result<PathBuf> {- let path = Path::new(subpath);- if !subpath.is_empty()- && path- .components()- .all(|component| matches!(component, Component::Normal(_)))- {- return Ok(path.to_path_buf());- }-- Err(io::Error::new(- io::ErrorKind::InvalidInput,- format!(- "filesystem subpath `{}` must be a descendant path without `.` or `..` components",- path.display()- ),- ))-}-fn push_warning(startup_warnings: &mut Vec<String>, message: String) {tracing::warn!("{message}");startup_warnings.push(message);diff --git a/codex-rs/core/src/config/permissions_tests.rs b/codex-rs/core/src/config/permissions_tests.rsindex abc185ba18..6b385ff25b 100644--- a/codex-rs/core/src/config/permissions_tests.rs+++ b/codex-rs/core/src/config/permissions_tests.rs@@ -18,19 +18,11 @@ use codex_protocol::permissions::FileSystemSandboxEntry;use codex_protocol::permissions::FileSystemSandboxPolicy;use codex_protocol::permissions::FileSystemSpecialPath;use codex_utils_absolute_path::AbsolutePathBuf;+use codex_utils_path_uri::PathConvention;use pretty_assertions::assert_eq;use std::collections::BTreeMap;use tempfile::TempDir;-#[test]-fn normalize_absolute_path_for_platform_simplifies_windows_verbatim_paths() {- let parsed = normalize_absolute_path_for_platform(- r"\\?\D:\c\x\worktrees\2508\swift-base",- /*is_windows*/ true,- );- assert_eq!(parsed, PathBuf::from(r"D:\c\x\worktrees\2508\swift-base"));-}-#[test]fn windows_verbatim_path_prefix_does_not_count_as_glob_syntax() {assert!(!contains_glob_chars_for_platform(@@ -432,9 +424,9 @@ fn profile_network_proxy_config_keeps_proxy_disabled_for_proxy_policy() {}#[test]-fn compile_permission_profile_workspace_roots_resolves_enabled_entries() -> std::io::Result<()> {+fn compile_permission_profile_resolves_enabled_workspace_roots() -> std::io::Result<()> {let cwd = TempDir::new()?;- let workspace_roots = compile_permission_profile_workspace_roots(+ let compiled = compile_permission_profile(Some(&PermissionsToml {entries: BTreeMap::from([("workspace".to_string(),@@ -453,15 +445,22 @@ fn compile_permission_profile_workspace_roots_resolves_enabled_entries() -> std:)]),}),"workspace",- cwd.path(),+ &ConfigPathContext::new(+ PathConvention::native(),+ Some(PathUri::from_host_native_path(cwd.path())?),+ /*user_home_dir*/ None,+ ),+ /*workspace_write*/ None,+ &mut Vec::new(),)?;assert_eq!(- workspace_roots,- vec![AbsolutePathBuf::resolve_path_against_base(- "backend",- cwd.path()- )]+ compiled.workspace_roots,+ vec![+ PathUri::from_host_native_path(cwd.path())?+ .join("backend")+ .unwrap()+ ]);Ok(())}@@ -489,24 +488,50 @@ docs = "read"let cwd = TempDir::new()?;let docs = cwd.path().join("docs");let mut startup_warnings = Vec::new();+ let context = ConfigPathContext::new(+ PathConvention::native(),+ Some(PathUri::from_host_native_path(cwd.path())?),+ /*user_home_dir*/ None,+ );- let (read_deny_policy, _) =- compile_permission_profile(&permissions, "read_deny", &mut startup_warnings)?;+ let read_deny_policy = compile_permission_profile(+ Some(&permissions),+ "read_deny",+ &context,+ /*workspace_write*/ None,+ &mut startup_warnings,+ )?+ .permission_profile+ .file_system_sandbox_policy();assert_eq!(read_deny_policy.resolve_access_for_local_path_with_cwd(cwd.path(), cwd.path()),FileSystemAccessMode::Deny);- let (write_deny_policy, _) =- compile_permission_profile(&permissions, "write_deny", &mut startup_warnings)?;+ let write_deny_policy = compile_permission_profile(+ Some(&permissions),+ "write_deny",+ &context,+ /*workspace_write*/ None,+ &mut startup_warnings,+ )?+ .permission_profile+ .file_system_sandbox_policy();assert!(!write_deny_policy.has_full_disk_write_access());assert_eq!(write_deny_policy.resolve_access_for_local_path_with_cwd(cwd.path(), cwd.path()),FileSystemAccessMode::Deny);- let (write_read_policy, _) =- compile_permission_profile(&permissions, "write_read", &mut startup_warnings)?;+ let write_read_policy = compile_permission_profile(+ Some(&permissions),+ "write_read",+ &context,+ /*workspace_write*/ None,+ &mut startup_warnings,+ )?+ .permission_profile+ .file_system_sandbox_policy();assert!(!write_read_policy.has_full_disk_write_access());assert_eq!(write_read_policy.resolve_access_for_local_path_with_cwd(&docs, cwd.path()),@@ -541,7 +566,15 @@ fn read_write_glob_warnings_skip_supported_deny_read_globs_and_trailing_subpaths};assert_eq!(- unsupported_read_write_glob_paths(&filesystem),+ unsupported_read_write_glob_paths(+ &filesystem,+ &ConfigPathContext::new(+ PathConvention::native(),+ /*base_dir*/ None,+ /*user_home_dir*/ None,+ )+ )+ .unwrap(),vec!["/tmp/**/*.log".to_string(),":workspace_roots/src/**/*.rs".to_string()@@ -594,8 +627,8 @@ fn glob_scan_max_depth_must_be_positive() {#[test]fn read_write_trailing_glob_suffix_compiles_as_subpath() -> std::io::Result<()> {let mut startup_warnings = Vec::new();- let (file_system_policy, _) = compile_permission_profile(- &PermissionsToml {+ let compiled = compile_permission_profile(+ Some(&PermissionsToml {entries: BTreeMap::from([("workspace".to_string(),PermissionProfileToml {@@ -615,13 +648,19 @@ fn read_write_trailing_glob_suffix_compiles_as_subpath() -> std::io::Result<()>network: None,},)]),- },+ }),"workspace",+ &ConfigPathContext::new(+ PathConvention::native(),+ /*base_dir*/ None,+ /*user_home_dir*/ None,+ ),+ /*workspace_write*/ None,&mut startup_warnings,)?;assert_eq!(- file_system_policy,+ compiled.permission_profile.file_system_sandbox_policy(),FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry {path: FileSystemPath::Special {value: FileSystemSpecialPath::project_roots(Some("docs".into())),@@ -636,8 +675,16 @@ fn read_write_trailing_glob_suffix_compiles_as_subpath() -> std::io::Result<()>#[test]fn read_write_glob_patterns_still_reject_non_subpath_globs() {- let err = compile_read_write_glob_path("src/**/*.rs", FileSystemAccessMode::Read)- .expect_err("non-subpath read/write glob should be rejected");+ let err = compile_read_write_glob_path(+ "src/**/*.rs",+ FileSystemAccessMode::Read,+ &ConfigPathContext::new(+ PathConvention::native(),+ /*base_dir*/ None,+ /*user_home_dir*/ None,+ ),+ )+ .expect_err("non-subpath read/write glob should be rejected");assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);assert!(diff --git a/codex-rs/protocol/src/permissions.rs b/codex-rs/protocol/src/permissions.rsindex 894e1268c3..4e8e469a49 100644--- a/codex-rs/protocol/src/permissions.rs+++ b/codex-rs/protocol/src/permissions.rs@@ -1173,6 +1173,18 @@ impl FileSystemSandboxPolicy {},None => (context.cwd, pattern.as_str()),};+ let convention = if is_windows {+ PathConvention::Windows+ } else {+ PathConvention::Posix+ };+ if LegacyAppPathString::from_string(pattern)+ .to_path_uri(convention)+ .is_err()+ && let Err(error) = root.validate_glob_directory(convention)+ {+ return Some(Err(error.to_string()));+ }Some(root.join(pattern)@@ -1188,73 +1200,27 @@ impl FileSystemSandboxPolicy {/// Replaces symbolic `:workspace_roots` entries with concrete entries for/// each workspace root.pub fn materialize_project_roots_with_workspace_roots(- mut self,+ self,workspace_roots: &[AbsolutePathBuf],) -> Self {- let mut entries = Vec::with_capacity(self.entries.len());- for entry in self.entries {- match entry.path {- FileSystemPath::Special {- value: FileSystemSpecialPath::ProjectRoots { subpath },- } => {- entries.extend(workspace_roots.iter().map(|root| FileSystemSandboxEntry {- path: FileSystemPath::from(match subpath.as_ref() {- Some(subpath) => {- AbsolutePathBuf::resolve_path_against_base(subpath, root.as_path())- }- None => root.clone(),- }),- access: entry.access,- missing_path_behavior: entry.missing_path_behavior,- }));- }- FileSystemPath::GlobPattern { pattern } => {- if let Some(subpath) = parse_project_roots_glob_pattern(&pattern) {- entries.extend(workspace_roots.iter().map(|root| FileSystemSandboxEntry {- path: FileSystemPath::GlobPattern {- pattern: resolve_project_roots_glob_pattern(subpath, root),- },- access: entry.access,- missing_path_behavior: entry.missing_path_behavior,- }));- } else {- entries.push(FileSystemSandboxEntry {- path: FileSystemPath::GlobPattern { pattern },- access: entry.access,- missing_path_behavior: entry.missing_path_behavior,- });- }- }- FileSystemPath::Path { path } => {- entries.push(FileSystemSandboxEntry {- path: path.into(),- access: entry.access,- missing_path_behavior: entry.missing_path_behavior,- });- }- FileSystemPath::Special { value } => {- entries.push(FileSystemSandboxEntry {- path: FileSystemPath::Special { value },- access: entry.access,- missing_path_behavior: entry.missing_path_behavior,- });- }- }- }- self.entries = entries;- self+ let roots = workspace_roots+ .iter()+ .map(PathUri::from_abs_path)+ .collect::<Vec<_>>();+ self.materialize_project_roots_with_path_uris(&roots)}/// Materializes workspace-root entries without projecting executor paths onto the host.- pub fn materialize_project_roots_with_path_uris(mut self, workspace_roots: &[PathUri]) -> Self {- if let Ok(native_workspace_roots) = workspace_roots- .iter()- .map(PathUri::to_abs_path)- .collect::<Result<Vec<_>, _>>()- {- return self.materialize_project_roots_with_workspace_roots(&native_workspace_roots);- }+ /// Legacy home-relative workspace denials clear all grants when their target is unknown.+ pub fn materialize_project_roots_with_path_uris(self, workspace_roots: &[PathUri]) -> Self {+ self.try_materialize_project_roots_with_path_uris(workspace_roots)+ .unwrap_or_else(|| Self::restricted(Vec::new()))+ }+ fn try_materialize_project_roots_with_path_uris(+ mut self,+ workspace_roots: &[PathUri],+ ) -> Option<Self> {let mut entries = Vec::with_capacity(self.entries.len());for entry in self.entries {let (subpath, is_glob) = match &entry.path {@@ -1274,11 +1240,34 @@ impl FileSystemSandboxPolicy {continue;}};+ if entry.access == FileSystemAccessMode::Deny+ && subpath.is_some_and(|subpath| {+ workspace_roots.iter().any(|root| {+ root.infer_path_convention().is_some_and(|convention| {+ convention.home_relative_suffix(subpath).is_some()+ })+ })+ })+ {+ // Older policies could expand these rules outside the workspace.+ // Without a home fact, denying only the workspace would weaken them.+ return None;+ }entries.extend(workspace_roots.iter().filter_map(|root| {- let path = subpath.map_or_else(- || Some(root.clone()),- |subpath| resolve_scoped_workspace_path(root, subpath),- );+ let path = if is_glob+ && root+ .infer_path_convention()+ .is_none_or(|convention| root.validate_glob_directory(convention).is_err())+ {+ // An infallible materializer cannot return an unsafe glob.+ // Use the existing deny-root fallback for unresolvable rules.+ None+ } else {+ subpath.map_or_else(+ || Some(root.clone()),+ |subpath| resolve_scoped_workspace_path(root, subpath),+ )+ };let (path, access) = match path {Some(path) if is_glob => (FileSystemPath::GlobPattern {@@ -1301,24 +1290,20 @@ impl FileSystemSandboxPolicy {}));}self.entries = entries;- self+ Some(self)}/// Preserves symbolic `:workspace_roots` entries while also adding concrete/// entries for each provided workspace root.pub fn with_materialized_project_roots_for_workspace_roots(- mut self,+ self,workspace_roots: &[AbsolutePathBuf],) -> Self {- let materialized = self- .clone()- .materialize_project_roots_with_workspace_roots(workspace_roots);- for entry in materialized.entries {- if !self.entries.contains(&entry) {- self.entries.push(entry);- }- }- self+ let roots = workspace_roots+ .iter()+ .map(PathUri::from_abs_path)+ .collect::<Vec<_>>();+ self.with_materialized_project_roots_for_path_uris(&roots)}pub fn with_additional_readable_roots(@@ -1939,18 +1924,6 @@ fn resolve_entry_path(}}-fn parse_project_roots_glob_pattern(pattern: &str) -> Option<&Path> {- pattern- .strip_prefix(PROJECT_ROOTS_GLOB_PATTERN_PREFIX)- .map(Path::new)-}--fn resolve_project_roots_glob_pattern(subpath: &Path, root: &AbsolutePathBuf) -> String {- AbsolutePathBuf::resolve_path_against_base(subpath, root.as_path())- .to_string_lossy()- .into_owned()-}-fn resolve_candidate_path(path: &Path, cwd: &Path) -> Option<AbsolutePathBuf> {if path.is_absolute() {AbsolutePathBuf::from_absolute_path(path).ok()diff --git a/codex-rs/protocol/src/permissions/target.rs b/codex-rs/protocol/src/permissions/target.rsindex fd6c98d809..5536df375e 100644--- a/codex-rs/protocol/src/permissions/target.rs+++ b/codex-rs/protocol/src/permissions/target.rs@@ -47,12 +47,15 @@ impl FileSystemSandboxPolicy {}/// Preserves workspace-root symbols and adds their executor-owned concrete paths.+ /// Legacy home-relative workspace denials clear all grants when their target is unknown.pub fn with_materialized_project_roots_for_path_uris(mut self, roots: &[PathUri]) -> Self {- for entry in self+ let Some(materialized) = self.clone()- .materialize_project_roots_with_path_uris(roots)- .entries- {+ .try_materialize_project_roots_with_path_uris(roots)+ else {+ return Self::restricted(Vec::new());+ };+ for entry in materialized.entries {if !self.entries.contains(&entry) {self.entries.push(entry);}diff --git a/codex-rs/protocol/src/permissions/target_tests.rs b/codex-rs/protocol/src/permissions/target_tests.rsindex 7e4876c222..bcca625071 100644--- a/codex-rs/protocol/src/permissions/target_tests.rs+++ b/codex-rs/protocol/src/permissions/target_tests.rs@@ -267,3 +267,125 @@ fn remote_workspace_write_keeps_metadata_protected() {}}}++#[test]+fn read_globs_reject_metacharacters_in_home_and_cwd_facts() {+ for prefix in ["file:///home", "file:///C:/Users"] {+ let parent = uri(prefix);+ let directory = parent.join("sam[1]").unwrap();+ for (pattern, cwd, home) in [+ ("~/private/*.key", &parent, Some(&directory)),+ ("private/*.key", &directory, None),+ ] {+ let policy =+ FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::GlobPattern {+ pattern: pattern.into(),+ })]);+ let context = FileSystemSandboxPolicyContext {+ cwd,+ workspace_roots: std::slice::from_ref(&directory),+ user_home_dir: home,+ temporary_directories: None,+ };+ assert!(ReadDenyMatcher::try_new_with_context(&policy, &context).is_err());+ let matcher = ReadDenyMatcher::from_context(&policy, &context).unwrap();+ assert!(+ matcher.is_read_denied_uri(&directory.join("private/a.key").unwrap(), &context)+ );+ }+ }+}++#[test]+fn workspace_globs_fail_closed_on_literal_root_metacharacters_on_every_host() {+ for prefix in ["file:///home", "file:///C:/Users"] {+ let root = uri(prefix).join("sam[1]").unwrap();+ let policy = FileSystemSandboxPolicy::restricted(vec![deny(FileSystemPath::GlobPattern {+ pattern: crate::permissions::project_roots_glob_pattern(std::path::Path::new(+ "private/*.key",+ )),+ })]);+ let materialized = policy+ .clone()+ .materialize_project_roots_with_path_uris(std::slice::from_ref(&root));+ assert_eq!(+ materialized,+ FileSystemSandboxPolicy::restricted(vec![deny(root.clone().into())]),+ );+ if let Ok(native_root) = root.to_abs_path() {+ assert_eq!(+ policy.materialize_project_roots_with_workspace_roots(&[native_root]),+ materialized,+ );+ }+ }+}++#[test]+fn materializing_legacy_home_relative_workspace_denials_removes_all_grants() {+ for (root, home) in [+ ("file:///work/repo", "file:///home/sam"),+ ("file:///C:/work/repo", "file:///D:/Users/sam"),+ ] {+ let root = uri(root);+ let home = uri(home);+ let convention = root.infer_path_convention().unwrap();+ for subpath in ["~", "~/private/*.env", r"~\private", r"~\private\*.env"] {+ if convention.home_relative_suffix(subpath).is_none() {+ continue;+ }+ let denied_path = if subpath.contains('*') {+ FileSystemPath::GlobPattern {+ pattern: crate::permissions::project_roots_glob_pattern(std::path::Path::new(+ subpath,+ )),+ }+ } else {+ FileSystemPath::Special {+ value: FileSystemSpecialPath::ProjectRoots {+ subpath: Some(subpath.into()),+ },+ }+ };+ let policy = FileSystemSandboxPolicy::restricted(vec![+ FileSystemSandboxEntry::new(+ FileSystemPath::Special {+ value: FileSystemSpecialPath::Root,+ },+ FileSystemAccessMode::Read,+ ),+ FileSystemSandboxEntry::new(+ FileSystemPath::Special {+ value: FileSystemSpecialPath::ProjectRoots { subpath: None },+ },+ FileSystemAccessMode::Write,+ ),+ FileSystemSandboxEntry::new(home.clone().into(), FileSystemAccessMode::Write),+ deny(denied_path),+ ]);+ let mut materialized = vec![+ policy+ .clone()+ .materialize_project_roots_with_path_uris(std::slice::from_ref(&root)),+ policy+ .clone()+ .with_materialized_project_roots_for_path_uris(std::slice::from_ref(&root)),+ ];+ if let Ok(native_root) = root.to_abs_path() {+ materialized.push(+ policy+ .clone()+ .materialize_project_roots_with_workspace_roots(std::slice::from_ref(+ &native_root,+ )),+ );+ materialized.push(policy.with_materialized_project_roots_for_workspace_roots(+ std::slice::from_ref(&native_root),+ ));+ }+ for policy in materialized {+ assert_eq!(policy, FileSystemSandboxPolicy::restricted(Vec::new()));+ }+ }+ }+}diff --git a/codex-rs/utils/path-uri/src/config_path.rs b/codex-rs/utils/path-uri/src/config_path.rsindex 518c52d1c1..2db74f9238 100644--- a/codex-rs/utils/path-uri/src/config_path.rs+++ b/codex-rs/utils/path-uri/src/config_path.rs@@ -17,6 +17,18 @@ impl PathUri {base: Option<&Self>,user_home_dir: Option<&Self>,) -> Result<String, LegacyAppPathStringError> {+ Self::resolve_config_path_uri(input, convention, base, user_home_dir)?+ .to_config_path_string(convention)+ }++ /// Resolves and validates configuration text as a URI using only supplied path facts.+ /// Normalizes trailing separators while preserving the path's root.+ pub fn resolve_config_path_uri(+ input: &str,+ convention: PathConvention,+ base: Option<&Self>,+ user_home_dir: Option<&Self>,+ ) -> Result<Self, LegacyAppPathStringError> {Self::validate_config_path_text(input, convention)?;let path = LegacyAppPathString::from_string(input);let resolved = if convention.home_relative_suffix(input).is_some() {@@ -25,6 +37,9 @@ impl PathUri {path: input.to_string(),})?;home.validate_config_path(convention)?;+ if contains_glob_metacharacter(input) {+ home.validate_glob_directory(convention)?;+ }path.resolve_against(home, Some(home))?} else {match path.to_path_uri(convention) {@@ -32,20 +47,48 @@ impl PathUri {Err(error) => {let base = base.ok_or(error)?;base.validate_config_path(convention)?;+ if contains_glob_metacharacter(input) {+ base.validate_glob_directory(convention)?;+ }path.resolve_against(base, /*user_home_dir*/ None)?}}};resolved.validate_config_path(convention)?;// Config paths historically omit trailing separators except at a root.- let resolved = resolved.join(".")?;- let mut rendered = LegacyAppPathString::from_path_uri(&resolved, convention)?.into_string();- if resolved.0.host_str().is_some() && resolved.parent().is_none() {+ Ok(resolved.join(".")?)+ }++ /// Renders an already resolved configuration path with legacy root separators.+ /// Use [`Self::resolve_config_path_uri`] to validate and normalize config input first.+ pub fn to_config_path_string(+ &self,+ convention: PathConvention,+ ) -> Result<String, LegacyAppPathStringError> {+ let mut rendered = LegacyAppPathString::from_path_uri(self, convention)?.into_string();+ if self.0.host_str().is_some() && self.parent().is_none() {rendered.push('\\');}Ok(rendered)}+ /// Checks that a literal directory can be inserted into a glob unchanged.+ /// Rejects metacharacters instead of turning directory names into patterns.+ /// POSIX backslashes would escape the following pattern character.+ pub fn validate_glob_directory(+ &self,+ convention: PathConvention,+ ) -> Result<(), LegacyAppPathStringError> {+ self.validate_config_path(convention)?;+ let path = LegacyAppPathString::from_path_uri(self, convention)?.into_string();+ if contains_glob_metacharacter(&path)+ || convention == PathConvention::Posix && path.contains('\\')+ {+ return Err(LegacyAppPathStringError::UnsupportedConfigPath { path, convention });+ }+ Ok(())+ }+/// Checks that a resolved configuration URI has a lossless native spelling/// in the owning executor's convention. Opaque and ambiguous paths fail.pub fn validate_config_path(@@ -124,6 +167,11 @@ impl PathUri {}}+fn contains_glob_metacharacter(path: &str) -> bool {+ path.chars()+ .any(|character| matches!(character, '*' | '?' | '[' | ']' | '{' | '}'))+}+#[cfg(test)]#[path = "config_path_tests.rs"]mod tests;diff --git a/codex-rs/utils/path-uri/src/config_path_tests.rs b/codex-rs/utils/path-uri/src/config_path_tests.rsindex 934d1dd096..00fb9aa94d 100644--- a/codex-rs/utils/path-uri/src/config_path_tests.rs+++ b/codex-rs/utils/path-uri/src/config_path_tests.rs@@ -5,13 +5,22 @@ use pretty_assertions::assert_eq;#[test]fn configuration_paths_resolve_with_the_supplied_platform_and_home() {- for (convention, base, home, input, expected) in [+ for (convention, base, home, input, expected, expected_uri) in [(PathConvention::Posix,"file:///work/project","file:///home/user","~/a b/雪%/","/home/user/a b/雪%",+ "file:///home/user/a%20b/%E9%9B%AA%25",+ ),+ (+ PathConvention::Posix,+ "file:///work/project",+ "file:///home/user",+ "/",+ "/",+ "file:///",),(PathConvention::Windows,@@ -19,6 +28,23 @@ fn configuration_paths_resolve_with_the_supplied_platform_and_home() {"file:///C:/Users/user",r"..\private\",r"C:\work\private",+ "file:///C:/work/private",+ ),+ (+ PathConvention::Windows,+ "file:///C:/work/project",+ "file:///C:/Users/user",+ r"d:\private\*.env\",+ r"D:\private\*.env",+ "file:///D:/private/*.env",+ ),+ (+ PathConvention::Windows,+ "file:///C:/work/project",+ "file:///C:/Users/user",+ r"D:\",+ r"D:\",+ "file:///D:",),(PathConvention::Windows,@@ -26,6 +52,15 @@ fn configuration_paths_resolve_with_the_supplied_platform_and_home() {"file:///C:/Users/user",r"~\a b\雪%\",r"C:\Users\user\a b\雪%",+ "file:///C:/Users/user/a%20b/%E9%9B%AA%25",+ ),+ (+ PathConvention::Windows,+ "file:///C:/work",+ "file:///C:/Users/user",+ r"\\SERVER\Share\private\*.env\",+ r"\\server\Share\private\*.env",+ "file://server/Share/private/*.env",),(PathConvention::Windows,@@ -33,10 +68,16 @@ fn configuration_paths_resolve_with_the_supplied_platform_and_home() {"file:///C:/Users/user",r"\\server\share",r"\\server\share\",+ "file://server/share",),] {let base = PathUri::parse(base).unwrap();let home = PathUri::parse(home).unwrap();+ assert_eq!(+ PathUri::resolve_config_path_uri(input, convention, Some(&base), Some(&home)),+ Ok(PathUri::parse(expected_uri).unwrap()),+ "{input:?}",+ );assert_eq!(PathUri::resolve_config_path(input, convention, Some(&base), Some(&home)),Ok(expected.to_string()),@@ -91,7 +132,8 @@ fn configuration_paths_reject_ambiguous_or_lossy_denials() {for input in [r"\\server\.\private",r"\\server\..\private",- r"C:\base\a:b\private",+ r"\\.\COM1",+ r"C:\private\file:stream",r"C:\base\a:b\..\private",] {assert!(@@ -128,3 +170,59 @@ fn configuration_paths_reject_ambiguous_or_lossy_denials() {Ok("/private".to_string()),);}++#[test]+fn glob_resolution_rejects_metacharacters_in_used_directory_facts() {+ for (convention, prefix, separator) in [+ (PathConvention::Posix, "/home/", "/"),+ (PathConvention::Windows, r"C:\Users\", r"\"),+ ] {+ let clean = LegacyAppPathString::from_string(format!("{prefix}sam"))+ .to_path_uri(convention)+ .unwrap();+ for name in ["sam[1]", "sam{1,2}"] {+ let directory = LegacyAppPathString::from_string(format!("{prefix}{name}"))+ .to_path_uri(convention)+ .unwrap();+ // The directory remains valid as a literal path, and unused facts+ // cannot reject an absolute pattern supplied by the user.+ let absolute = format!("{prefix}ordinary{separator}*.key");+ let literal = format!("{prefix}{name}{separator}private{separator}key");+ for (input, base, home, expected) in [+ ("private/*.key", &directory, None, None),+ ("~/private/*.key", &clean, Some(&directory), None),+ ("private/key", &directory, None, Some(literal.as_str())),+ (+ absolute.as_str(),+ &directory,+ Some(&directory),+ Some(absolute.as_str()),+ ),+ ] {+ assert_eq!(+ PathUri::resolve_config_path(input, convention, Some(base), home)+ .ok()+ .as_deref(),+ expected,+ "{convention:?}: {name}: {input}",+ );+ }+ }+ assert_eq!(+ PathUri::resolve_config_path("~/private/*.key", convention, Some(&clean), Some(&clean),),+ Ok(format!("{prefix}sam{separator}private{separator}*.key")),+ );+ }+}++#[test]+fn glob_directory_validation_rejects_posix_escape_characters() {+ let directory = LegacyAppPathString::from_string(r"/home/sam\name")+ .to_path_uri(PathConvention::Posix)+ .unwrap();+ assert!(+ directory+ .validate_glob_directory(PathConvention::Posix)+ .is_err()+ );+}