Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Add portable project trust lookup APIs (#47620)

Sean Huang13869ca39e7a
diff --git a/codex-rs/config/src/config_toml.rs b/codex-rs/config/src/config_toml.rs
index e15bb847b6..7d966891a3 100644
--- a/codex-rs/config/src/config_toml.rs
+++ b/codex-rs/config/src/config_toml.rs
@@ -55,7 +55,6 @@ use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_utils_absolute_path::AbsolutePathBuf;
-use codex_utils_path::normalize_for_path_comparison;
use codex_utils_path_uri::Platform;
use schemars::JsonSchema;
use serde::Deserialize;
@@ -866,70 +865,12 @@ impl ConfigToml {
resolved_cwd: &Path,
repo_root: Option<&Path>,
) -> Option<ProjectConfig> {
- let projects = self.projects.as_ref()?;
-
- for normalized_cwd in normalized_project_lookup_keys(resolved_cwd) {
- if let Some(project_config) = project_config_for_lookup_key(projects, &normalized_cwd) {
- return Some(project_config);
- }
- }
-
- if let Some(repo_root) = repo_root {
- for normalized_repo_root in normalized_project_lookup_keys(repo_root) {
- if let Some(project_config_for_root) =
- project_config_for_lookup_key(projects, &normalized_repo_root)
- {
- return Some(project_config_for_root);
- }
- }
- }
-
- None
- }
-}
-
-/// Canonicalize the path and convert it to a string to be used as a key in the
-/// projects trust map. On Windows, strips UNC, when possible, to try to ensure
-/// that different paths that point to the same location have the same key.
-fn normalized_project_lookup_keys(path: &Path) -> Vec<String> {
- let normalized_path = normalize_project_lookup_key(path.to_string_lossy().to_string());
- let normalized_canonical_path = normalize_project_lookup_key(
- normalize_for_path_comparison(path)
- .unwrap_or_else(|_| path.to_path_buf())
- .to_string_lossy()
- .to_string(),
- );
- if normalized_path == normalized_canonical_path {
- vec![normalized_canonical_path]
- } else {
- vec![normalized_canonical_path, normalized_path]
- }
-}
-
-fn normalize_project_lookup_key(key: String) -> String {
- if cfg!(windows) {
- key.to_ascii_lowercase()
- } else {
- key
- }
-}
-
-fn project_config_for_lookup_key(
- projects: &HashMap<String, ProjectConfig>,
- lookup_key: &str,
-) -> Option<ProjectConfig> {
- if let Some(project_config) = projects.get(lookup_key) {
- return Some(project_config.clone());
+ self.projects.as_ref()?;
+ self.get_active_project_for_lookup(&crate::ProjectTrustLookup::from_native(
+ resolved_cwd,
+ repo_root,
+ ))
}
-
- let mut normalized_matches: Vec<_> = projects
- .iter()
- .filter(|(key, _)| normalize_project_lookup_key((*key).clone()) == lookup_key)
- .collect();
- normalized_matches.sort_by_key(|(key, _)| *key);
- normalized_matches
- .first()
- .map(|(_, project_config)| (**project_config).clone())
}
pub fn validate_reserved_model_provider_ids(
diff --git a/codex-rs/config/src/lib.rs b/codex-rs/config/src/lib.rs
index 6da94a301d..a999fe64f2 100644
--- a/codex-rs/config/src/lib.rs
+++ b/codex-rs/config/src/lib.rs
@@ -33,6 +33,7 @@ pub mod permissions_toml;
mod plugin_edit;
pub mod profile_toml;
mod project_root_markers;
+mod project_trust;
mod requirements_exec_policy;
mod requirements_layers;
pub mod schema;
@@ -188,6 +189,7 @@ pub use plugin_edit::clear_user_plugin;
pub use plugin_edit::set_user_plugin_enabled;
pub use project_root_markers::default_project_root_markers;
pub use project_root_markers::project_root_markers_from_config;
+pub use project_trust::ProjectTrustLookup;
pub use requirements_exec_policy::RequirementsExecPolicyDecisionToml;
pub use requirements_exec_policy::RequirementsExecPolicyParseError;
pub use requirements_exec_policy::RequirementsExecPolicyPatternTokenToml;
diff --git a/codex-rs/config/src/project_trust.rs b/codex-rs/config/src/project_trust.rs
new file mode 100644
index 0000000000..d12e5702ab
--- /dev/null
+++ b/codex-rs/config/src/project_trust.rs
@@ -0,0 +1,97 @@
+//! Match merged project settings against ordered native path spellings.
+
+use crate::config_toml::ConfigToml;
+use crate::config_toml::ProjectConfig;
+use codex_utils_path::normalize_for_path_comparison;
+use codex_utils_path_uri::PathConvention;
+use std::path::Path;
+
+/// Ordered project lookup keys for one executor working directory.
+///
+/// Resolve this independently of configuration layers, then apply it after all
+/// local and cloud projects maps have been merged. Cwd entries, including an
+/// entry without a trust level, take precedence over repository-root entries.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct ProjectTrustLookup {
+ convention: PathConvention,
+ keys: Vec<String>,
+}
+
+impl ProjectTrustLookup {
+ pub(crate) fn from_native(cwd: &Path, repo_root: Option<&Path>) -> Self {
+ Self::from_paths(
+ PathConvention::native(),
+ std::iter::once(cwd).chain(repo_root).map(|path| {
+ (
+ path.to_string_lossy().into_owned(),
+ normalize_for_path_comparison(path)
+ .ok()
+ .map(|path| path.to_string_lossy().into_owned()),
+ )
+ }),
+ )
+ }
+
+ /// Build lookup keys from `(original, canonical)` native path spellings.
+ ///
+ /// Supply the cwd first, followed by the optional repository root. Each
+ /// canonical spelling is tried before its original spelling; `None` uses
+ /// only the original. This method performs no filesystem access or path
+ /// resolution. Callers must supply executor-normalized canonical spellings,
+ /// including Windows extended-length prefixes and WSL mounted-drive folding
+ /// where applicable. Original spellings remain literal. Windows keys are
+ /// matched without ASCII case distinctions; POSIX keys remain case-sensitive.
+ pub fn from_paths(
+ convention: PathConvention,
+ paths: impl IntoIterator<Item = (String, Option<String>)>,
+ ) -> Self {
+ let mut keys = Vec::new();
+ for (original, canonical) in paths {
+ let original = normalize_lookup_key(&original, convention);
+ let canonical = canonical
+ .map(|key| normalize_lookup_key(&key, convention))
+ .unwrap_or_else(|| original.clone());
+ if canonical != original {
+ keys.push(canonical);
+ }
+ keys.push(original);
+ }
+ Self { convention, keys }
+ }
+}
+
+impl ConfigToml {
+ /// Select the active project from the final merged projects map.
+ pub fn get_active_project_for_lookup(
+ &self,
+ lookup: &ProjectTrustLookup,
+ ) -> Option<ProjectConfig> {
+ let projects = self.projects.as_ref()?;
+ for key in &lookup.keys {
+ if let Some(project) = projects.get(key) {
+ return Some(project.clone());
+ }
+ // Preserve native exact-key preference and deterministic selection
+ // when multiple Windows keys differ only in ASCII case.
+ if let Some((_, project)) = projects
+ .iter()
+ .filter(|(candidate, _)| normalize_lookup_key(candidate, lookup.convention) == *key)
+ .min_by_key(|(candidate, _)| *candidate)
+ {
+ return Some(project.clone());
+ }
+ }
+ None
+ }
+}
+
+fn normalize_lookup_key(key: &str, convention: PathConvention) -> String {
+ match convention {
+ PathConvention::Windows => key.to_ascii_lowercase(),
+ PathConvention::Posix => key.to_owned(),
+ }
+}
+
+#[cfg(test)]
+#[path = "project_trust_tests.rs"]
+mod tests;
diff --git a/codex-rs/config/src/project_trust_tests.rs b/codex-rs/config/src/project_trust_tests.rs
new file mode 100644
index 0000000000..672209bf6a
--- /dev/null
+++ b/codex-rs/config/src/project_trust_tests.rs
@@ -0,0 +1,81 @@
+//! Exercises project-key precedence and map matching across path conventions.
+
+use super::*;
+use codex_protocol::config_types::TrustLevel;
+use pretty_assertions::assert_eq;
+
+fn config_with_projects(entries: &[(&str, Option<TrustLevel>)]) -> ConfigToml {
+ ConfigToml {
+ projects: Some(
+ entries
+ .iter()
+ .map(|(key, trust_level)| {
+ (
+ key.to_string(),
+ ProjectConfig {
+ trust_level: *trust_level,
+ },
+ )
+ })
+ .collect(),
+ ),
+ ..Default::default()
+ }
+}
+
+fn assert_lookup_order(lookup: &ProjectTrustLookup, entries: &[(&str, Option<TrustLevel>)]) {
+ let mut config = config_with_projects(entries);
+ for (key, trust_level) in entries {
+ assert_eq!(
+ config.get_active_project_for_lookup(lookup),
+ Some(ProjectConfig {
+ trust_level: *trust_level
+ }),
+ );
+ config.projects.as_mut().unwrap().remove(*key);
+ }
+ assert_eq!(config.get_active_project_for_lookup(lookup), None);
+ assert_eq!(
+ ConfigToml::default().get_active_project_for_lookup(lookup),
+ None
+ );
+}
+
+#[test]
+fn posix_lookup_preserves_cwd_root_alias_order_and_case() {
+ let lookup = ProjectTrustLookup::from_paths(
+ PathConvention::Posix,
+ [
+ ("/alias/src".into(), Some("/repo/src".into())),
+ ("/alias".into(), Some("/repo".into())),
+ ],
+ );
+ assert_lookup_order(
+ &lookup,
+ &[
+ ("/repo/src", None),
+ ("/alias/src", Some(TrustLevel::Trusted)),
+ ("/repo", Some(TrustLevel::Untrusted)),
+ ("/alias", Some(TrustLevel::Trusted)),
+ ],
+ );
+ assert_eq!(
+ config_with_projects(&[("/Repo/src", Some(TrustLevel::Trusted))])
+ .get_active_project_for_lookup(&lookup),
+ None,
+ );
+}
+
+#[test]
+fn windows_prefers_exact_normalized_key_then_sorted_aliases() {
+ let lookup =
+ ProjectTrustLookup::from_paths(PathConvention::Windows, [(r"C:\Repo".into(), None)]);
+ assert_lookup_order(
+ &lookup,
+ &[
+ (r"c:\repo", Some(TrustLevel::Trusted)),
+ (r"C:\REPO", Some(TrustLevel::Untrusted)),
+ (r"C:\Repo", Some(TrustLevel::Trusted)),
+ ],
+ );
+}
diff --git a/codex-rs/core/src/git_info_tests.rs b/codex-rs/core/src/git_info_tests.rs
index 8cadb3b7ba..4e3f099540 100644
--- a/codex-rs/core/src/git_info_tests.rs
+++ b/codex-rs/core/src/git_info_tests.rs
@@ -22,13 +22,17 @@ use codex_git_utils::get_git_repo_root;
use codex_git_utils::get_has_changes_in_repo;
use codex_git_utils::git_diff_to_remote;
use codex_git_utils::recent_commits;
-use codex_git_utils::resolve_root_git_project_for_trust;
+use codex_git_utils::resolve_root_git_project_uri_for_trust;
+// Existing trust fixtures check both entry points through this shared wrapper.
+use self::resolve_native_and_portable_trust_roots as resolve_root_git_project_for_trust;
+use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path::normalize_for_path_comparison;
use codex_utils_path_uri::PathUri;
use core_test_support::PathBufExt;
use core_test_support::PathExt;
use core_test_support::skip_if_sandbox;
use pretty_assertions::assert_eq;
+use std::collections::HashMap;
use std::fs;
use std::io;
#[cfg(unix)]
@@ -38,13 +42,36 @@ use std::path::PathBuf;
use tempfile::TempDir;
use tokio::process::Command;
+#[derive(Default)]
struct MetadataOverrideFileSystem {
- path: PathUri,
+ path: Option<PathUri>,
replacement: Option<PathBuf>,
canonical_overrides: Vec<(PathUri, PathUri)>,
+ // Optional virtual filesystem; entries without contents are directories.
+ entries: Option<HashMap<String, Option<String>>>,
}
impl MetadataOverrideFileSystem {
+ fn with_entries(entries: impl IntoIterator<Item = (PathUri, Option<String>)>) -> Self {
+ Self {
+ entries: Some(
+ entries
+ .into_iter()
+ .map(|(path, contents)| (path.to_string(), contents))
+ .collect(),
+ ),
+ ..Default::default()
+ }
+ }
+
+ fn entry(&self, path: &PathUri) -> Option<FileSystemResult<&Option<String>>> {
+ self.entries.as_ref().map(|entries| {
+ entries
+ .get(path.to_url().as_str())
+ .ok_or_else(|| io::ErrorKind::NotFound.into())
+ })
+ }
+
fn unsupported<T>() -> FileSystemResult<T> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
@@ -60,6 +87,9 @@ impl ExecutorFileSystem for MetadataOverrideFileSystem {
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, PathUri> {
Box::pin(async move {
+ if let Some(entry) = self.entry(path) {
+ return entry.map(|_| path.clone());
+ }
if let Some((_, canonical)) = self
.canonical_overrides
.iter()
@@ -78,8 +108,14 @@ impl ExecutorFileSystem for MetadataOverrideFileSystem {
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
Box::pin(async move {
+ if let Some(entry) = self.entry(path) {
+ return entry?
+ .as_ref()
+ .map(|contents| contents.as_bytes().to_vec())
+ .ok_or_else(|| io::ErrorKind::IsADirectory.into());
+ }
#[cfg(unix)]
- if path == &self.path
+ if Some(path) == self.path.as_ref()
&& let Some(replacement) = &self.replacement
{
let local_path = path.to_abs_path()?;
@@ -124,7 +160,20 @@ impl ExecutorFileSystem for MetadataOverrideFileSystem {
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, FileMetadata> {
Box::pin(async move {
- if path == &self.path && self.replacement.is_none() {
+ if let Some(entry) = self.entry(path) {
+ let contents = entry?;
+ return Ok(FileMetadata {
+ is_directory: contents.is_none(),
+ is_file: contents.is_some(),
+ is_symlink: false,
+ size: contents
+ .as_ref()
+ .map_or(/*default*/ 0, |contents| contents.len() as u64),
+ created_at_ms: 0,
+ modified_at_ms: 0,
+ });
+ }
+ if Some(path) == self.path.as_ref() && self.replacement.is_none() {
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"injected metadata failure",
@@ -172,6 +221,27 @@ impl ExecutorFileSystem for MetadataOverrideFileSystem {
}
}
+async fn resolve_native_and_portable_trust_roots(
+ fs: &dyn ExecutorFileSystem,
+ cwd: &AbsolutePathBuf,
+) -> Option<AbsolutePathBuf> {
+ let native = codex_git_utils::resolve_root_git_project_for_trust(fs, cwd).await;
+ let cwd_uri = PathUri::from_abs_path(cwd);
+ let portable = resolve_root_git_project_uri_for_trust(fs, &cwd_uri).await;
+ if cwd_uri.is_opaque() {
+ // Opaque URI components cannot provide ancestry, but native lookup still can.
+ assert_eq!(portable, None);
+ } else {
+ assert_eq!(
+ portable.map(|path| path.to_url()),
+ native
+ .as_ref()
+ .map(|path| PathUri::from_abs_path(path).to_url()),
+ );
+ }
+ native
+}
+
// Helper function to create a test git repository
async fn create_test_git_repo(temp_dir: &TempDir) -> PathBuf {
let repo_path = temp_dir.path().join("repo");
@@ -685,9 +755,8 @@ async fn resolve_root_git_project_for_trust_ignores_metadata_errors() {
std::fs::write(proj.join(".git/HEAD"), "ref: refs/heads/main\n").unwrap();
std::fs::create_dir_all(&nested).unwrap();
let fs = MetadataOverrideFileSystem {
- path: PathUri::from_abs_path(&nested.join(".git").abs()),
- replacement: None,
- canonical_overrides: Vec::new(),
+ path: Some(PathUri::from_abs_path(&nested.join(".git").abs())),
+ ..Default::default()
};
assert_eq!(
diff --git a/codex-rs/core/src/worktree_trust_tests.rs b/codex-rs/core/src/worktree_trust_tests.rs
index 4dc69a5485..9c7abdb6c5 100644
--- a/codex-rs/core/src/worktree_trust_tests.rs
+++ b/codex-rs/core/src/worktree_trust_tests.rs
@@ -1,8 +1,11 @@
use super::MetadataOverrideFileSystem;
use super::create_test_git_repo;
+use super::resolve_root_git_project_for_trust;
use super::write_linked_worktree_metadata;
use codex_exec_server::LOCAL_FS;
-use codex_git_utils::resolve_root_git_project_for_trust;
+use codex_git_utils::resolve_root_git_project_uri_for_trust;
+#[cfg(unix)]
+use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path::normalize_for_path_comparison;
use codex_utils_path_uri::PathUri;
use core_test_support::PathBufExt;
@@ -11,6 +14,74 @@ use std::fs;
use tempfile::TempDir;
use tokio::process::Command;
+#[tokio::test]
+async fn portable_trust_roots_support_posix_windows_drive_and_unc_paths() {
+ for root in [
+ "file:///repo%20with%20spaces",
+ "file:///C:/Repo%20%23",
+ "file://server/share/Repo%20%23",
+ ] {
+ let root = PathUri::parse(root).unwrap();
+ let checkout = root.parent().unwrap().join("checkout").unwrap();
+ let dot_git = root.join(".git").unwrap();
+ let git_dir = dot_git.join("worktrees/dev").unwrap();
+ let checkout_dot_git = checkout.join(".git").unwrap();
+ let fs = MetadataOverrideFileSystem::with_entries([
+ (root.join("src").unwrap(), None),
+ (dot_git.clone(), None),
+ (
+ dot_git.join("HEAD").unwrap(),
+ Some("ref: refs/heads/main\n".into()),
+ ),
+ (checkout.clone(), None),
+ (checkout.join("src").unwrap(), None),
+ (git_dir.clone(), None),
+ (
+ checkout_dot_git.clone(),
+ Some(format!(
+ "gitdir: {}\n",
+ git_dir.inferred_native_path_string()
+ )),
+ ),
+ (
+ git_dir.join("gitdir").unwrap(),
+ Some(checkout_dot_git.inferred_native_path_string()),
+ ),
+ (git_dir.join("commondir").unwrap(), Some("../..".into())),
+ ]);
+ for cwd in [root.join("src").unwrap(), checkout.join("src").unwrap()] {
+ assert_eq!(
+ resolve_root_git_project_uri_for_trust(&fs, &cwd)
+ .await
+ .map(|path| path.to_url()),
+ Some(root.to_url().clone()),
+ );
+ }
+ }
+}
+
+#[cfg(unix)]
+#[tokio::test]
+async fn opaque_uri_ancestry_remains_available_only_to_native_trust_lookup() {
+ // This POSIX spelling would imply a Windows drive in an ordinary URI.
+ let root = AbsolutePathBuf::try_from("/C:/project").unwrap();
+ let cwd = root.join("src");
+ let cwd_uri = PathUri::from_abs_path(&cwd);
+ assert!(cwd_uri.is_opaque());
+ let fs = MetadataOverrideFileSystem::with_entries([
+ (cwd_uri.clone(), None),
+ (PathUri::from_abs_path(&root.join(".git")), None),
+ (
+ PathUri::from_abs_path(&root.join(".git/HEAD")),
+ Some("ref: refs/heads/main\n".into()),
+ ),
+ ]);
+ assert_eq!(
+ resolve_root_git_project_for_trust(&fs, &cwd).await,
+ Some(root)
+ );
+}
+
#[tokio::test]
async fn resolve_root_git_project_for_trust_validates_main_checkout_ownership() {
let tmp = TempDir::new().unwrap();
@@ -51,12 +122,12 @@ async fn resolve_root_git_project_for_trust_rejects_dot_git_swapped_after_stat()
fs::create_dir_all(&attacker).unwrap();
fs::copy(checkout.join(".git"), attacker.join(".git")).unwrap();
let fs = MetadataOverrideFileSystem {
- path: PathUri::from_abs_path(&attacker.join(".git").abs()),
+ path: Some(PathUri::from_abs_path(&attacker.join(".git").abs())),
replacement: Some(checkout.join(".git")),
- canonical_overrides: Vec::new(),
+ ..Default::default()
};
assert_eq!(
- resolve_root_git_project_for_trust(&fs, &attacker.abs()).await,
+ codex_git_utils::resolve_root_git_project_for_trust(&fs, &attacker.abs()).await,
None
);
assert!(
@@ -84,8 +155,6 @@ async fn resolve_root_git_project_for_trust_preserves_canonical_checkout_case()
("file:///C:/REAL", None),
] {
let fs = MetadataOverrideFileSystem {
- path: PathUri::from_abs_path(&tmp.path().join("unused").abs()),
- replacement: None,
canonical_overrides: vec![
(
registered_uri.clone(),
@@ -96,6 +165,7 @@ async fn resolve_root_git_project_for_trust_preserves_canonical_checkout_case()
PathUri::parse(canonical_attacker).unwrap(),
),
],
+ ..Default::default()
};
assert_eq!(
resolve_root_git_project_for_trust(&fs, &attacker.abs()).await,
diff --git a/codex-rs/exec-server/tests/environment_config.rs b/codex-rs/exec-server/tests/environment_config.rs
index 5df1bea910..ed456f505d 100644
--- a/codex-rs/exec-server/tests/environment_config.rs
+++ b/codex-rs/exec-server/tests/environment_config.rs
@@ -22,15 +22,17 @@ async fn remote_environment_reads_projected_executor_config() -> anyhow::Result<
AbsolutePathBuf::from_absolute_path(std::fs::canonicalize(server.codex_home())?)?;
let config_file = codex_home.join(CONFIG_TOML_FILE);
let project = codex_home.join("project");
+ let nested = project.join("nested");
let dot_codex = project.join(".codex");
tokio::fs::create_dir_all(dot_codex.as_path()).await?;
tokio::fs::write(project.join(".project-root").as_path(), "").await?;
let project_key = toml::Value::String(project_trust_key(project.as_path())).to_string();
+ let nested_key = toml::Value::String(project_trust_key(nested.as_path())).to_string();
+ let projects_toml =
+ format!("[projects.{project_key}]\ntrust_level = \"trusted\"\n[projects.{nested_key}]\n");
tokio::fs::write(
&config_file,
- format!(
- "project_root_markers = [\".project-root\"]\n[projects.{project_key}]\ntrust_level = \"trusted\""
- ),
+ format!("project_root_markers = [\".project-root\"]\n{projects_toml}"),
)
.await?;
tokio::fs::write(
@@ -93,6 +95,27 @@ unselected = "do not return"
}
);
+ let mut expected_projects = response;
+ expected_projects.config.layers[0] = EnvironmentConfigLayer {
+ source: format_config_layer_source(
+ &ConfigLayerSource::User {
+ file: config_file,
+ profile: None,
+ },
+ CONFIG_TOML_FILE,
+ ),
+ base_dir: PathUri::from_abs_path(&codex_home),
+ toml: toml::to_string(&toml::from_str::<toml::Value>(&projects_toml)?)?,
+ };
+ let projects = environment
+ .read_environment_config(EnvironmentConfigReadParams {
+ cwd: PathUri::from_abs_path(&project),
+ config_paths: vec![vec!["projects".to_string()]],
+ requirements_paths: Vec::new(),
+ })
+ .await?;
+ assert_eq!(projects, expected_projects);
+
server.shutdown().await?;
Ok(())
}
diff --git a/codex-rs/git-utils/src/lib.rs b/codex-rs/git-utils/src/lib.rs
index ec0f4128b7..495a459fb0 100644
--- a/codex-rs/git-utils/src/lib.rs
+++ b/codex-rs/git-utils/src/lib.rs
@@ -52,6 +52,7 @@ pub use operations::git_config_override_env;
pub use platform::create_symlink;
pub use status::get_has_changes_in_repo;
pub use trust::resolve_root_git_project_for_trust;
+pub use trust::resolve_root_git_project_uri_for_trust;
pub use worktree::RepositoryIdentity;
pub use worktree::linked_worktree_cwds;
pub use worktree::repository_identity;
diff --git a/codex-rs/git-utils/src/trust.rs b/codex-rs/git-utils/src/trust.rs
index 34dfdfb244..c9cd4a4565 100644
--- a/codex-rs/git-utils/src/trust.rs
+++ b/codex-rs/git-utils/src/trust.rs
@@ -1,5 +1,8 @@
+//! Resolve repository trust roots through local or remote filesystem access.
+
use codex_file_system::ExecutorFileSystem;
use codex_file_system::FindUpErrorPolicy;
+use codex_file_system::find_nearest_ancestor_with_markers;
use codex_file_system::find_nearest_native_ancestor_with_markers;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
@@ -14,7 +17,59 @@ pub async fn resolve_root_git_project_for_trust(
fs: &dyn ExecutorFileSystem,
cwd: &AbsolutePathBuf,
) -> Option<AbsolutePathBuf> {
- let cwd_uri = PathUri::from_abs_path(cwd);
+ match resolve_root(fs, TrustPath::Native(cwd.clone())).await? {
+ TrustPath::Native(root) => Some(root),
+ TrustPath::Uri(_) => None,
+ }
+}
+
+/// Resolve the main repository's trust root using the executor's path convention.
+///
+/// Uses existing filesystem operations so this also works with independently
+/// deployed executors. Native callers should use [`resolve_root_git_project_for_trust`]
+/// to preserve paths whose URI representation is opaque.
+pub async fn resolve_root_git_project_uri_for_trust(
+ fs: &dyn ExecutorFileSystem,
+ cwd: &PathUri,
+) -> Option<PathUri> {
+ resolve_root(fs, TrustPath::Uri(cwd.clone()))
+ .await
+ .map(|root| root.uri())
+}
+
+// Keep native ancestry native: an opaque URI cannot supply parents or children.
+// Everything after ancestry discovery shares the same repository validation.
+#[derive(Clone)]
+enum TrustPath {
+ Native(AbsolutePathBuf),
+ Uri(PathUri),
+}
+
+impl TrustPath {
+ fn uri(&self) -> PathUri {
+ match self {
+ Self::Native(path) => PathUri::from_abs_path(path),
+ Self::Uri(path) => path.clone(),
+ }
+ }
+
+ fn parent(&self) -> Option<Self> {
+ match self {
+ Self::Native(path) => path.parent().map(Self::Native),
+ Self::Uri(path) => path.parent().map(Self::Uri),
+ }
+ }
+
+ fn join(&self, component: &str) -> Option<Self> {
+ match self {
+ Self::Native(path) => Some(Self::Native(path.join(component))),
+ Self::Uri(path) => path.join(component).ok().map(Self::Uri),
+ }
+ }
+}
+
+async fn resolve_root(fs: &dyn ExecutorFileSystem, cwd: TrustPath) -> Option<TrustPath> {
+ let cwd_uri = cwd.uri();
let base = match fs
.get_metadata(&cwd_uri, Default::default(), /*sandbox*/ None)
.await
@@ -24,28 +79,38 @@ pub async fn resolve_root_git_project_for_trust(
};
let mut base = base;
let repo_root = loop {
- let candidate = find_nearest_native_ancestor_with_markers(
- fs,
- &base,
- vec![".git".to_string()],
- FindUpErrorPolicy::Ignore,
- /*sandbox*/ None,
- )
- .await
- .ok()??;
- let dot_git = candidate.join(".git");
- let metadata = fs
- .get_metadata(
- &PathUri::from_abs_path(&dot_git),
- Default::default(),
+ let candidate = match &base {
+ TrustPath::Native(path) => find_nearest_native_ancestor_with_markers(
+ fs,
+ path,
+ vec![".git".to_string()],
+ FindUpErrorPolicy::Ignore,
/*sandbox*/ None,
)
.await
+ .ok()?
+ .map(TrustPath::Native)?,
+ TrustPath::Uri(path) => TrustPath::Uri(
+ find_nearest_ancestor_with_markers(
+ fs,
+ path,
+ vec![".git".to_string()],
+ FindUpErrorPolicy::Ignore,
+ /*sandbox*/ None,
+ )
+ .await
+ .ok()??,
+ ),
+ };
+ let dot_git = candidate.join(".git")?;
+ let metadata = fs
+ .get_metadata(&dot_git.uri(), Default::default(), /*sandbox*/ None)
+ .await
.ok()?;
if !metadata.is_directory
|| fs
.get_metadata(
- &PathUri::from_abs_path(&dot_git.join("HEAD")),
+ &dot_git.join("HEAD")?.uri(),
Default::default(),
/*sandbox*/ None,
)
@@ -56,8 +121,7 @@ pub async fn resolve_root_git_project_for_trust(
}
base = candidate.parent()?;
};
- let dot_git = repo_root.join(".git");
- let dot_git_uri = PathUri::from_abs_path(&dot_git);
+ let dot_git_uri = repo_root.join(".git")?.uri();
let dot_git_metadata = fs
.get_metadata(&dot_git_uri, Default::default(), /*sandbox*/ None)
.await
@@ -73,7 +137,10 @@ pub async fn resolve_root_git_project_for_trust(
}
let git_dir_uri = read_gitdir_file(fs, &dot_git_uri).await?;
- let git_dir_path = git_dir_uri.to_abs_path().ok()?;
+ let git_dir_path = match &repo_root {
+ TrustPath::Native(_) => TrustPath::Native(git_dir_uri.to_abs_path().ok()?),
+ TrustPath::Uri(_) => TrustPath::Uri(git_dir_uri.clone()),
+ };
let git_dir_metadata = fs
.get_metadata(&git_dir_uri, Default::default(), /*sandbox*/ None)
.await
@@ -112,7 +179,7 @@ pub async fn resolve_root_git_project_for_trust(
}
let linked_common_dir_uri = canonical_git_dir_uri.join_native_bytes(commondir).ok()?;
let registered_checkout_uri = worktree_dot_git_uri.parent()?;
- let checkout_uri = PathUri::from_abs_path(&repo_root);
+ let checkout_uri = repo_root.uri();
// Compare checkout directories, not the final .git entries. Following a
// substituted .git symlink must never turn an unrelated checkout into the
// registered one, even if it is swapped after the metadata check above.
@@ -134,7 +201,7 @@ pub async fn resolve_root_git_project_for_trust(
// checkout made with --separate-git-dir may have a regular .git pointer.
let common_dir = git_dir_path.parent()?.parent()?;
let main_root = common_dir.parent()?;
- let main_dot_git_uri = PathUri::from_abs_path(&main_root.join(".git"));
+ let main_dot_git_uri = main_root.join(".git")?.uri();
let main_metadata = fs
.get_metadata(&main_dot_git_uri, Default::default(), /*sandbox*/ None)
.await