Stop showing worktree trust modal after "Stay in Restricted Mode" is called (#66649)

Closes https://github.com/zed-industries/zed/issues/58246

* Starts to remember "Stay in Restricted Mode" calls to avoid repeated
worktree trust pop-ups
* Uses `RemoteConnectionIdentity` instead of the prior type (removed) as
more detailed remote host identifier (has a port value now)
* Migrates worktree trust DB to that, more detailed, data format

Release Notes:

- Stopped showing worktree trust modal after "Stay in Restricted Mode"
is called
This commit is contained in:
Kirill Bulatov
2026-11-11 21:17:08 +00:00
committed by GitHub
parent 3d42ca7c09
commit b6ff193ba6
9 changed files with 902 additions and 156 deletions
+75
View File
@@ -80,6 +80,7 @@ use workspace::{
Pane, SplitDirection, ToolbarItemLocation, ViewId, Workspace,
item::{FollowEvent, FollowableItem, Item, ItemHandle, SaveOptions},
register_project_item,
security_modal::SecurityModal,
};
fn display_ranges(editor: &Editor, cx: &mut Context<'_, Editor>) -> Vec<Range<DisplayPoint>> {
@@ -46902,6 +46903,80 @@ async fn test_tab_list_indent(cx: &mut TestAppContext) {
cx.assert_editor_state(expected);
}
#[gpui::test]
async fn test_stay_in_restricted_mode_is_remembered(cx: &mut TestAppContext) {
init_test(cx, |_| {});
cx.update(|cx| {
cx.set_global(db::AppDatabase::test_new());
project::trusted_worktrees::init(HashMap::default(), cx);
});
let fs = FakeFs::new(cx.executor());
fs.insert_tree(
path!("/projects"),
json!({
"declined": {"main.rs": "", "nested": {"lib.rs": ""}},
"other": {"main.rs": ""},
}),
)
.await;
for (project_path, expect_prompt) in [
(path!("/projects/declined"), true),
(path!("/projects/declined"), false),
(path!("/projects/declined/nested"), true),
(path!("/projects/other"), true),
(path!("/projects/other"), false),
] {
let project =
Project::test_with_worktree_trust(fs.clone(), [project_path.as_ref()], cx).await;
let worktree_store = project.read_with(cx, |project, _| project.worktree_store());
let worktree_id = project.read_with(cx, |project, cx| {
project
.worktrees(cx)
.next()
.expect("project should have a worktree")
.read(cx)
.id()
});
let trusted_worktrees = cx
.update(|cx| TrustedWorktrees::try_get_global(cx).expect("trust global should exist"));
assert!(!trusted_worktrees.update(cx, |store, cx| {
store.can_trust(&worktree_store, worktree_id, cx)
}));
let (multi_workspace, window_cx) =
cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx));
let workspace = multi_workspace.read_with(window_cx, |multi_workspace, _| {
multi_workspace.workspace().clone()
});
let has_modal = |window_cx: &mut VisualTestContext| {
workspace.read_with(window_cx, |workspace, cx| {
workspace.active_modal::<SecurityModal>(cx).is_some()
})
};
workspace.update_in(window_cx, |workspace, window, cx| {
workspace.show_worktree_trust_security_modal(false, window, cx);
});
window_cx.run_until_parked();
assert_eq!(has_modal(window_cx), expect_prompt, "{project_path}");
if !expect_prompt {
window_cx.dispatch_action(workspace::ToggleWorktreeSecurity);
window_cx.run_until_parked();
assert!(has_modal(window_cx), "{project_path}");
}
window_cx.dispatch_action(workspace::ToggleWorktreeSecurity);
window_cx.run_until_parked();
assert!(!has_modal(window_cx), "{project_path}");
assert!(!trusted_worktrees.update(window_cx, |store, cx| {
store.can_trust(&worktree_store, worktree_id, cx)
}));
}
}
#[gpui::test]
async fn test_local_worktree_trust(cx: &mut TestAppContext) {
init_test(cx, |_| {});
+113 -16
View File
@@ -629,26 +629,26 @@ pub async fn await_and_rollback_on_failure(
/// Propagates worktree trust from the source workspace to the new workspace.
/// If the source project's worktrees are all trusted, the new worktree paths
/// will also be trusted automatically.
fn maybe_propagate_worktree_trust(
async fn maybe_propagate_worktree_trust(
source_workspace: &WeakEntity<Workspace>,
new_workspace: &Entity<Workspace>,
paths: &[PathBuf],
cx: &mut AsyncWindowContext,
) {
cx.update(|_, cx| {
let inherit_restriction = cx.update(|window, cx| {
if ProjectSettings::get_global(cx).session.trust_all_worktrees {
return;
return None;
}
let source_is_trusted = source_workspace
.upgrade()
.map(|workspace| {
let source_worktree_store = workspace.read(cx).project().read(cx).worktree_store();
!TrustedWorktrees::has_restricted_worktrees(&source_worktree_store, cx)
})
.unwrap_or(false);
if !source_is_trusted {
return;
let source_workspace = source_workspace.upgrade()?;
let source_worktree_store = source_workspace
.read(cx)
.project()
.read(cx)
.worktree_store();
if TrustedWorktrees::has_restricted_worktrees(&source_worktree_store, cx) {
return Some(new_workspace.update(cx, |new_workspace, cx| {
new_workspace.inherit_restricted_worktrees(&source_workspace, window, cx)
}));
}
let worktree_store = new_workspace.read(cx).project().read(cx).worktree_store();
@@ -667,8 +667,11 @@ fn maybe_propagate_worktree_trust(
});
}
}
})
.ok();
None
});
if let Ok(Some(inherit_restriction)) = inherit_restriction {
inherit_restriction.await;
}
// After trust propagation, refresh the security modal on the new workspace
// so it dismisses itself if there are no more restricted worktrees.
@@ -1258,7 +1261,7 @@ async fn open_worktree_workspace(
})
.await;
maybe_propagate_worktree_trust(&workspace, &new_workspace, &all_paths, cx);
maybe_propagate_worktree_trust(&workspace, &new_workspace, &all_paths, cx).await;
if transfer_state {
window_handle.update(cx, |_multi_workspace, window, cx| {
@@ -1709,6 +1712,100 @@ mod tests {
);
}
#[gpui::test]
async fn test_linked_worktree_inherits_stay_in_restricted_mode(cx: &mut TestAppContext) {
init_test(cx);
cx.update(|cx| {
cx.set_global(db::AppDatabase::test_new());
project::trusted_worktrees::init(collections::HashMap::default(), cx);
});
let fs = FakeFs::new(cx.background_executor.clone());
cx.update(|cx| <dyn Fs>::set_global(fs.clone(), cx));
fs.insert_tree(
"/root",
json!({
"project": {
".git": {},
"src": {
"main.rs": "fn main() {}",
},
},
}),
)
.await;
let main_project_root = PathBuf::from(path!("/root/project"));
for (worktree_name, stay_restricted_in_source) in [("undecided", false), ("declined", true)]
{
let project =
Project::test_with_worktree_trust(fs.clone(), [main_project_root.as_path()], cx)
.await;
project
.update(cx, |project, cx| project.git_scans_complete(cx))
.await;
let (multi_workspace, window_cx) = cx.add_window_view(|window, cx| {
MultiWorkspace::test_new(project.clone(), window, cx)
});
multi_workspace.update(window_cx, |multi_workspace, cx| {
multi_workspace.retain_active_workspace(cx);
});
let main_workspace = multi_workspace.read_with(window_cx, |multi_workspace, _| {
multi_workspace.workspace().clone()
});
if stay_restricted_in_source {
main_workspace.update_in(window_cx, |workspace, window, cx| {
workspace.show_worktree_trust_security_modal(true, window, cx);
});
window_cx.run_until_parked();
window_cx.dispatch_action(workspace::ToggleWorktreeSecurity);
window_cx.run_until_parked();
}
main_workspace.update_in(window_cx, |workspace, window, cx| {
assert!(
workspace
.active_modal::<workspace::security_modal::SecurityModal>(cx)
.is_none(),
"{worktree_name}"
);
handle_create_worktree(
workspace,
&zed_actions::CreateWorktree {
worktree_name: Some(worktree_name.to_string()),
branch_target: NewWorktreeBranchTarget::CurrentBranch,
},
window,
None,
cx,
);
});
window_cx.run_until_parked();
let new_workspace = multi_workspace.read_with(window_cx, |multi_workspace, _| {
multi_workspace.workspace().clone()
});
assert_ne!(new_workspace, main_workspace, "{worktree_name}");
new_workspace.read_with(window_cx, |workspace, cx| {
assert!(
project::trusted_worktrees::TrustedWorktrees::has_restricted_worktrees(
&workspace.project().read(cx).worktree_store(),
cx,
),
"{worktree_name}"
);
assert_eq!(
workspace
.active_modal::<workspace::security_modal::SecurityModal>(cx)
.is_some(),
!stay_restricted_in_source,
"{worktree_name}"
);
});
}
}
#[test]
fn test_remote_branch_name_parse() {
assert_eq!(
+2 -2
View File
@@ -41,7 +41,7 @@ use crate::{
git_store::GitStore,
lsp_store::{SymbolLocation, log_store::LogKind},
project_search::SearchResultsHandle,
trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
trusted_worktrees::{PathTrust, TrustedWorktrees},
worktree_store::WorktreeIdCounter,
};
pub use agent_registry_store::{AgentRegistryStore, RegistryAgent};
@@ -1526,7 +1526,7 @@ impl Project {
(
remote.proto_client(),
remote.path_style(),
RemoteHostLocation::from(remote.connection_options()),
remote.connection_options().identity().into_owned(),
)
});
let worktree_store = cx.new(|cx| {
+12 -47
View File
@@ -1,6 +1,6 @@
//! A module, responsible for managing the trust logic in Zed.
//!
//! It deals with multiple hosts, distinguished by [`RemoteHostLocation`].
//! It deals with multiple hosts, distinguished by [`remote::RemoteConnectionIdentity`].
//! Each [`crate::Project`] and `HeadlessProject` should call [`init_global`], if wants to establish the trust mechanism.
//! This will set up a [`gpui::Global`] with [`TrustedWorktrees`] entity that will persist, restore and allow querying for worktree trust.
//! It's also possible to subscribe on [`TrustedWorktreesEvent`] events of this entity to track trust changes dynamically.
@@ -41,10 +41,8 @@
use client::ProjectId;
use collections::{HashMap, HashSet};
use gpui::{
App, AppContext as _, Context, Entity, EventEmitter, Global, SharedString, Task, WeakEntity,
};
use remote::RemoteConnectionOptions;
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::{
@@ -65,7 +63,7 @@ pub fn init(db_trusted_paths: DbTrustedPaths, cx: &mut App) {
/// An initialization call to set up trust global for a particular project (remote or local).
pub fn track_worktree_trust(
worktree_store: Entity<WorktreeStore>,
remote_host: Option<RemoteHostLocation>,
remote_host: Option<RemoteConnectionIdentity<'static>>,
downstream_client: Option<(AnyProtoClient, ProjectId)>,
upstream_client: Option<(AnyProtoClient, ProjectId)>,
cx: &mut App,
@@ -144,43 +142,7 @@ pub struct TrustedWorktreesStore {
struct StoreData {
upstream_client: Option<(AnyProtoClient, ProjectId)>,
downstream_client: Option<(AnyProtoClient, ProjectId)>,
host: Option<RemoteHostLocation>,
}
/// An identifier of a host to split the trust questions by.
/// Each trusted data change and event is done for a particular host.
/// A host may contain more than one worktree or even project open concurrently.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct RemoteHostLocation {
pub user_name: Option<SharedString>,
pub host_identifier: SharedString,
}
impl From<&RemoteConnectionOptions> for RemoteHostLocation {
fn from(options: &RemoteConnectionOptions) -> Self {
let (user_name, host_name) = match options {
RemoteConnectionOptions::Ssh(ssh) => (
ssh.username.as_ref().map(SharedString::new),
SharedString::new(ssh.host.to_string()),
),
RemoteConnectionOptions::Wsl(wsl) => (
wsl.user.as_ref().map(SharedString::new),
SharedString::new(&wsl.distro_name),
),
RemoteConnectionOptions::Docker(docker_connection_options) => (
Some(SharedString::new(&docker_connection_options.name)),
SharedString::new(&docker_connection_options.container_id),
),
#[cfg(feature = "test-support")]
RemoteConnectionOptions::Mock(mock) => {
(None, SharedString::new(format!("mock-{}", mock.id)))
}
};
Self {
user_name,
host_identifier: host_name,
}
}
host: Option<RemoteConnectionIdentity<'static>>,
}
/// A unit of trust consideration inside a particular host:
@@ -232,7 +194,7 @@ pub enum TrustedWorktreesEvent {
impl EventEmitter<TrustedWorktreesEvent> for TrustedWorktreesStore {}
type TrustedPaths = HashMap<WeakEntity<WorktreeStore>, HashSet<PathTrust>>;
pub type DbTrustedPaths = HashMap<Option<RemoteHostLocation>, HashSet<PathBuf>>;
pub type DbTrustedPaths = HashMap<Option<RemoteConnectionIdentity<'static>>, HashSet<PathBuf>>;
impl TrustedWorktreesStore {
fn new(db_trusted_paths: DbTrustedPaths) -> Self {
@@ -607,7 +569,10 @@ impl TrustedWorktreesStore {
pub fn schedule_serialization<S>(&mut self, cx: &mut Context<Self>, serialize: S)
where
S: FnOnce(HashMap<Option<RemoteHostLocation>, HashSet<PathBuf>>, &App) -> Task<()>
S: FnOnce(
HashMap<Option<RemoteConnectionIdentity<'static>>, HashSet<PathBuf>>,
&App,
) -> Task<()>
+ 'static,
{
self.worktree_trust_serialization = serialize(self.trusted_paths_for_serialization(cx), cx);
@@ -616,7 +581,7 @@ impl TrustedWorktreesStore {
fn trusted_paths_for_serialization(
&mut self,
cx: &mut Context<Self>,
) -> HashMap<Option<RemoteHostLocation>, HashSet<PathBuf>> {
) -> HashMap<Option<RemoteConnectionIdentity<'static>>, HashSet<PathBuf>> {
let new_trusted_paths = self
.trusted_paths
.iter()
@@ -651,7 +616,7 @@ impl TrustedWorktreesStore {
fn add_worktree_store(
&mut self,
worktree_store: Entity<WorktreeStore>,
remote_host: Option<RemoteHostLocation>,
remote_host: Option<RemoteConnectionIdentity<'static>>,
downstream_client: Option<(AnyProtoClient, ProjectId)>,
upstream_client: Option<(AnyProtoClient, ProjectId)>,
cx: &mut Context<Self>,
+2 -2
View File
@@ -29,7 +29,7 @@ use project::{
project_settings::SettingsObserver,
search::SearchQuery,
task_store::TaskStore,
trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
trusted_worktrees::{PathTrust, TrustedWorktrees},
worktree_store::{WorktreeIdCounter, WorktreeStore},
};
use rpc::{
@@ -132,7 +132,7 @@ impl HeadlessProject {
if init_worktree_trust {
project::trusted_worktrees::track_worktree_trust(
worktree_store.clone(),
None::<RemoteHostLocation>,
None,
Some((session.clone(), ProjectId(REMOTE_SERVER_PROJECT_ID))),
None,
cx,
+469 -30
View File
@@ -24,7 +24,7 @@ use project::{
ProjectGroupKey,
bookmark_store::SerializedBookmark,
debugger::breakpoint_store::{BreakpointState, SourceBreakpoint},
trusted_worktrees::{DbTrustedPaths, RemoteHostLocation},
trusted_worktrees::DbTrustedPaths,
};
use language::{LanguageName, Toolchain, ToolchainScope};
@@ -1087,6 +1087,53 @@ impl Domain for WorkspaceDb {
sql!(
ALTER TABLE workspaces ADD COLUMN path_style TEXT;
),
sql!(
CREATE TABLE restricted_worktrees (
absolute_path BLOB NOT NULL,
connection_kind TEXT,
host TEXT,
user TEXT,
port INTEGER
) STRICT;
CREATE INDEX restricted_worktrees_absolute_path ON restricted_worktrees(absolute_path);
),
sql!(
CREATE TABLE trusted_worktrees_2 (
trust_id INTEGER PRIMARY KEY AUTOINCREMENT,
absolute_path TEXT,
connection_kind TEXT,
host TEXT,
user TEXT,
port INTEGER
) STRICT;
INSERT INTO trusted_worktrees_2 (absolute_path)
SELECT absolute_path
FROM trusted_worktrees
WHERE user_name IS NULL AND host_name IS NULL;
INSERT INTO trusted_worktrees_2 (absolute_path, connection_kind, host, user, port)
SELECT DISTINCT
trusted.absolute_path,
connections.kind,
trusted.host_name,
connections.user,
connections.port
FROM trusted_worktrees AS trusted
JOIN remote_connections AS connections ON
(connections.kind = "ssh"
AND connections.host = trusted.host_name
AND connections.user IS trusted.user_name)
OR (connections.kind = "wsl"
AND connections.distro = trusted.host_name
AND connections.user IS trusted.user_name)
OR (connections.kind = "docker"
AND connections.container_id = trusted.host_name
AND connections.name IS trusted.user_name);
DROP TABLE trusted_worktrees;
ALTER TABLE trusted_worktrees_2 RENAME TO trusted_worktrees;
),
];
// Allow recovering from bad migration that was initially shipped to nightly
@@ -2597,7 +2644,7 @@ impl WorkspaceDb {
pub(crate) async fn save_trusted_worktrees(
&self,
trusted_worktrees: HashMap<Option<RemoteHostLocation>, HashSet<PathBuf>>,
trusted_worktrees: DbTrustedPaths,
) -> anyhow::Result<()> {
use anyhow::Context as _;
use db::sqlez::statement::Statement;
@@ -2617,10 +2664,10 @@ impl WorkspaceDb {
.collect::<Vec<_>>();
let mut first_worktree;
let mut last_worktree = 0_usize;
for (count, placeholders) in std::iter::once("(?, ?, ?)")
for (count, placeholders) in std::iter::once("(?, ?, ?, ?, ?)")
.cycle()
.take(trusted_worktrees.len())
.chunks(MAX_QUERY_PLACEHOLDERS / 3)
.chunks(MAX_QUERY_PLACEHOLDERS / 5)
.into_iter()
.map(|chunk| {
let mut count = 0;
@@ -2636,7 +2683,7 @@ impl WorkspaceDb {
first_worktree = last_worktree;
last_worktree = last_worktree + count;
let query = format!(
r#"INSERT INTO trusted_worktrees(absolute_path, user_name, host_name)
r#"INSERT INTO trusted_worktrees(absolute_path, connection_kind, host, user, port)
VALUES {placeholders};"#
);
@@ -2650,16 +2697,8 @@ VALUES {placeholders};"#
&abs_path.as_ref().map(|abs_path| abs_path.as_ref()),
next_index,
)?;
next_index = statement.bind(
&host
.as_ref()
.and_then(|host| Some(host.user_name.as_ref()?.as_str())),
next_index,
)?;
next_index = statement.bind(
&host.as_ref().map(|host| host.host_identifier.as_str()),
next_index,
)?;
next_index =
statement.bind(&remote_identity_columns(host.as_ref()), next_index)?;
}
statement.exec()
})
@@ -2673,19 +2712,9 @@ VALUES {placeholders};"#
let trusted_worktrees = self.trusted_worktrees()?;
Ok(trusted_worktrees
.into_iter()
.filter_map(|(abs_path, user_name, host_name)| {
let db_host = match (user_name, host_name) {
(None, Some(host_name)) => Some(RemoteHostLocation {
user_name: None,
host_identifier: SharedString::new(host_name),
}),
(Some(user_name), Some(host_name)) => Some(RemoteHostLocation {
user_name: Some(SharedString::new(user_name)),
host_identifier: SharedString::new(host_name),
}),
_ => None,
};
Some((db_host, abs_path?))
.filter_map(|(abs_path, kind, host, user, port)| {
let remote_host = remote_identity_from_columns(kind, host, user, port)?;
Some((remote_host, abs_path?))
})
.fold(HashMap::default(), |mut acc, (remote_host, abs_path)| {
acc.entry(remote_host)
@@ -2696,8 +2725,8 @@ VALUES {placeholders};"#
}
query! {
fn trusted_worktrees() -> Result<Vec<(Option<PathBuf>, Option<String>, Option<String>)>> {
SELECT absolute_path, user_name, host_name
fn trusted_worktrees() -> Result<Vec<(Option<PathBuf>, Option<String>, Option<String>, Option<String>, Option<u16>)>> {
SELECT absolute_path, connection_kind, host, user, port
FROM trusted_worktrees
}
}
@@ -2707,6 +2736,146 @@ VALUES {placeholders};"#
DELETE FROM trusted_worktrees
}
}
pub(crate) async fn has_undecided_restricted_worktrees(
&self,
abs_paths: Vec<Arc<Path>>,
connection_identity: Option<RemoteConnectionIdentity<'static>>,
) -> Result<bool> {
self.write(move |connection| {
let columns = remote_identity_columns(connection_identity.as_ref());
for abs_path in &abs_paths {
if !is_worktree_kept_restricted(connection, abs_path, &columns)? {
return Ok(true);
}
}
Ok(false)
})
.await
}
pub(crate) fn keep_worktrees_restricted(
&self,
abs_paths: Vec<Arc<Path>>,
connection_identity: Option<RemoteConnectionIdentity<'static>>,
) {
// The write is queued by this call and runs even if the returned future is dropped.
drop(self.write(move |connection| {
connection
.with_savepoint("keep_worktrees_restricted", || {
let columns = remote_identity_columns(connection_identity.as_ref());
let mut insert =
connection.exec_bound::<(&Path, RemoteIdentityColumns)>(sql!(
INSERT INTO restricted_worktrees(absolute_path, connection_kind, host, user, port)
VALUES (?, ?, ?, ?, ?)
))?;
for abs_path in &abs_paths {
if !is_worktree_kept_restricted(connection, abs_path, &columns)? {
insert((abs_path.as_ref(), columns.clone()))?;
}
}
Ok(())
})
.log_err();
}));
}
query! {
pub(crate) async fn clear_restricted_worktrees() -> Result<()> {
DELETE FROM restricted_worktrees
}
}
}
type RemoteIdentityColumns = (
Option<&'static str>,
Option<String>,
Option<String>,
Option<u16>,
);
fn remote_identity_columns(
connection_identity: Option<&RemoteConnectionIdentity<'_>>,
) -> RemoteIdentityColumns {
match connection_identity {
None => (None, None, None, None),
Some(RemoteConnectionIdentity::Ssh {
host,
username,
port,
}) => (
Some(RemoteConnectionKind::Ssh.serialize()),
Some(host.to_string()),
username.as_ref().map(ToString::to_string),
*port,
),
Some(RemoteConnectionIdentity::Wsl { distro_name, user }) => (
Some(RemoteConnectionKind::Wsl.serialize()),
Some(distro_name.to_string()),
user.as_ref().map(ToString::to_string),
None,
),
Some(RemoteConnectionIdentity::Docker {
container_id,
remote_user,
}) => (
Some(RemoteConnectionKind::Docker.serialize()),
Some(container_id.to_string()),
Some(remote_user.to_string()),
None,
),
#[cfg(any(test, feature = "test-support"))]
Some(RemoteConnectionIdentity::Mock { id }) => {
(Some("mock"), Some(id.to_string()), None, None)
}
}
}
fn remote_identity_from_columns(
kind: Option<String>,
host: Option<String>,
user: Option<String>,
port: Option<u16>,
) -> Option<Option<RemoteConnectionIdentity<'static>>> {
let Some(kind) = kind else {
return Some(None);
};
#[cfg(any(test, feature = "test-support"))]
if kind == "mock" {
let id = host?.parse().ok()?;
return Some(Some(RemoteConnectionIdentity::Mock { id }));
}
let host = Cow::Owned(host?);
let user = user.map(Cow::Owned);
let identity = match RemoteConnectionKind::deserialize(&kind)? {
RemoteConnectionKind::Ssh => RemoteConnectionIdentity::Ssh {
host,
username: user,
port,
},
RemoteConnectionKind::Wsl => RemoteConnectionIdentity::Wsl {
distro_name: host,
user,
},
RemoteConnectionKind::Docker => RemoteConnectionIdentity::Docker {
container_id: host,
remote_user: user?,
},
};
Some(Some(identity))
}
fn is_worktree_kept_restricted(
connection: &Connection,
abs_path: &Path,
columns: &RemoteIdentityColumns,
) -> Result<bool> {
let mut select = connection.select_row_bound::<(&Path, RemoteIdentityColumns), PathBuf>(sql!(
SELECT absolute_path
FROM restricted_worktrees
WHERE absolute_path = ? AND connection_kind IS ? AND host IS ? AND user IS ? AND port IS ?
))?;
Ok(select((abs_path, columns.clone()))?.is_some())
}
#[derive(Clone, Debug, PartialEq)]
@@ -3278,6 +3447,276 @@ mod tests {
assert_eq!(test_text_1, "test-text-1");
}
#[gpui::test]
async fn test_restricted_worktrees_are_scoped_to_path_and_connection() {
let db = WorkspaceDb::open_test_db("test_restricted_worktrees").await;
let path = Path::new("/project");
let other_path = Path::new("/other");
let ssh =
|username: Option<&'static str>, port: Option<u16>| RemoteConnectionIdentity::Ssh {
host: Cow::Borrowed("host"),
username: username.map(Cow::Borrowed),
port,
};
let declined_connection = ssh(Some("user"), Some(2222));
db.keep_worktrees_restricted(
Vec::from([Arc::from(path), Arc::from(path), Arc::from(other_path)]),
Some(declined_connection.clone()),
);
for (paths, connection_identity, expected_undecided) in [
(
Vec::from([path, other_path]),
Some(declined_connection.clone()),
false,
),
(
Vec::from([path, Path::new("/project/nested")]),
Some(declined_connection.clone()),
true,
),
(Vec::from([path]), None, true),
(Vec::from([path]), Some(ssh(None, Some(2222))), true),
(Vec::from([path]), Some(ssh(Some("user"), Some(2223))), true),
(Vec::from([path]), Some(ssh(Some("user"), None)), true),
(
Vec::from([path]),
Some(RemoteConnectionIdentity::Wsl {
distro_name: Cow::Borrowed("host"),
user: Some(Cow::Borrowed("user")),
}),
true,
),
] {
assert_eq!(
db.has_undecided_restricted_worktrees(
paths.iter().copied().map(Arc::from).collect::<Vec<_>>(),
connection_identity.clone(),
)
.await
.unwrap(),
expected_undecided,
"{paths:?} on {connection_identity:?}"
);
}
db.keep_worktrees_restricted(Vec::from([Arc::from(Path::new("/late"))]), None);
db.keep_worktrees_restricted(Vec::from([Arc::from(Path::new("/late"))]), None);
assert_eq!(
db.select_row::<i64>(sql!(SELECT COUNT(*) FROM restricted_worktrees))
.unwrap()()
.unwrap(),
Some(3)
);
db.clear_restricted_worktrees().await.unwrap();
assert_eq!(
db.select_row::<i64>(sql!(SELECT COUNT(*) FROM restricted_worktrees))
.unwrap()()
.unwrap(),
Some(0)
);
}
#[test]
fn test_trusted_worktrees_migration_splits_hosts_by_known_connections() {
let connection = Connection::open_memory(Some(
"test_trusted_worktrees_migration_splits_hosts_by_known_connections",
));
let trusted_worktrees_migration = WorkspaceDb::MIGRATIONS
.iter()
.position(|migration| migration.contains("CREATE TABLE trusted_worktrees_2"))
.expect("trusted worktrees migration should exist");
let old_migrations = &WorkspaceDb::MIGRATIONS[..trusted_worktrees_migration];
connection
.migrate(WorkspaceDb::NAME, old_migrations, &mut |_, _, _| false)
.unwrap();
connection
.exec(
"
INSERT INTO remote_connections (kind, host, port, user, distro, name, container_id)
VALUES
('ssh', 'server', 2222, 'user', NULL, NULL, NULL),
('ssh', 'server', 2223, 'user', NULL, NULL, NULL),
('ssh', 'server', 2224, 'other', NULL, NULL, NULL),
('ssh', 'no-user', NULL, NULL, NULL, NULL, NULL),
('wsl', NULL, NULL, 'user', 'Ubuntu', NULL, NULL),
('docker', NULL, NULL, 'vscode', NULL, 'dev', 'container');
INSERT INTO trusted_worktrees (absolute_path, user_name, host_name)
VALUES
('/local', NULL, NULL),
('/ssh', 'user', 'server'),
('/ssh_no_user', NULL, 'no-user'),
('/wsl', 'user', 'Ubuntu'),
('/docker', 'dev', 'container'),
('/unknown_connection', 'user', 'forgotten'),
('/unknown_shape', 'user', NULL);",
)
.unwrap()()
.unwrap();
connection
.migrate(
WorkspaceDb::NAME,
WorkspaceDb::MIGRATIONS,
&mut |_, _, _| false,
)
.unwrap();
let migrated_rows = connection
.select::<(
String,
Option<String>,
Option<String>,
Option<String>,
Option<u16>,
)>(
"SELECT absolute_path, connection_kind, host, user, port
FROM trusted_worktrees
ORDER BY absolute_path, port",
)
.unwrap()()
.unwrap();
let row = |path: &str, kind: Option<&str>, host: Option<&str>, user: Option<&str>, port| {
(
path.to_string(),
kind.map(String::from),
host.map(String::from),
user.map(String::from),
port,
)
};
assert_eq!(
migrated_rows,
Vec::from([
row(
"/docker",
Some("docker"),
Some("container"),
Some("vscode"),
None
),
row("/local", None, None, None, None),
row(
"/ssh",
Some("ssh"),
Some("server"),
Some("user"),
Some(2222)
),
row(
"/ssh",
Some("ssh"),
Some("server"),
Some("user"),
Some(2223)
),
row("/ssh_no_user", Some("ssh"), Some("no-user"), None, None),
row("/wsl", Some("wsl"), Some("Ubuntu"), Some("user"), None),
])
);
}
#[gpui::test]
async fn test_trusted_worktrees_round_trip_all_connection_kinds() {
let db = WorkspaceDb::open_test_db("test_trusted_worktrees_round_trip").await;
let connections = [
None,
Some(RemoteConnectionIdentity::Ssh {
host: Cow::Borrowed("server"),
username: Some(Cow::Borrowed("user")),
port: Some(2222),
}),
Some(RemoteConnectionIdentity::Ssh {
host: Cow::Borrowed("server"),
username: Some(Cow::Borrowed("user")),
port: Some(2223),
}),
Some(RemoteConnectionIdentity::Ssh {
host: Cow::Borrowed("server"),
username: None,
port: None,
}),
Some(RemoteConnectionIdentity::Wsl {
distro_name: Cow::Borrowed("server"),
user: Some(Cow::Borrowed("user")),
}),
Some(RemoteConnectionIdentity::Docker {
container_id: Cow::Borrowed("server"),
remote_user: Cow::Borrowed("user"),
}),
Some(RemoteConnectionIdentity::Mock { id: 7 }),
];
let trusted_paths = connections
.into_iter()
.map(|connection_identity| {
(
connection_identity,
HashSet::from_iter([PathBuf::from("/project")]),
)
})
.collect::<DbTrustedPaths>();
db.save_trusted_worktrees(trusted_paths.clone())
.await
.unwrap();
assert_eq!(db.fetch_trusted_worktrees().unwrap(), trusted_paths);
}
#[test]
fn test_restricted_worktree_lookup_waits_for_pending_saves() {
futures::executor::block_on(async {
let db = WorkspaceDb(
ThreadSafeConnection::builder::<WorkspaceDb>(
"test_restricted_worktree_lookup",
false,
)
.build()
.await
.unwrap(),
);
let path = Arc::<Path>::from(Path::new("/project"));
let (release_writer, writer_released) = std::sync::mpsc::channel::<()>();
drop(db.write(move |_| {
writer_released.recv().ok();
}));
db.keep_worktrees_restricted(Vec::from([path.clone()]), None);
let (has_undecided_worktrees, ()) = futures::join!(
db.has_undecided_restricted_worktrees(Vec::from([path]), None),
async {
release_writer.send(()).unwrap();
}
);
assert_eq!(has_undecided_worktrees.unwrap(), false);
});
}
#[cfg(unix)]
#[gpui::test]
async fn test_restricted_worktrees_keep_non_utf8_paths_distinct() {
use std::{ffi::OsStr, os::unix::ffi::OsStrExt as _};
let db = WorkspaceDb::open_test_db("test_restricted_worktrees_non_utf8").await;
let declined_path = Path::new(OsStr::from_bytes(b"/tmp/\xff/project"));
let other_path = Path::new(OsStr::from_bytes(b"/tmp/\xfe/project"));
db.keep_worktrees_restricted(Vec::from([Arc::from(declined_path)]), None);
for (path, expected_undecided) in [(declined_path, false), (other_path, true)] {
assert_eq!(
db.has_undecided_restricted_worktrees(Vec::from([Arc::from(path)]), None)
.await
.unwrap(),
expected_undecided,
"{path:?}"
);
}
}
#[gpui::test]
async fn test_native_window_state_round_trip() {
zlog::init_test();
+97 -32
View File
@@ -13,9 +13,10 @@ use gpui::{
use project::{
WorktreeId,
trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
trusted_worktrees::{PathTrust, TrustedWorktrees},
worktree_store::WorktreeStore,
};
use remote::RemoteConnectionIdentity;
use smallvec::SmallVec;
use theme::ActiveTheme;
use ui::{
@@ -26,7 +27,7 @@ use ui_input::InputField;
use util::{ResultExt, paths::PathStyle};
use crate::{DismissDecision, ModalView, ToggleWorktreeSecurity};
use crate::{DismissDecision, ModalView, ToggleWorktreeSecurity, WorkspaceDb};
pub struct SecurityModal {
restricted_paths: HashMap<WorktreeId, RestrictedPath>,
@@ -34,10 +35,11 @@ pub struct SecurityModal {
_home_dir_task: Task<()>,
trust_parents: bool,
worktree_store: WeakEntity<WorktreeStore>,
remote_host: Option<RemoteHostLocation>,
remote_host: Option<RemoteConnectionIdentity<'static>>,
focus_handle: FocusHandle,
project_list_scroll_handle: ScrollHandle,
trusted: Option<bool>,
restriction_inherited: bool,
/// Editable trust scope shown inline with the checkbox when a single
/// project is being prompted for; read-only until the checkbox is ticked.
trust_path_input: Entity<InputField>,
@@ -47,7 +49,7 @@ pub struct SecurityModal {
struct RestrictedPath {
abs_path: Arc<Path>,
is_file: bool,
host: Option<RemoteHostLocation>,
host: Option<RemoteConnectionIdentity<'static>>,
}
impl Focusable for SecurityModal {
@@ -63,10 +65,20 @@ impl ModalView for SecurityModal {
true
}
fn on_before_dismiss(&mut self, _: &mut Window, _: &mut Context<Self>) -> DismissDecision {
fn on_before_dismiss(&mut self, _: &mut Window, cx: &mut Context<Self>) -> DismissDecision {
if self.restriction_inherited {
return DismissDecision::Dismiss(true);
}
match self.trusted {
Some(false) => {
telemetry::event!("Open in Restricted", source = "Worktree Trust Modal");
let abs_paths = self
.restricted_paths
.values()
.map(|restricted_path| restricted_path.abs_path.clone())
.collect::<Vec<_>>();
WorkspaceDb::global(cx)
.keep_worktrees_restricted(abs_paths, self.remote_host.clone());
DismissDecision::Dismiss(true)
}
Some(true) => {
@@ -111,8 +123,7 @@ impl Render for SecurityModal {
this.trust_and_dismiss(cx);
}))
.on_action(cx.listener(|security_modal, _: &ToggleWorktreeSecurity, _window, cx| {
security_modal.trusted = Some(false);
security_modal.dismiss(cx);
security_modal.stay_restricted_and_dismiss(cx);
}))
.header(
v_flex()
@@ -146,28 +157,14 @@ impl Render for SecurityModal {
} else {
Some(restricted_path.abs_path.as_ref())
}?;
let path = self.shorten_path(abs_path, path_style);
let label = match &restricted_path.host {
Some(remote_host) => {
match &remote_host.user_name {
Some(user_name) => format!(
"{} ({}@{})",
self.shorten_path(abs_path, path_style)
.display(),
user_name,
remote_host.host_identifier
),
None => format!(
"{} ({})",
self.shorten_path(abs_path, path_style)
.display(),
remote_host.host_identifier
),
}
}
None => self
.shorten_path(abs_path, path_style)
.display()
.to_string(),
Some(remote_host) => format!(
"{} ({})",
path.display(),
remote_host_label(remote_host),
),
None => path.display().to_string(),
};
Some(
h_flex()
@@ -286,8 +283,7 @@ impl Render for SecurityModal {
.map(|kb| kb.size(rems_from_px(12_f32))),
)
.on_click(cx.listener(move |security_modal, _, _, cx| {
security_modal.trusted = Some(false);
security_modal.dismiss(cx);
security_modal.stay_restricted_and_dismiss(cx);
cx.stop_propagation();
})),
)
@@ -312,7 +308,7 @@ impl Render for SecurityModal {
impl SecurityModal {
pub fn new(
worktree_store: WeakEntity<WorktreeStore>,
remote_host: Option<impl Into<RemoteHostLocation>>,
remote_host: Option<RemoteConnectionIdentity<'static>>,
home_dir_task: Task<Option<PathBuf>>,
window: &mut Window,
cx: &mut Context<Self>,
@@ -328,7 +324,7 @@ impl SecurityModal {
});
let mut this = Self {
worktree_store,
remote_host: remote_host.map(|host| host.into()),
remote_host,
restricted_paths: HashMap::default(),
focus_handle: cx.focus_handle(),
project_list_scroll_handle: ScrollHandle::new(),
@@ -336,6 +332,7 @@ impl SecurityModal {
home_dir: None,
_home_dir_task: task,
trusted: None,
restriction_inherited: false,
trust_path_input,
};
this.refresh_restricted_paths(cx);
@@ -471,6 +468,16 @@ impl SecurityModal {
cx.emit(DismissEvent);
}
pub(crate) fn dismiss_inherited_restriction(&mut self, cx: &mut Context<Self>) {
self.restriction_inherited = true;
self.dismiss(cx);
}
fn stay_restricted_and_dismiss(&mut self, cx: &mut Context<Self>) {
self.trusted = Some(false);
self.dismiss(cx);
}
/// The sole untrusted, non-file project, when exactly one is being prompted
/// for. This is the case where the trust scope can be edited (Delta opens
/// one worktree per thread); with zero or several we keep the static label.
@@ -558,9 +565,40 @@ fn validate_trust_scope(
Ok(expanded)
}
fn remote_host_label(remote_host: &RemoteConnectionIdentity<'_>) -> String {
let (user, host) = match remote_host {
RemoteConnectionIdentity::Ssh {
host,
username,
port,
} => (
username.as_deref(),
match port {
Some(port) if host.contains(':') => format!("[{host}]:{port}"),
Some(port) => format!("{host}:{port}"),
None => host.to_string(),
},
),
RemoteConnectionIdentity::Wsl { distro_name, user } => {
(user.as_deref(), distro_name.to_string())
}
RemoteConnectionIdentity::Docker {
container_id,
remote_user,
} => (Some(remote_user.as_ref()), container_id.to_string()),
#[cfg(any(test, feature = "test-support"))]
RemoteConnectionIdentity::Mock { id } => (None, format!("mock-{id}")),
};
match user {
Some(user) => format!("{user}@{host}"),
None => host,
}
}
#[cfg(test)]
mod tests {
use super::*;
use remote::{RemoteConnectionOptions, SshConnectionOptions};
#[test]
fn accepts_ancestor_or_equal() {
@@ -676,4 +714,31 @@ mod tests {
PathBuf::from("/Users/me"),
);
}
#[test]
fn remote_host_label_matches_ssh_connection_string() {
for (host, username, port) in [
("server", Some("user"), Some(2222)),
("server", Some("user"), None),
("server", None, Some(2222)),
("server", None, None),
("::1", Some("user"), Some(2222)),
("::1", None, None),
("127.0.0.1", None, Some(2222)),
] {
let options = RemoteConnectionOptions::Ssh(SshConnectionOptions {
host: host.into(),
username: username.map(String::from),
port,
..SshConnectionOptions::default()
});
let RemoteConnectionOptions::Ssh(ssh_options) = &options else {
unreachable!();
};
assert_eq!(
remote_host_label(&options.identity()),
ssh_options.connection_string(),
);
}
}
}
+128 -26
View File
@@ -103,7 +103,7 @@ use project::{
git_store::{GitStoreEvent, RepositoryEvent},
project_settings::ProjectSettings,
toolchain_store::ToolchainStoreEvent,
trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent},
trusted_worktrees::{TrustedWorktrees, TrustedWorktreesEvent},
};
use release_channel::ReleaseChannel;
use remote::{
@@ -491,6 +491,7 @@ actions!(
ToggleWorktreeSecurity,
/// Clears all trusted worktrees, placing them in restricted mode on next open.
/// Requires restart to take effect on already opened projects.
/// Also forgets which worktrees were chosen to stay in restricted mode.
ClearTrustedWorktrees,
/// Stops following a collaborator.
Unfollow,
@@ -1697,6 +1698,7 @@ pub struct Workspace {
_observe_current_user: Task<Result<()>>,
_schedule_serialize_workspace: Option<Task<()>>,
_serialize_workspace_task: Option<Task<()>>,
worktree_trust_prompt_check: Option<Task<()>>,
_schedule_serialize_ssh_paths: Option<Task<()>>,
pane_history_timestamp: Arc<AtomicUsize>,
bounds: Bounds<Pixels>,
@@ -2203,6 +2205,7 @@ impl Workspace {
_apply_leader_updates,
_schedule_serialize_workspace: None,
_serialize_workspace_task: None,
worktree_trust_prompt_check: None,
_schedule_serialize_ssh_paths: None,
leader_updates_tx,
_subscriptions: subscriptions,
@@ -8614,6 +8617,7 @@ impl Workspace {
});
let db = WorkspaceDb::global(cx);
cx.spawn(async move |_, cx| {
db.clear_restricted_worktrees().await.log_err();
if db.clear_trusted_worktrees().await.log_err().is_some() {
cx.update(|cx| reload(cx));
}
@@ -9424,6 +9428,9 @@ impl Workspace {
window: &mut Window,
cx: &mut Context<Self>,
) {
if toggle {
self.worktree_trust_prompt_check = None;
}
if let Some(security_modal) = self.active_modal::<SecurityModal>(cx) {
if toggle {
security_modal.update(cx, |security_modal, cx| {
@@ -9434,33 +9441,128 @@ impl Workspace {
security_modal.refresh_restricted_paths(cx);
});
}
} else if toggle {
self.open_worktree_trust_security_modal(window, cx);
} else {
let has_restricted_worktrees = TrustedWorktrees::has_restricted_worktrees(
&self.project().read(cx).worktree_store(),
cx,
);
if has_restricted_worktrees {
let project = self.project().read(cx);
let remote_host = project
.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, home_dir_task, window, cx)
});
self.check_worktree_trust_prompt(window, cx);
}
}
pub fn inherit_restricted_worktrees(
&mut self,
source_workspace: &Entity<Workspace>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Task<()> {
if source_workspace.entity_id() == cx.entity_id() {
return Task::ready(());
}
let Some((source_paths, source_connection_identity)) =
source_workspace.read(cx).restricted_worktree_paths(cx)
else {
return Task::ready(());
};
let Some((restricted_paths, connection_identity)) = self.restricted_worktree_paths(cx)
else {
return Task::ready(());
};
let db = WorkspaceDb::global(cx);
cx.spawn_in(window, async move |workspace, cx| {
let source_has_undecided_worktrees = db
.has_undecided_restricted_worktrees(source_paths, source_connection_identity)
.await
.log_err()
.unwrap_or(true);
if source_has_undecided_worktrees {
return;
}
db.keep_worktrees_restricted(restricted_paths, connection_identity);
workspace
.update(cx, |workspace, cx| {
workspace.worktree_trust_prompt_check = None;
if let Some(security_modal) = workspace.active_modal::<SecurityModal>(cx) {
security_modal.update(cx, |security_modal, cx| {
security_modal.dismiss_inherited_restriction(cx);
});
}
})
.ok();
})
}
fn restricted_worktree_paths(
&self,
cx: &App,
) -> Option<(Vec<Arc<Path>>, Option<RemoteConnectionIdentity<'static>>)> {
let trusted_worktrees = TrustedWorktrees::try_get_global(cx)?;
let project = self.project().read(cx);
let restricted_paths = trusted_worktrees
.read(cx)
.restricted_worktrees(&project.worktree_store(), cx)
.into_iter()
.map(|(_, abs_path)| abs_path)
.collect::<Vec<_>>();
if restricted_paths.is_empty() {
return None;
}
let connection_identity = project
.remote_connection_identity(cx)
.map(RemoteConnectionIdentity::into_owned);
Some((restricted_paths, connection_identity))
}
fn check_worktree_trust_prompt(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some((restricted_paths, connection_identity)) = self.restricted_worktree_paths(cx)
else {
return;
};
let db = WorkspaceDb::global(cx);
self.worktree_trust_prompt_check = Some(cx.spawn_in(window, async move |workspace, cx| {
let has_undecided_worktrees = db
.has_undecided_restricted_worktrees(restricted_paths, connection_identity)
.await
.log_err()
.unwrap_or(true);
if has_undecided_worktrees {
workspace
.update_in(cx, |workspace, window, cx| {
if workspace.active_modal::<SecurityModal>(cx).is_none() {
workspace.open_worktree_trust_security_modal(window, cx);
}
})
.ok();
}
}));
}
fn open_worktree_trust_security_modal(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let has_restricted_worktrees = TrustedWorktrees::has_restricted_worktrees(
&self.project().read(cx).worktree_store(),
cx,
);
if has_restricted_worktrees {
let project = self.project().read(cx);
let remote_host = project
.remote_connection_identity(cx)
.map(RemoteConnectionIdentity::into_owned);
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, home_dir_task, window, cx)
});
}
}
}
+4 -1
View File
@@ -20,7 +20,10 @@ If a worktree is not trusted, Zed will indicate this with an exclamation mark ic
Trusting a worktree persists that decision between restarts. You can clear all trusted worktrees with the `workspace::ClearTrustedWorktrees` command.
This command will restart Zed, to ensure no untrusted settings, language servers or MCP servers persist.
This feature works locally and on SSH and WSL remote hosts. Zed tracks trust information per host in these cases.
Choosing "Stay in Restricted Mode" also persists between restarts, per worktree path and remote connection, so the security modal does not open automatically for that worktree again.
The title bar icon and the `workspace::ToggleWorktreeSecurity` action still open it, and `workspace::ClearTrustedWorktrees` also clears these choices.
This feature works locally and on SSH and WSL remote hosts. Zed tracks trust information per remote connection in these cases, so the same host on a different SSH port or with a different user is trusted separately.
## What is restricted