mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-27 02:50:30 +01:00
trusted_worktrees: Fix case-sensitive path comparison on Windows (#67078)
Closes #66915 ## Summary Zed canonicalizes a folder's path when it opens it, so a worktree root always has its on-disk spelling. Persisted trusted paths don't. They keep the casing they had when they were saved. On Windows the two can drift apart, for example after renaming `Project` to `project`. The trust check then compares `C:\dev\project` with `C:\dev\Project`, fails, and the worktree's `.zed/debug.json`, tasks, and settings never load. The fix happens while a local worktree is created. In `create_local_worktree`, before `Worktree::local` starts scanning and before the worktree is added to its store, Zed looks for persisted local trusted paths that match the worktree path only when case is ignored. It resolves those through the project's `Fs`, with `Fs::canonicalize` like the worktree path itself, so mapped drive letters are kept, and trusts their on-disk spelling in that store. Nothing can check the worktree's trust before it's added, so the first check already sees the corrected grant. What it does and doesn't touch: - The filesystem decides whether two spellings are the same directory. In a case-sensitive directory, `safe` and `SAFE` stay separate. - Path components are checked from the root down, and the lookup stops at the first symlink or junction, so nothing under a link is looked up. The check uses a new `Fs::is_symlink`, which neither follows a path nor needs read access to it, so a parent that can be traversed but not listed doesn't block the correction. Only local drive paths are resolved, `C:\` and the extended-length `\\?\C:\` form kept by paths longer than `MAX_PATH` alike; UNC paths (network shares, `\\wsl.localhost`) are skipped. - Only case variants of the new worktree's own ancestors are looked up. Unrelated saved paths aren't touched, and startup does no extra work. - It only runs on Windows, only for local stores tracked for trust, and not when the store's own grants already cover the worktree path. - Nothing restricted gets lifted, no events are sent, and `can_trust`, `trust`, and remote hosts are unchanged. Known limits: - Only ASCII casing differences are handled. Other paths stay restricted, the same as today. - A worktree root that moves after it's opened isn't resolved again, also the same as today. - There's a small window between the link check and the lookup. Winning it requires permission to replace the trusted folder, and with that permission someone can already put their own folder at the trusted path, which is trusted today anyway. ## Testing Windows tests in `crates/project`: - `test_debug_scenarios_load_with_differently_cased_db_trusted_path`: the reported symptom. A test-only hook holds the casing resolution while everything else runs, then releases it: the worktree is never restricted and its `debug.json` scenario loads. With the lookup placed after `Worktree::local`, the scan finishes during the hold and the test fails. - `test_differently_cased_db_trusted_parent_path`: a saved `DEV` parent trusts `Dev\one` and `Dev\two` opened one after the other in two tracked stores registered beforehand, but not in a worktree store that isn't tracked for trust. - `test_db_trusted_path_in_case_sensitive_directory`: uses `fsutil file setCaseSensitiveInfo` to make a real case-sensitive directory. Trusting `safe` doesn't trust `SAFE`, and the junctions `link` -> `LINK` and `parent` -> `PARENT` (with `project` inside) don't extend trust to their targets. If the machine can't enable case sensitivity, the test prints a message and returns early. - `test_differently_cased_db_trusted_path_longer_than_max_path`: a project path over 260 characters trusted directly, and a short `\\?\` parent grant over one, both kept in their `\\?\` form. - `test_differently_cased_db_trusted_path_under_unlistable_parent`: denies listing a parent directory with `icacls` and checks that a differently cased grant still trusts the project below it. It skips if the deny doesn't apply, e.g. on an admin account. - `test_db_trusted_paths_on_case_sensitive_fake_fs`: the same cases on a case-sensitive `FakeFs`, so they run everywhere: distinct `safe`/`SAFE` directories, a nonexistent `ONLY` spelling, and links to targets differing only by case, in the leaf and in a parent directory. - `test_differently_cased_db_trusted_path_on_mapped_drive`: maps a free drive letter to the temp directory through `\\localhost\C$` (`net use /persistent:no`) and checks that a differently cased grant on that drive trusts the worktree. It skips if no drive can be mapped. Each test fails if I remove the part of the fix it covers: the respelling, the link check, checking only the last component, or the tracked-store check. `cargo test -p project` passes on Windows. I couldn't run Linux or macOS locally, but the new code returns right away there. Video: to follow. Release Notes: - Fixed project settings, tasks, and debug scenarios not loading on Windows when a trusted folder's saved path casing differed from the folder on disk.
This commit is contained in:
committed by
GitHub
parent
aeabc0823d
commit
dc1a4bfd05
@@ -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<Option<Metadata>>;
|
||||
/// 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<bool>;
|
||||
async fn read_link(&self, path: &Path) -> Result<PathBuf>;
|
||||
async fn read_dir(
|
||||
&self,
|
||||
@@ -1281,6 +1285,15 @@ impl Fs for RealFs {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn is_symlink(&self, path: &Path) -> Result<bool> {
|
||||
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<PathBuf> {
|
||||
let path = path.to_owned();
|
||||
let path = self
|
||||
@@ -3681,6 +3694,16 @@ impl Fs for FakeFs {
|
||||
}
|
||||
}
|
||||
|
||||
async fn is_symlink(&self, path: &Path) -> Result<bool> {
|
||||
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<PathBuf> {
|
||||
self.simulate_random_delay().await;
|
||||
let path = normalize_path(path);
|
||||
|
||||
@@ -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<PathBuf> {
|
||||
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::<Vec<_>>().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<WorktreeStore>,
|
||||
@@ -136,6 +177,8 @@ pub struct TrustedWorktreesStore {
|
||||
trusted_paths: TrustedPaths,
|
||||
restricted: HashMap<WeakEntity<WorktreeStore>, HashSet<WorktreeId>>,
|
||||
worktree_trust_serialization: Task<()>,
|
||||
#[cfg(feature = "test-support")]
|
||||
casing_resolution_hold: Option<futures::channel::oneshot::Receiver<()>>,
|
||||
}
|
||||
|
||||
#[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<WorktreeStore>,
|
||||
worktree_abs_path: &Path,
|
||||
fs: Arc<dyn Fs>,
|
||||
cx: &mut Context<Self>,
|
||||
) -> 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::<Vec<_>>();
|
||||
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) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<Self> {
|
||||
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::<Vec<_>>()
|
||||
});
|
||||
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<Self> {
|
||||
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::<collections::HashMap<_, _>>()
|
||||
});
|
||||
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::<collections::HashMap<_, _>>()
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
Reference in New Issue
Block a user