workspace: Fix trust scope paths when connecting to Windows hosts from Unix (#63102)

# Objective

This is another fix related to the path handling issue when connecting
from Unix to Windows, similar to #62038 and #63075, but confined to the
path handling in the security modal. The root cause is the same: when
using the standard library `Path` API across platforms — especially
connecting from Unix to Windows — these `Path` methods give wrong
results.

The bugs I have observed include:
1. When opening a single file, its parent folder is not shown properly
in the project list.
2. When opening a folder, no parent folder is auto-filled into the input
field after "Trust all projects in".
3. When Zed runs in debug mode, opening two untrusted folders, checking
"Trust parents", and then trusting would result in a panic.

## Solution

Use the corresponding methods in `PathStyle`, which is designed for
handling paths across platforms, instead of the `Path` methods in the
relevant code.

## Testing

Built and tested locally, with comparison screenshots attached.

## Self-Review Checklist:

- [x] I've reviewed my own diff for quality, security, and reliability
- [x] Unsafe blocks (if any) have justifying comments
- [x] The content adheres to Zed's UI standards
([UX/UI](https://github.com/zed-industries/zed/blob/main/CONTRIBUTING.md#uiux-checklist)
and
[icon](https://github.com/zed-industries/zed/blob/main/crates/icons/README.md)
guidelines)
- [ ] Tests cover the new/changed behavior
- [x] Performance impact has been considered and is acceptable

## Showcase

|| Before | After |
|:--:|:--:|:--:|
| Auto fill |<img width="657" height="343" alt="auto_fill_before"
src="https://github.com/user-attachments/assets/e36ca3d5-998c-4bed-94e9-f97dd0e7ebf4"
/>| <img width="654" height="333" alt="auto_fill_after"
src="https://github.com/user-attachments/assets/c8413fb5-d2dd-427a-afb0-9cbebc033742"
/> |
| Single file | <img width="654" height="322" alt="single_file_before"
src="https://github.com/user-attachments/assets/bfe87ab0-bf87-491a-8f85-b5a2681763a9"
/>| <img width="657" height="325" alt="single_file_after"
src="https://github.com/user-attachments/assets/0437cbde-42c3-44f6-847b-abd33e54cd2c"
/> |

---

Release Notes:

- Fixed trusting projects on remote Windows machines from Unix systems
This commit is contained in:
Xin Zhao
2026-10-16 11:32:38 +00:00
committed by GitHub
parent 32b16ce2ad
commit 5504e87bfd
5 changed files with 259 additions and 38 deletions
+1 -1
View File
@@ -311,7 +311,7 @@ impl PathStyle {
})
}
pub fn starts_with<P: AsRef<Path>>(&self, path: P, prefix: P) -> bool {
pub fn starts_with(&self, path: impl AsRef<Path>, prefix: impl AsRef<Path>) -> bool {
iter_after(
self.components(path.as_ref()),
self.components(prefix.as_ref()),
+9 -7
View File
@@ -287,6 +287,7 @@ impl TrustedWorktreesStore {
let mut new_trusted_single_file_worktrees = HashSet::default();
let mut new_trusted_other_worktrees = HashSet::default();
let mut new_trusted_abs_paths = HashSet::default();
let path_style = worktree_store.read(cx).path_style();
for trusted_path in trusted_paths.iter().chain(
self.trusted_paths
.remove(&weak_worktree_store)
@@ -337,9 +338,9 @@ impl TrustedWorktreesStore {
}
new_trusted_other_worktrees.retain(|(worktree_abs_path, _)| {
new_trusted_abs_paths
.iter()
.all(|new_trusted_path| !worktree_abs_path.starts_with(new_trusted_path))
new_trusted_abs_paths.iter().all(|new_trusted_path| {
!path_style.starts_with(worktree_abs_path, new_trusted_path)
})
});
if !new_trusted_other_worktrees.is_empty() {
new_trusted_single_file_worktrees.clear();
@@ -366,7 +367,7 @@ impl TrustedWorktreesStore {
let restricted_worktree_path = worktree.read(cx).abs_path();
let retain = (!is_file || new_trusted_other_worktrees.is_empty())
&& new_trusted_abs_paths.iter().all(|new_trusted_path| {
!restricted_worktree_path.starts_with(new_trusted_path)
!path_style.starts_with(&restricted_worktree_path, new_trusted_path)
});
if !retain {
trusted_paths.insert(PathTrust::Worktree(*restricted_worktree));
@@ -472,6 +473,7 @@ impl TrustedWorktreesStore {
return false;
};
let worktree_path = worktree.read(cx).abs_path();
let path_style = worktree.read(cx).path_style();
// Zed opened an "internal" directory: e.g. a tmp dir for `keymap_editor.rs` needs.
if !worktree.read(cx).is_visible() {
log::debug!("Skipping worktree trust checks for not visible {worktree_path:?}");
@@ -496,7 +498,7 @@ impl TrustedWorktreesStore {
}
// * Single files are auto-approved when something else (not a single file) was approved on this host already.
// * If parent path is trusted already, this worktree is stusted also.
// * If parent path is trusted already, this worktree is trusted also.
//
// See module documentation for details on trust level.
if let Some(trusted_paths) = self.trusted_paths.get(&weak_worktree_store) {
@@ -506,11 +508,11 @@ impl TrustedWorktreesStore {
.worktree_for_id(*worktree_id, cx)
.is_some_and(|worktree| {
let worktree = worktree.read(cx);
worktree_path.starts_with(&worktree.abs_path())
path_style.starts_with(&worktree_path, &worktree.abs_path())
|| (is_file && !worktree.is_single_file())
}),
PathTrust::AbsPath(trusted_path) => {
is_file || worktree_path.starts_with(trusted_path)
is_file || path_style.starts_with(&worktree_path, trusted_path)
}
})
});
@@ -955,3 +955,121 @@ async fn test_invisible_worktree_stores_do_not_affect_trust(cx: &mut TestAppCont
"only visible worktrees should be restricted"
);
}
#[gpui::test]
async fn test_windows_style_abs_path_trust_from_unix_client(cx: &mut TestAppContext) {
use gpui::AppContext as _;
use project::worktree_store::WorktreeIdCounter;
use rpc::{AnyProtoClient, NoopProtoClient, proto};
use util::paths::PathStyle;
use worktree::Worktree;
init_test(cx);
let client = AnyProtoClient::new(NoopProtoClient::new());
let worktree_store = cx.update(|cx| {
cx.new(|_| {
WorktreeStore::remote(
true,
client.clone(),
1,
PathStyle::Windows,
WorktreeIdCounter::default(),
)
})
});
let make_worktree = |id: u64, name: &str, abs_path: &str, cx: &mut TestAppContext| {
let metadata = proto::WorktreeMetadata {
id,
root_name: name.to_string(),
visible: true,
abs_path: abs_path.to_string(),
root_repo_common_dir: None,
root_repo_is_linked_worktree: false,
};
let worktree = cx.update(|cx| {
Worktree::remote(
1,
clock::ReplicaId::new(1),
metadata,
client.clone(),
PathStyle::Windows,
cx,
)
});
worktree.update(cx, |worktree, _| {
worktree
.as_remote()
.unwrap()
.update_from_remote(proto::UpdateWorktree {
project_id: 1,
worktree_id: id,
abs_path: abs_path.to_string(),
root_name: name.to_string(),
updated_entries: vec![proto::Entry {
id: 1,
is_dir: true,
path: "".to_string(),
inode: 1,
mtime: Some(proto::Timestamp {
seconds: 0,
nanos: 0,
}),
is_ignored: false,
is_hidden: false,
is_external: false,
is_fifo: false,
size: None,
canonical_path: None,
is_unloaded: false,
}],
removed_entries: vec![],
scan_id: 1,
is_last_update: true,
updated_repositories: vec![],
removed_repositories: vec![],
root_repo_common_dir: None,
root_repo_is_linked_worktree: false,
});
});
cx.run_until_parked();
worktree
};
let worktree_t1 = make_worktree(1, "t1", r"C:\Users\me\dev\wt\t1", cx);
let worktree_t2 = make_worktree(2, "t2", r"C:\Users\me\dev\wt\t2", cx);
let t1_id = worktree_t1.read_with(cx, |worktree, _| worktree.id());
let t2_id = worktree_t2.read_with(cx, |worktree, _| worktree.id());
worktree_store.update(cx, |store, cx| {
store.add(&worktree_t1, cx);
store.add(&worktree_t2, cx);
});
assert!(
!worktree_t1.read_with(cx, |worktree, _| worktree.is_single_file()),
"t1 must be a folder worktree for this test to be meaningful"
);
let trusted_worktrees = init_trust_global(worktree_store.clone(), cx);
assert!(
!trusted_worktrees.update(cx, |store, cx| store.can_trust(&worktree_store, t1_id, cx)),
"t1 should be restricted by default"
);
trusted_worktrees.update(cx, |store, cx| {
store.trust(
&worktree_store,
HashSet::from_iter([
PathTrust::Worktree(t1_id),
PathTrust::AbsPath(PathBuf::from(r"C:\Users\me\dev\wt")),
]),
cx,
);
});
assert!(
trusted_worktrees.update(cx, |store, cx| store.can_trust(&worktree_store, t2_id, cx)),
"t2 should be auto-trusted by the trusted parent scope C:\\Users\\me\\dev\\wt"
);
}
+118 -29
View File
@@ -7,7 +7,9 @@ use std::{
};
use collections::{HashMap, HashSet};
use gpui::{DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, ScrollHandle, WeakEntity};
use gpui::{
DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, ScrollHandle, Task, WeakEntity,
};
use project::{
WorktreeId,
@@ -22,13 +24,14 @@ use ui::{
};
use ui_input::InputField;
use util::paths::PathStyle;
use util::{ResultExt, paths::PathStyle};
use crate::{DismissDecision, ModalView, ToggleWorktreeSecurity};
pub struct SecurityModal {
restricted_paths: HashMap<WorktreeId, RestrictedPath>,
home_dir: Option<PathBuf>,
_home_dir_task: Task<()>,
trust_parents: bool,
worktree_store: WeakEntity<WorktreeStore>,
remote_host: Option<RemoteHostLocation>,
@@ -90,7 +93,8 @@ impl Render for SecurityModal {
format!("Unrecognized Projects ({})", restricted_count).into()
};
let trust_label = self.build_trust_label();
let path_style = self.path_style(cx);
let trust_label = self.build_trust_label(path_style);
// The editable trust-scope field is shown only when a single project is
// being prompted for (Delta opens one worktree per thread).
@@ -138,7 +142,7 @@ impl Render for SecurityModal {
self.restricted_paths.values().filter_map(
|restricted_path| {
let abs_path = if restricted_path.is_file {
restricted_path.abs_path.parent()
path_style.parent(&restricted_path.abs_path)
} else {
Some(restricted_path.abs_path.as_ref())
}?;
@@ -147,21 +151,21 @@ impl Render for SecurityModal {
match &remote_host.user_name {
Some(user_name) => format!(
"{} ({}@{})",
self.shorten_path(abs_path)
self.shorten_path(abs_path, path_style)
.display(),
user_name,
remote_host.host_identifier
),
None => format!(
"{} ({})",
self.shorten_path(abs_path)
self.shorten_path(abs_path, path_style)
.display(),
remote_host.host_identifier
),
}
}
None => self
.shorten_path(abs_path)
.shorten_path(abs_path, path_style)
.display()
.to_string(),
};
@@ -309,10 +313,19 @@ impl SecurityModal {
pub fn new(
worktree_store: WeakEntity<WorktreeStore>,
remote_host: Option<impl Into<RemoteHostLocation>>,
home_dir_task: Task<Option<PathBuf>>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let trust_path_input = cx.new(|cx| InputField::new(window, cx, "Folder to trust"));
let task = cx.spawn(async |this, cx| {
let home_dir = home_dir_task.await;
this.update(cx, |this, cx| {
this.home_dir = home_dir;
cx.notify();
})
.log_err();
});
let mut this = Self {
worktree_store,
remote_host: remote_host.map(|host| host.into()),
@@ -320,7 +333,8 @@ impl SecurityModal {
focus_handle: cx.focus_handle(),
project_list_scroll_handle: ScrollHandle::new(),
trust_parents: false,
home_dir: std::env::home_dir(),
home_dir: None,
_home_dir_task: task,
trusted: None,
trust_path_input,
};
@@ -329,7 +343,11 @@ impl SecurityModal {
// Pre-fill with the single project's parent folder (today's static
// scope), read-only until the checkbox is ticked.
if let Some(project) = this.single_trustable_path() {
let default_scope = project.parent().unwrap_or(&project).to_path_buf();
let path_style = this.path_style(cx);
let default_scope = path_style
.parent(&project)
.unwrap_or(&project)
.to_path_buf();
this.trust_path_input.update(cx, |field, cx| {
field.set_text(&default_scope.to_string_lossy(), window, cx);
});
@@ -340,7 +358,7 @@ impl SecurityModal {
this
}
fn build_trust_label(&self) -> Option<Cow<'static, str>> {
fn build_trust_label(&self, path_style: PathStyle) -> Option<Cow<'static, str>> {
let mut has_restricted_files = false;
let available_parents = self
.restricted_paths
@@ -349,7 +367,7 @@ impl SecurityModal {
has_restricted_files |= restricted_path.is_file;
!restricted_path.is_file
})
.filter_map(|restricted_path| restricted_path.abs_path.parent())
.filter_map(|restricted_path| path_style.parent(&restricted_path.abs_path))
.collect::<SmallVec<[_; 2]>>();
match available_parents.len() {
0 => {
@@ -361,18 +379,27 @@ impl SecurityModal {
}
1 => Some(Cow::Owned(format!(
"Trust all projects in the {:} folder",
self.shorten_path(available_parents[0]).display()
self.shorten_path(available_parents[0], path_style)
.display()
))),
_ => Some(Cow::Borrowed("Trust all projects in the parent folders")),
}
}
fn shorten_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> {
fn path_style(&self, cx: &App) -> PathStyle {
self.worktree_store
.upgrade()
.map(|store| store.read(cx).path_style())
.unwrap_or_else(PathStyle::local)
}
fn shorten_path<'a>(&self, path: &'a Path, path_style: PathStyle) -> Cow<'a, Path> {
match &self.home_dir {
Some(home_dir) => path
.strip_prefix(home_dir)
.map(|stripped| Path::new("~").join(stripped))
.map(Cow::Owned)
Some(home_dir) => path_style
.strip_prefix(path, home_dir)
.ok()
.and_then(|stripped| path_style.join("~", stripped))
.map(|joined| Cow::Owned(PathBuf::from(joined)))
.unwrap_or(Cow::Borrowed(path)),
None => Cow::Borrowed(path),
}
@@ -389,11 +416,7 @@ impl SecurityModal {
return Ok(None);
};
let typed = self.trust_path_input.read(cx).text(cx);
let path_style = self
.worktree_store
.upgrade()
.map(|store| store.read(cx).path_style())
.unwrap_or_else(PathStyle::local);
let path_style = self.path_style(cx);
validate_trust_scope(&typed, &project, self.home_dir.as_deref(), path_style).map(Some)
}
@@ -422,13 +445,14 @@ impl SecurityModal {
if let Some(scope) = scope_override {
paths_to_trust.insert(PathTrust::AbsPath(scope));
} else {
let path_style = self.path_style(cx);
paths_to_trust.extend(self.restricted_paths.values().filter_map(
|restricted_paths| {
if restricted_paths.is_file {
None
} else {
let parent_abs_path =
restricted_paths.abs_path.parent()?.to_owned();
path_style.parent(&restricted_paths.abs_path)?.to_owned();
Some(PathTrust::AbsPath(parent_abs_path))
}
},
@@ -511,23 +535,33 @@ fn validate_trust_scope(
if trimmed.is_empty() {
return Err("Enter a folder to trust".into());
}
if home_dir.is_none() && trimmed.starts_with('~') {
return Err("Home directory not available".into());
}
let expanded = match (trimmed.strip_prefix('~'), home_dir) {
(Some(rest), Some(home_dir)) => home_dir.join(
rest.strip_prefix(path_style.primary_separator())
.unwrap_or(rest),
),
(Some(rest), Some(home_dir)) => {
let rest = rest.trim_start_matches(path_style.separators_ch());
if path_style == PathStyle::local() {
home_dir.join(rest)
} else {
path_style
.join_path_preserving_components(home_dir, rest)
.map_err(|error| SharedString::from(error.to_string()))?
}
}
_ => PathBuf::from(trimmed),
};
if !path_style.is_absolute(&expanded) {
return Err("Enter an absolute folder path".into());
}
if !project.starts_with(&expanded) {
if !path_style.starts_with(project, expanded.as_path()) {
return Err("Must be a parent folder of the project".into());
}
Ok(expanded)
}
#[cfg(all(test, unix))]
#[cfg(test)]
mod tests {
use super::*;
@@ -561,6 +595,61 @@ mod tests {
);
}
#[test]
fn accepts_windows_style_ancestor() {
let project = Path::new(r"C:\Users\me\dev\wt\t1");
let style = PathStyle::Windows;
assert_eq!(
validate_trust_scope(r"C:\Users\me\dev\wt", project, None, style).unwrap(),
PathBuf::from(r"C:\Users\me\dev\wt"),
);
assert!(validate_trust_scope(r"C:\Users\me", project, None, style).is_ok());
assert_eq!(
validate_trust_scope(r"C:\Users\me\dev\wt\t1", project, None, style).unwrap(),
PathBuf::from(r"C:\Users\me\dev\wt\t1")
);
// Drive letters are matched case-insensitively.
assert_eq!(
validate_trust_scope(r"c:\Users\me\dev\wt", project, None, style).unwrap(),
PathBuf::from(r"c:\Users\me\dev\wt")
);
}
#[test]
fn rejects_windows_style_non_ancestor() {
let project = Path::new(r"C:\Users\me\dev\wt\t1");
let style = PathStyle::Windows;
assert!(validate_trust_scope(r"C:\Users\other", project, None, style).is_err());
// Relative paths are not absolute.
assert!(validate_trust_scope(r"dev\wt", project, None, style).is_err());
// Deeper than the project is not an ancestor.
assert!(validate_trust_scope(r"C:\Users\me\dev\wt\t1\sub", project, None, style).is_err());
// A prefix that is not a component boundary is not an ancestor.
assert!(
validate_trust_scope(
r"C:\Users\me\dev\wt",
Path::new(r"C:\Users\me\dev\wt2"),
None,
style,
)
.is_err()
);
assert!(
validate_trust_scope(
r"\\server",
Path::new(r"\\server\share\project"),
None,
style
)
.is_err()
);
}
#[test]
fn expands_leading_tilde() {
let home = Path::new("/Users/me");
+13 -1
View File
@@ -9089,8 +9089,20 @@ impl Workspace {
.remote_connection_options(cx)
.map(RemoteHostLocation::from);
let worktree_store = project.worktree_store().downgrade();
let home_dir_task = if project.is_local() {
Task::ready(std::env::home_dir())
} else {
let resolve_task = project.resolve_abs_path("~", cx);
cx.spawn(async |_, _| {
let resolved_path = resolve_task
.await
.and_then(|path| path.into_abs_path())
.map(PathBuf::from);
resolved_path
})
};
self.toggle_modal(window, cx, |window, cx| {
SecurityModal::new(worktree_store, remote_host, window, cx)
SecurityModal::new(worktree_store, remote_host, home_dir_task, window, cx)
});
}
}