diff --git a/crates/fs/src/fs.rs b/crates/fs/src/fs.rs index de841474cf1..22c2280008a 100644 --- a/crates/fs/src/fs.rs +++ b/crates/fs/src/fs.rs @@ -161,6 +161,10 @@ pub trait Fs: Send + Sync { async fn is_file(&self, path: &Path) -> bool; async fn is_dir(&self, path: &Path) -> bool; async fn metadata(&self, path: &Path) -> Result>; + /// Whether `path` is a symlink, without following it or needing read access to it. + /// On Windows, junctions and other name surrogate reparse points (e.g. mount points) count too. + /// Errors when `path` does not exist. + async fn is_symlink(&self, path: &Path) -> Result; async fn read_link(&self, path: &Path) -> Result; async fn read_dir( &self, @@ -1281,6 +1285,15 @@ impl Fs for RealFs { })) } + async fn is_symlink(&self, path: &Path) -> Result { + let path = path.to_owned(); + let metadata = self + .executor + .spawn(async move { std::fs::symlink_metadata(&path) }) + .await?; + Ok(metadata.file_type().is_symlink()) + } + async fn read_link(&self, path: &Path) -> Result { let path = path.to_owned(); let path = self @@ -3681,6 +3694,16 @@ impl Fs for FakeFs { } } + async fn is_symlink(&self, path: &Path) -> Result { + self.simulate_random_delay().await; + let path = normalize_path(path); + let mut state = self.state.lock(); + let (entry, _) = state + .try_entry(&path, false) + .with_context(|| format!("path does not exist: {path:?}"))?; + Ok(entry.is_symlink()) + } + async fn read_link(&self, path: &Path) -> Result { self.simulate_random_delay().await; let path = normalize_path(path); diff --git a/crates/project/src/trusted_worktrees.rs b/crates/project/src/trusted_worktrees.rs index b3493555498..08171069688 100644 --- a/crates/project/src/trusted_worktrees.rs +++ b/crates/project/src/trusted_worktrees.rs @@ -41,12 +41,13 @@ use client::ProjectId; use collections::{HashMap, HashSet}; +use fs::Fs; use gpui::{App, AppContext as _, Context, Entity, EventEmitter, Global, Task, WeakEntity}; use remote::RemoteConnectionIdentity; use rpc::{AnyProtoClient, proto}; use settings::{Settings as _, WorktreeId}; use std::{ - path::{Path, PathBuf}, + path::{Component, Path, PathBuf, Prefix}, sync::Arc, }; use util::debug_panic; @@ -60,6 +61,46 @@ pub fn init(db_trusted_paths: DbTrustedPaths, cx: &mut App) { } } +/// Returns the on-disk spelling of `path` when it differs from `path` only by ASCII case. +/// +/// Paths through a symlink or junction are skipped, as resolving those may land in another +/// directory whose name differs only by case. Components are checked from the root, so nothing +/// under a link is looked up. Only local drive paths are resolved, `C:\` and `\\?\C:\` alike: +/// paths with a component that cannot be checked are skipped, as are UNC paths (network shares, +/// `\\wsl.localhost`). +async fn on_disk_spelling(fs: &dyn Fs, path: &Path) -> Option { + let Some(Component::Prefix(prefix)) = path.components().next() else { + return None; + }; + // Local drives, including in the extended-length `\\?\C:\` form, which paths keep e.g. when + // longer than `MAX_PATH`. + if !matches!(prefix.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)) { + return None; + } + for ancestor in path.ancestors().collect::>().into_iter().rev() { + if fs.is_symlink(ancestor).await.unwrap_or(true) { + return None; + } + } + // Resolved with the `Fs::canonicalize` worktree paths are opened with, which keeps mapped + // drive letters. Unlike worktree roots, the result is not simplified: it keeps the drive + // prefix form of `path`, so that a short `\\?\C:\` parent of a longer root keeps matching it. + let canonical = fs.canonicalize(path).await.ok()?; + (canonical != path && canonical.as_os_str().eq_ignore_ascii_case(path.as_os_str())) + .then_some(canonical) +} + +fn starts_with_ignoring_ascii_case(path: &Path, prefix: &Path) -> bool { + let mut components = path.components(); + prefix.components().all(|prefix_component| { + components.next().is_some_and(|component| { + component + .as_os_str() + .eq_ignore_ascii_case(prefix_component.as_os_str()) + }) + }) +} + /// An initialization call to set up trust global for a particular project (remote or local). pub fn track_worktree_trust( worktree_store: Entity, @@ -136,6 +177,8 @@ pub struct TrustedWorktreesStore { trusted_paths: TrustedPaths, restricted: HashMap, HashSet>, worktree_trust_serialization: Task<()>, + #[cfg(feature = "test-support")] + casing_resolution_hold: Option>, } #[derive(Debug, Default)] @@ -204,9 +247,21 @@ impl TrustedWorktreesStore { worktree_stores: HashMap::default(), restricted: HashMap::default(), worktree_trust_serialization: Task::ready(()), + #[cfg(feature = "test-support")] + casing_resolution_hold: None, } } + /// Holds the next casing resolution until the returned sender is used or dropped, + /// so that tests can let everything else run first. + /// Only a resolution with persisted paths to resolve takes the hold. + #[cfg(feature = "test-support")] + pub fn hold_next_casing_resolution(&mut self) -> futures::channel::oneshot::Sender<()> { + let (release, hold) = futures::channel::oneshot::channel(); + self.casing_resolution_hold = Some(hold); + release + } + /// Whether a particular worktree store has associated worktrees that are restricted, or an associated host is restricted. pub fn has_restricted_worktrees( &self, @@ -409,6 +464,88 @@ impl TrustedWorktreesStore { )); } + /// Worktrees open with their canonical, on-disk path spelling, but a persisted trusted path keeps + /// the casing it was stored with, so it stops matching once those differ (#66915). + /// + /// To be awaited before a local worktree at `worktree_abs_path` joins `worktree_store`: + /// finds the persisted local trusted paths that match the worktree path only when ignoring + /// ASCII case, and trusts their on-disk spelling in that store. + /// The file system decides whether those name the same directory; nothing restricted is lifted. + pub(crate) fn resolve_trusted_path_casing( + &mut self, + worktree_store: &Entity, + worktree_abs_path: &Path, + fs: Arc, + cx: &mut Context, + ) -> Task<()> { + let worktree_store = worktree_store.downgrade(); + let is_local_store = self + .worktree_stores + .get(&worktree_store) + .is_some_and(|store_data| store_data.host.is_none()); + let store_has_grant = self + .trusted_paths + .get(&worktree_store) + .into_iter() + .flatten() + .any(|trusted_path| match trusted_path { + PathTrust::AbsPath(path) => worktree_abs_path.starts_with(path), + PathTrust::Worktree(_) => false, + }); + if !cfg!(windows) + || !is_local_store + || store_has_grant + || ProjectSettings::get_global(cx).session.trust_all_worktrees + { + return Task::ready(()); + } + let mismatched_paths = self + .db_trusted_paths + .get(&None) + .into_iter() + .flatten() + .filter(|path| { + !worktree_abs_path.starts_with(path) + && starts_with_ignoring_ascii_case(worktree_abs_path, path) + }) + .cloned() + .collect::>(); + if mismatched_paths.is_empty() { + return Task::ready(()); + } + + #[cfg(feature = "test-support")] + let hold = self.casing_resolution_hold.take(); + cx.spawn(async move |this, cx| { + #[cfg(feature = "test-support")] + if let Some(hold) = hold { + hold.await.ok(); + } + let mut respelled_paths = Vec::new(); + for path in mismatched_paths { + if let Some(respelled) = on_disk_spelling(fs.as_ref(), &path).await { + respelled_paths.push((respelled, path)); + } + } + this.update(cx, |this, _| { + let Some(local_paths) = this.db_trusted_paths.get_mut(&None) else { + return; + }; + for (respelled, path) in respelled_paths { + // Skip the paths whose trust got cleared meanwhile. + if local_paths.contains(&path) { + local_paths.insert(respelled.clone()); + this.trusted_paths + .entry(worktree_store.clone()) + .or_default() + .insert(PathTrust::AbsPath(respelled)); + } + } + }) + .ok(); + }) + } + /// Erases all trust information. /// Requires Zed's restart to take proper effect. pub fn clear_trusted_paths(&mut self) { diff --git a/crates/project/src/worktree_store.rs b/crates/project/src/worktree_store.rs index 723581dac16..2d2e96572ad 100644 --- a/crates/project/src/worktree_store.rs +++ b/crates/project/src/worktree_store.rs @@ -1013,6 +1013,25 @@ impl WorktreeStore { cx.spawn(async move |this, cx| { let worktree_id = next_worktree_id.await?; + // Before the worktree starts scanning, so that neither a trust check nor a scan + // event happens before the worktree joins the store with the corrected grants. + let resolve_trusted_path_casing = this.update(cx, |_, cx| { + TrustedWorktrees::try_get_global(cx).map(|trusted_worktrees| { + let worktree_store = cx.entity(); + trusted_worktrees.update(cx, |trusted_worktrees, cx| { + trusted_worktrees.resolve_trusted_path_casing( + &worktree_store, + abs_path.as_path(), + fs.clone(), + cx, + ) + }) + }) + })?; + if let Some(resolve_trusted_path_casing) = resolve_trusted_path_casing { + resolve_trusted_path_casing.await; + } + let worktree = Worktree::local( SanitizedPath::cast_arc(abs_path.clone()), visible, diff --git a/crates/project/tests/integration/project_tests.rs b/crates/project/tests/integration/project_tests.rs index 53581474abb..5cd697d9d6e 100644 --- a/crates/project/tests/integration/project_tests.rs +++ b/crates/project/tests/integration/project_tests.rs @@ -1446,6 +1446,81 @@ async fn test_project_tasks_and_debug_scenarios_require_trust(cx: &mut gpui::Tes assert_eq!(scenarios[0].1.label, "debug"); } +#[cfg(windows)] +#[gpui::test] +async fn test_debug_scenarios_load_with_differently_cased_db_trusted_path( + cx: &mut gpui::TestAppContext, +) { + use project::trusted_worktrees::{self, DbTrustedPaths, TrustedWorktrees}; + + init_test(cx); + TaskStore::init(None); + + let fs = FakeFs::new(cx.executor()); + fs.set_case_sensitive(false); + fs.insert_tree( + path!("/root/Project"), + json!({ + ".zed": { + "debug.json": r#"[{ "label": "debug", "adapter": "Debugpy", "request": "launch" }]"#, + }, + }), + ) + .await; + let root = PathBuf::from(path!("/root")); + let db_trusted_paths = + DbTrustedPaths::from_iter([(None, HashSet::from_iter([root.join("project")]))]); + cx.update(|cx| trusted_worktrees::init(db_trusted_paths, cx)); + let trusted_worktrees = cx.update(|cx| TrustedWorktrees::try_get_global(cx).unwrap()); + + let no_paths: [&Path; 0] = []; + let project = Project::test_with_worktree_trust(fs, no_paths, cx).await; + let release_casing_resolution = + trusted_worktrees.update(cx, |store, _| store.hold_next_casing_resolution()); + let create_worktree = project.update(cx, |project, cx| { + project.find_or_create_worktree(root.join("Project"), true, cx) + }); + // Let everything else run first: had the worktree started scanning, the scan would finish here. + cx.run_until_parked(); + assert!( + project.read_with(cx, |project, cx| project.worktrees(cx).next().is_none()), + "the casing resolution should hold the worktree creation" + ); + release_casing_resolution.send(()).unwrap(); + create_worktree.await.unwrap(); + cx.run_until_parked(); + + let worktree_store = project.read_with(cx, |project, _| project.worktree_store()); + assert!( + !trusted_worktrees.read_with(cx, |store, cx| store + .has_restricted_worktrees(&worktree_store, cx)), + "the worktree must never be restricted" + ); + + let worktree_id = project.read_with(cx, |project, cx| { + project.worktrees(cx).next().unwrap().read(cx).id() + }); + let inventory = project.read_with(cx, |project, cx| { + project + .task_store() + .read(cx) + .task_inventory() + .unwrap() + .clone() + }); + let contexts = TaskContexts { + active_worktree_context: Some((worktree_id, TaskContext::default())), + ..Default::default() + }; + let (_, scenarios) = inventory + .update(cx, |inventory, cx| { + inventory.list_debug_scenarios(&contexts, Vec::new(), Vec::new(), false, cx) + }) + .await; + assert_eq!(scenarios.len(), 1); + assert_eq!(scenarios[0].1.label, "debug"); +} + #[gpui::test] async fn test_invalid_local_tasks_shows_toast_with_doc_link(cx: &mut gpui::TestAppContext) { init_test(cx); diff --git a/crates/project/tests/integration/trusted_worktrees.rs b/crates/project/tests/integration/trusted_worktrees.rs index 7b21b766b05..9b36f96256c 100644 --- a/crates/project/tests/integration/trusted_worktrees.rs +++ b/crates/project/tests/integration/trusted_worktrees.rs @@ -33,6 +33,485 @@ fn init_trust_global( }) } +#[cfg(windows)] +#[gpui::test] +async fn test_differently_cased_db_trusted_parent_path(cx: &mut TestAppContext) { + use fs::RealFs; + use std::path::Path; + use util::{paths::SanitizedPath, test::TempTree}; + + init_test(cx); + cx.executor().allow_parking(); + + let dir = TempTree::new(json!({ "Dev": { "one": {}, "two": {} } })); + let root = SanitizedPath::new(dir.path()).as_path().to_path_buf(); + cx.update(|cx| { + init( + DbTrustedPaths::from_iter([(None, HashSet::from_iter([root.join("DEV")]))]), + cx, + ) + }); + let one = root.join("Dev").join("one"); + let two = root.join("Dev").join("two"); + let untracked_project = + Project::test(RealFs::new(None, cx.executor()), [one.as_path()], cx).await; + // Both tracked stores are registered before either opens a child of the trusted parent. + let no_paths: [&Path; 0] = []; + let project_a = + Project::test_with_worktree_trust(RealFs::new(None, cx.executor()), no_paths, cx).await; + let project_b = + Project::test_with_worktree_trust(RealFs::new(None, cx.executor()), no_paths, cx).await; + for (project, path) in [(&project_a, &one), (&project_b, &two)] { + project + .update(cx, |project, cx| { + project.find_or_create_worktree(path, true, cx) + }) + .await + .unwrap(); + cx.run_until_parked(); + } + + let trusted_worktrees = cx.update(|cx| TrustedWorktrees::try_get_global(cx).unwrap()); + for (project, trusted) in [ + (project_a, true), + (project_b, true), + (untracked_project, false), + ] { + let worktree_store = project.read_with(cx, |project, _| project.worktree_store()); + let worktree_id = worktree_store.read_with(cx, |store, cx| { + store.worktrees().next().unwrap().read(cx).id() + }); + trusted_worktrees.update(cx, |store, cx| { + assert_eq!( + store.can_trust(&worktree_store, worktree_id, cx), + trusted, + "a differently cased trusted parent should trust its subdirectories \ + in every worktree store tracked for trust, and only there" + ); + }); + } +} + +#[cfg(windows)] +#[gpui::test] +async fn test_differently_cased_db_trusted_path_on_mapped_drive(cx: &mut TestAppContext) { + use fs::{Fs as _, RealFs}; + use std::path::Path; + use util::{ResultExt as _, paths::SanitizedPath, test::TempTree}; + + /// A free drive letter mapped to the directory's administrative network share. + struct MappedDrive(PathBuf); + + impl MappedDrive { + #[allow(clippy::disallowed_methods)] + fn new(target: &Path) -> Option { + let share = format!( + r"\\localhost\{}", + target.to_string_lossy().replacen(':', "$", 1) + ); + if !Path::new(&share).exists() { + return None; + } + ('M'..='Z').rev().find_map(|letter| { + let root = PathBuf::from(format!("{letter}:\\")); + if root.exists() { + return None; + } + std::process::Command::new("net") + .args(["use", &format!("{letter}:"), &share, "/persistent:no"]) + .output() + .ok()? + .status + .success() + .then(|| Self(root)) + }) + } + } + + impl Drop for MappedDrive { + #[allow(clippy::disallowed_methods)] + fn drop(&mut self) { + let drive = self.0.to_string_lossy(); + std::process::Command::new("net") + .args(["use", drive.trim_end_matches('\\'), "/delete", "/y"]) + .output() + .log_err(); + } + } + + init_test(cx); + cx.executor().allow_parking(); + + let dir = TempTree::new(json!({ "Project": {} })); + let Some(drive) = MappedDrive::new(SanitizedPath::new(dir.path()).as_path()) else { + eprintln!("skipping: no drive letter could be mapped to a network share"); + return; + }; + cx.update(|cx| { + init( + DbTrustedPaths::from_iter([(None, HashSet::from_iter([drive.0.join("project")]))]), + cx, + ) + }); + let fs = RealFs::new(None, cx.executor()); + // Zed opens a worktree by its canonical path, which keeps the mapped drive letter. + let worktree_path = fs.canonicalize(&drive.0.join("project")).await.unwrap(); + assert_eq!(worktree_path, drive.0.join("Project")); + let project = Project::test_with_worktree_trust(fs, [worktree_path.as_path()], cx).await; + let worktree_store = project.read_with(cx, |project, _| project.worktree_store()); + let worktree_id = worktree_store.read_with(cx, |store, cx| { + store.worktrees().next().unwrap().read(cx).id() + }); + + let trusted_worktrees = cx.update(|cx| TrustedWorktrees::try_get_global(cx).unwrap()); + trusted_worktrees.update(cx, |store, cx| { + assert!( + store.can_trust(&worktree_store, worktree_id, cx), + "a differently cased trusted path on a mapped drive should match its directory" + ); + }); +} + +#[cfg(windows)] +#[gpui::test] +async fn test_differently_cased_db_trusted_path_longer_than_max_path(cx: &mut TestAppContext) { + use fs::{Fs as _, RealFs}; + use util::{paths::SanitizedPath, test::TempTree}; + + init_test(cx); + cx.executor().allow_parking(); + + let dir = TempTree::new(json!({})); + let root = dir.path().join("review"); + // A long project trusted itself, and one trusted through its shorter parent: both get saved + // in the extended-length `\\?\C:\` form that the project path keeps. + let deep_parent = ["a", "b", "c"] + .iter() + .fold(root.join("deep"), |path, letter| { + path.join(letter.repeat(90)) + }); + let short_parent = root.join("Dev"); + let fs = RealFs::new(None, cx.executor()); + for path in [ + deep_parent.join("Project"), + short_parent.join("x".repeat(240)), + ] { + fs.create_dir(&path).await.unwrap(); + } + cx.update(|cx| { + init( + DbTrustedPaths::from_iter([( + None, + HashSet::from_iter([deep_parent.join("project"), root.join("dev")]), + )]), + cx, + ) + }); + let mut worktree_paths = Vec::new(); + for path in [ + deep_parent.join("project"), + root.join("dev").join("x".repeat(240)), + ] { + let worktree_path = fs.canonicalize(&path).await.unwrap(); + assert!( + worktree_path.as_os_str().len() > 260 + && SanitizedPath::new(&worktree_path).as_path() == worktree_path + && worktree_path.to_string_lossy().starts_with(r"\\?\"), + "worktree paths longer than `MAX_PATH` should keep their `\\\\?\\` form" + ); + worktree_paths.push(worktree_path); + } + assert_eq!(worktree_paths[0], deep_parent.join("Project")); + let project = + Project::test_with_worktree_trust(fs, worktree_paths.iter().map(|path| path.as_path()), cx) + .await; + let worktree_store = project.read_with(cx, |project, _| project.worktree_store()); + let worktree_ids = worktree_store.read_with(cx, |store, cx| { + store + .worktrees() + .map(|worktree| worktree.read(cx).id()) + .collect::>() + }); + assert_eq!(worktree_ids.len(), 2); + + let trusted_worktrees = cx.update(|cx| TrustedWorktrees::try_get_global(cx).unwrap()); + trusted_worktrees.update(cx, |store, cx| { + for worktree_id in worktree_ids { + assert!( + store.can_trust(&worktree_store, worktree_id, cx), + "a differently cased trusted path should match its directory longer than `MAX_PATH`" + ); + } + }); +} + +#[cfg(windows)] +#[gpui::test] +async fn test_differently_cased_db_trusted_path_under_unlistable_parent(cx: &mut TestAppContext) { + use fs::RealFs; + use std::path::Path; + use util::{paths::SanitizedPath, test::TempTree}; + + /// Denies listing a directory's contents while still allowing to traverse it. + struct UnlistableDirectory(PathBuf, String); + + impl UnlistableDirectory { + #[allow(clippy::disallowed_methods)] + fn new(path: &Path) -> Option { + let user = format!( + "{}\\{}", + std::env::var("USERDOMAIN").ok()?, + std::env::var("USERNAME").ok()? + ); + let denied = std::process::Command::new("icacls") + .arg(path) + .args(["/deny", &format!("{user}:(RD)")]) + .output() + .ok()? + .status + .success(); + let unlistable = denied.then(|| Self(path.to_path_buf(), user))?; + // Elevated or privileged accounts may still list the directory. + std::fs::read_dir(path).is_err().then_some(unlistable) + } + } + + impl Drop for UnlistableDirectory { + #[allow(clippy::disallowed_methods)] + fn drop(&mut self) { + let restored = std::process::Command::new("icacls") + .arg(&self.0) + .args(["/remove:d", &self.1]) + .output(); + if !restored + .as_ref() + .is_ok_and(|output| output.status.success()) + { + eprintln!("failed to restore listing {:?}: {restored:?}", self.0); + } + } + } + + init_test(cx); + cx.executor().allow_parking(); + + let dir = TempTree::new(json!({ "Private": { "Project": {} } })); + let root = SanitizedPath::new(dir.path()).as_path().to_path_buf(); + let Some(_unlistable) = UnlistableDirectory::new(&root.join("Private")) else { + eprintln!("skipping: directory listing could not be denied"); + return; + }; + cx.update(|cx| { + init( + DbTrustedPaths::from_iter([( + None, + HashSet::from_iter([root.join("Private").join("project")]), + )]), + cx, + ) + }); + let project = Project::test_with_worktree_trust( + RealFs::new(None, cx.executor()), + [root.join("Private").join("Project").as_path()], + cx, + ) + .await; + let worktree_store = project.read_with(cx, |project, _| project.worktree_store()); + let worktree_id = worktree_store.read_with(cx, |store, cx| { + store.worktrees().next().unwrap().read(cx).id() + }); + + let trusted_worktrees = cx.update(|cx| TrustedWorktrees::try_get_global(cx).unwrap()); + trusted_worktrees.update(cx, |store, cx| { + assert!( + store.can_trust(&worktree_store, worktree_id, cx), + "a differently cased trusted path should match its directory \ + even when a parent directory cannot be listed" + ); + }); +} + +#[cfg(windows)] +#[gpui::test] +async fn test_db_trusted_paths_on_case_sensitive_fake_fs(cx: &mut TestAppContext) { + use std::path::Path; + + init_test(cx); + + // A case-sensitive file system, where distinct directories and link targets may have names + // differing only by case. + let fs = FakeFs::new(cx.executor()); + fs.insert_tree( + path!("/root"), + json!({ "safe": {}, "SAFE": {}, "only": {}, "LINK": {}, "PARENT": { "project": {} } }), + ) + .await; + fs.insert_symlink(path!("/root/link"), PathBuf::from(path!("/root/LINK"))) + .await; + fs.insert_symlink(path!("/root/parent"), PathBuf::from(path!("/root/PARENT"))) + .await; + cx.update(|cx| { + init( + DbTrustedPaths::from_iter([( + None, + HashSet::from_iter([ + PathBuf::from(path!("/root/safe")), + PathBuf::from(path!("/root/ONLY")), + PathBuf::from(path!("/root/link")), + PathBuf::from(path!("/root/parent/project")), + ]), + )]), + cx, + ) + }); + let expected_trust = [ + (path!("/root/safe"), true, "`safe` is trusted"), + ( + path!("/root/SAFE"), + false, + "trusting `safe` must not trust the distinct `SAFE` directory", + ), + ( + path!("/root/only"), + false, + "`ONLY` names no directory on a case-sensitive file system", + ), + ( + path!("/root/LINK"), + false, + "a trusted link must not extend trust to its target", + ), + ( + path!("/root/PARENT/project"), + false, + "a link in a parent directory must not extend trust to its target", + ), + ]; + let project = Project::test_with_worktree_trust( + fs, + expected_trust.iter().map(|(path, _, _)| Path::new(path)), + cx, + ) + .await; + + let worktree_store = project.read_with(cx, |project, _| project.worktree_store()); + let worktree_ids = worktree_store.read_with(cx, |store, cx| { + store + .worktrees() + .map(|worktree| { + let worktree = worktree.read(cx); + (worktree.abs_path().to_path_buf(), worktree.id()) + }) + .collect::>() + }); + let trusted_worktrees = cx.update(|cx| TrustedWorktrees::try_get_global(cx).unwrap()); + trusted_worktrees.update(cx, |store, cx| { + for (path, trusted, message) in expected_trust { + let worktree_id = worktree_ids[Path::new(path)]; + assert_eq!( + store.can_trust(&worktree_store, worktree_id, cx), + trusted, + "{message}" + ); + } + }); +} + +#[cfg(windows)] +#[gpui::test] +async fn test_db_trusted_path_in_case_sensitive_directory(cx: &mut TestAppContext) { + use fs::{Fs as _, RealFs}; + use util::{command::new_command, paths::SanitizedPath, test::TempTree}; + + init_test(cx); + cx.executor().allow_parking(); + + let dir = TempTree::new(json!({ "case-test": {} })); + let root = SanitizedPath::new(dir.path()).as_path().join("case-test"); + let enabled = new_command("fsutil") + .args(["file", "setCaseSensitiveInfo"]) + .arg(&root) + .arg("enable") + .output() + .await + .is_ok_and(|output| output.status.success()); + if !enabled { + eprintln!("skipping: per-directory case sensitivity is not available"); + return; + } + let fs = RealFs::new(None, cx.executor()); + for name in ["safe", "SAFE", "only", "LINK", "PARENT\\project"] { + fs.create_dir(&root.join(name)).await.unwrap(); + } + // Junctions whose targets differ from their own names only by case. + for (link, target) in [("link", "LINK"), ("parent", "PARENT")] { + fs.create_symlink(&root.join(link), root.join(target)) + .await + .unwrap(); + } + + cx.update(|cx| { + init( + DbTrustedPaths::from_iter([( + None, + HashSet::from_iter([ + root.join("safe"), + root.join("ONLY"), + root.join("link"), + root.join("parent").join("project"), + ]), + )]), + cx, + ) + }); + let project = Project::test_with_worktree_trust( + fs, + [ + root.join("safe").as_path(), + root.join("SAFE").as_path(), + root.join("only").as_path(), + root.join("LINK").as_path(), + root.join("PARENT").join("project").as_path(), + ], + cx, + ) + .await; + cx.run_until_parked(); + let worktree_store = project.read_with(cx, |project, _| project.worktree_store()); + let worktree_ids = worktree_store.read_with(cx, |store, cx| { + store + .worktrees() + .map(|worktree| { + let worktree = worktree.read(cx); + (worktree.abs_path().to_path_buf(), worktree.id()) + }) + .collect::>() + }); + + let trusted_worktrees = cx.update(|cx| TrustedWorktrees::try_get_global(cx).unwrap()); + trusted_worktrees.update(cx, |store, cx| { + let mut can_trust = + |name: &str| store.can_trust(&worktree_store, worktree_ids[&root.join(name)], cx); + assert!(can_trust("safe")); + assert!( + !can_trust("SAFE"), + "trusting `safe` must not trust the distinct `SAFE` directory" + ); + assert!( + !can_trust("only"), + "`ONLY` names no directory in a case-sensitive directory" + ); + assert!( + !can_trust("LINK"), + "a trusted junction must not extend trust to its target" + ); + assert!( + !can_trust("PARENT\\project"), + "a junction in a parent directory must not extend trust to its target" + ); + }); +} + #[gpui::test] async fn test_single_worktree_trust(cx: &mut TestAppContext) { init_test(cx);