Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai c4c99ecced fix(remote): trust the projects of a trusted remote folder on this machine too
Trust Folder in a remote window trusted the parent folder on the server, but
this machine kept only the one project's decision, keyed by target and root.
Opening another project in that folder found no local decision and asked
again. The desktop now records the folder per remote target as well and
treats projects under it as trusted (an explicit Don't Trust still wins), and
Remove Trusted Location in a remote window forgets it here too. Earlier
per-project decisions keep their key.
2026-12-04 15:39:58 +08:00
7 змінених файлів з 158 додано та 32 видалено

No files matched your search

+94 -16
Переглянути файл
@@ -28,6 +28,34 @@ pub struct TrustStore {
struct RemoteDecisions {
trusted: Vec<String>,
restricted: Vec<String>,
/// Folders trusted with everything under them (Trust Folder), per target.
#[serde(default)]
locations: Vec<RemoteLocation>,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
struct RemoteLocation {
target: String,
folder: String,
}
/// The key of a remote project's decisions: `[<target>,"<root>"]`, as `serde_json` writes the
/// `(target, root)` tuple (the format of earlier versions). `target` is the target's JSON.
pub fn remote_key(target: &str, root: &str) -> String {
format!("[{target},{}]", serde_json::to_string(root).unwrap_or_default())
}
/// The folder Trust Folder trusts for remote project `root`: its parent (`/`-separated).
fn remote_parent(root: &str) -> Option<&str> {
let root = root.trim_end_matches('/');
let (parent, _) = root.rsplit_once('/')?;
Some(if parent.is_empty() { "/" } else { parent })
}
fn remote_under(root: &str, folder: &str) -> bool {
let root = root.trim_end_matches('/');
let folder = folder.trim_end_matches('/');
root == folder || root.strip_prefix(folder).is_some_and(|rest| rest.starts_with('/'))
}
/// Set by the desktop when it starts the server in a dev container of a folder the user trusts
@@ -59,25 +87,52 @@ impl TrustStore {
Self { file, state: Mutex::new(state), inherited: Mutex::default(), remote_file, remote: Mutex::new(remote) }
}
/// The decision made on this machine for the remote project at `location` (`None`: none yet).
/// Commands a remote window runs here follow it, not the server's own trust.
pub fn remote_decision(&self, location: &str) -> IdeResult<Option<bool>> {
/// The decision made on this machine for the remote project `root` of `target` (the
/// target's JSON; `None`: none yet). Commands a remote window runs here follow it, not the
/// server's own trust. A project under a trusted folder of the same target is trusted.
pub fn remote_decision(&self, target: &str, root: &str) -> IdeResult<Option<bool>> {
let remote = self.remote.lock().clone()?;
Ok(if remote.restricted.iter().any(|l| l == location) {
let location = remote_key(target, root);
Ok(if remote.restricted.contains(&location) {
Some(false)
} else if remote.trusted.iter().any(|l| l == location) {
} else if remote.trusted.contains(&location)
|| remote.locations.iter().any(|l| l.target == target && remote_under(root, &l.folder))
{
Some(true)
} else {
None
})
}
pub fn decide_remote(&self, location: &str, trusted: bool) -> IdeResult<()> {
/// Records the decision for remote project `root` of `target`; `folder` also trusts its
/// parent folder (Trust Folder).
pub fn decide_remote(&self, target: &str, root: &str, trusted: bool, folder: bool) -> IdeResult<()> {
let location = remote_key(target, root);
let mut state = self.remote.lock();
let mut next = state.clone()?;
next.trusted.retain(|l| l != location);
next.restricted.retain(|l| l != location);
if trusted { &mut next.trusted } else { &mut next.restricted }.push(location.to_owned());
next.trusted.retain(|l| *l != location);
next.restricted.retain(|l| *l != location);
if trusted { &mut next.trusted } else { &mut next.restricted }.push(location);
if trusted
&& folder
&& let Some(parent) = remote_parent(root)
{
let parent = RemoteLocation { target: target.to_owned(), folder: parent.to_owned() };
if !next.locations.contains(&parent) {
next.locations.push(parent);
}
}
persist(&self.remote_file, &next)?;
*state = Ok(next);
Ok(())
}
/// Forgets trusted folder `folder` of `target` (Remove Trusted Location in a remote window).
pub fn remove_remote_location(&self, target: &str, folder: &str) -> IdeResult<()> {
let mut state = self.remote.lock();
let mut next = state.clone()?;
let folder = folder.trim_end_matches('/');
next.locations.retain(|l| l.target != target || l.folder.trim_end_matches('/') != folder);
persist(&self.remote_file, &next)?;
*state = Ok(next);
Ok(())
@@ -439,12 +494,35 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
let load = || super::TrustStore::load(&tmp.path().join("config"), &tmp.path().join("data"));
let store = load();
let here = r#"[{"kind":"ssh","config":"box"},"/srv/app"]"#;
assert_eq!(store.remote_decision(here).unwrap(), None);
store.decide_remote(here, true).unwrap();
assert_eq!(store.remote_decision(here).unwrap(), Some(true));
assert_eq!(store.remote_decision(r#"[{"kind":"ssh","config":"box"},"/srv/other"]"#).unwrap(), None);
store.decide_remote(here, false).unwrap();
assert_eq!(load().remote_decision(here).unwrap(), Some(false));
let target = r#"{"kind":"ssh","config":"box"}"#;
assert_eq!(store.remote_decision(target, "/srv/app").unwrap(), None);
store.decide_remote(target, "/srv/app", true, false).unwrap();
assert_eq!(store.remote_decision(target, "/srv/app").unwrap(), Some(true));
assert_eq!(store.remote_decision(target, "/srv/other").unwrap(), None);
store.decide_remote(target, "/srv/app", false, false).unwrap();
assert_eq!(load().remote_decision(target, "/srv/app").unwrap(), Some(false));
}
#[test]
fn trusting_a_remote_folder_trusts_the_projects_under_it_on_that_target() {
let tmp = tempfile::tempdir().unwrap();
let load = || super::TrustStore::load(&tmp.path().join("config"), &tmp.path().join("data"));
let store = load();
let target = r#"{"kind":"ssh","config":"box"}"#;
let other = r#"{"kind":"ssh","config":"other"}"#;
store.decide_remote(target, "/srv/work/app", true, true).unwrap();
let store = load();
assert_eq!(store.remote_decision(target, "/srv/work/api").unwrap(), Some(true));
assert_eq!(store.remote_decision(target, "/srv/work/a/b").unwrap(), Some(true));
assert_eq!(store.remote_decision(target, "/srv/workshop").unwrap(), None);
assert_eq!(store.remote_decision(other, "/srv/work/api").unwrap(), None);
// An explicit Don't Trust of a project under it still wins.
store.decide_remote(target, "/srv/work/api", false, false).unwrap();
assert_eq!(store.remote_decision(target, "/srv/work/api").unwrap(), Some(false));
store.remove_remote_location(target, "/srv/work/").unwrap();
assert_eq!(load().remote_decision(target, "/srv/work/lib").unwrap(), None);
assert_eq!(load().remote_decision(target, "/srv/work/app").unwrap(), Some(true));
store.decide_remote(target, "/app", true, true).unwrap();
assert_eq!(store.remote_decision(target, "/anything").unwrap(), Some(true));
}
}
+23 -8
Переглянути файл
@@ -157,7 +157,7 @@ impl Connection {
/// This machine's decision about the project (`None`: none yet). A dev container is its local
/// folder's project, trusted before it was started.
pub fn trusted_here(&self, trust: &ide_host::trust::TrustStore) -> Option<bool> {
match trust.remote_decision(&self.location()) {
match trust.remote_decision(&self.target_key(), &self.root) {
Ok(Some(decision)) => Some(decision),
Ok(None) => match &self.target {
RemoteTarget::DevContainer { folder, .. } => {
@@ -169,9 +169,9 @@ impl Connection {
}
}
/// The key of this project's decisions on this machine.
fn location(&self) -> String {
serde_json::to_string(&(&self.target, &self.root)).unwrap_or_default()
/// The target of this project's decisions on this machine, as JSON.
fn target_key(&self) -> String {
serde_json::to_string(&self.target).unwrap_or_default()
}
}
@@ -1125,9 +1125,9 @@ pub fn remote_trust_status(window: Window, state: State<'_, AppState>) -> IdeRes
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn remote_trust_set(window: Window, state: State<'_, AppState>, trusted: bool) -> IdeResult<()> {
pub fn remote_trust_set(window: Window, state: State<'_, AppState>, trusted: bool, folder: bool) -> IdeResult<()> {
let c = connection(&window, &state)?;
state.host.trust.decide_remote(&c.location(), trusted)?;
state.host.trust.decide_remote(&c.target_key(), &c.root, trusted, folder)?;
if trusted {
let plugins = state.plugins.clone();
let label = AppState::owner_window(window.label()).to_owned();
@@ -1139,6 +1139,15 @@ pub fn remote_trust_set(window: Window, state: State<'_, AppState>, trusted: boo
Ok(())
}
/// Forgets a trusted folder of the window's remote host on this machine.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub fn remote_trust_remove_location(window: Window, state: State<'_, AppState>, folder: String) -> IdeResult<()> {
let c = connection(&window, &state)?;
state.host.trust.remove_remote_location(&c.target_key(), &folder)
}
/// A port of the remote host reachable on this machine at `localhost:local_port`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -1758,12 +1767,17 @@ mod tests {
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
}
assert!(c.authorize(&trust, TrustClass::Always).is_ok());
trust.decide_remote(&c.location(), true).unwrap();
trust.decide_remote(&c.target_key(), &c.root, true, false).unwrap();
assert!(c.authorize(&trust, TrustClass::Trusted).is_ok());
let other = connected(RemoteTarget::Ssh { config: "box".into() }, "/srv/other");
assert!(other.authorize(&trust, TrustClass::Trusted).is_err());
trust.decide_remote(&c.location(), false).unwrap();
trust.decide_remote(&c.target_key(), &c.root, false, false).unwrap();
assert!(c.authorize(&trust, TrustClass::Trusted).is_err());
// Earlier versions keyed decisions by the `(target, root)` tuple's JSON.
assert_eq!(
ide_host::trust::remote_key(&c.target_key(), &c.root),
serde_json::to_string(&(&c.target, &c.root)).unwrap()
);
}
#[tokio::test]
@@ -1819,6 +1833,7 @@ ide_command::desktop_domain!(
remote_invoke,
remote_stop_backend,
remote_stop_forwarding,
remote_trust_remove_location,
remote_trust_set,
remote_trust_status,
);
+1
Переглянути файл
@@ -689,6 +689,7 @@ remote_open always project_host bin
remote_rename trusted project_host bindings async
remote_stop_backend always desktop bindings async
remote_stop_forwarding trusted desktop bindings async
remote_trust_remove_location always desktop bindings sync
remote_trust_set always desktop bindings sync
remote_trust_status always desktop bindings sync
remote_upload_into trusted project_host bindings async
+3 -1
Переглянути файл
@@ -2009,8 +2009,10 @@ export const commands = {
remoteStopBackend: () => typedError<null, IdeError>(__TAURI_INVOKE("remote_stop_backend")),
/** Stops forwarding `remote_port` of `host` (`None`: the remote host itself). */
remoteStopForwarding: (remotePort: number, host: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("remote_stop_forwarding", { remotePort, host })),
/** Forgets a trusted folder of the window's remote host on this machine. */
remoteTrustRemoveLocation: (folder: string) => typedError<null, IdeError>(__TAURI_INVOKE("remote_trust_remove_location", { folder })),
/** Records the user's trust decision for the window's remote project on this machine. */
remoteTrustSet: (trusted: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("remote_trust_set", { trusted })),
remoteTrustSet: (trusted: boolean, folder: boolean) => typedError<null, IdeError>(__TAURI_INVOKE("remote_trust_set", { trusted, folder })),
/** This machine's trust decision for the window's remote project (see [`Connection::authorize`]). */
remoteTrustStatus: () => typedError<TrustStatus, IdeError>(__TAURI_INVOKE("remote_trust_status")),
remoteUploadInto: (connection: FsConnection, paths: IpcPath[], target: string, replace: boolean, request: RequestId) => typedError<TransferReport, IdeError>(__TAURI_INVOKE("remote_upload_into", { connection, paths, target, replace, request })),
+7 -4
Переглянути файл
@@ -3,7 +3,7 @@ import { create } from "zustand";
import { executeAction, registerActions } from "@/platform/actions";
import { call, callDesktop, commands, onIdeEvent, type TrustDecisions, type TrustStatus } from "@/platform/ipc";
import { dirname, useProject } from "@/platform/project";
import { initializeRemoteTrustMigration, isRemoteRoot } from "@/platform/remote";
import { initializeRemoteTrustMigration, isRemoteRoot, isRemoteWindow } from "@/platform/remote";
import { provideProjectTrustPrompt, type ProjectTrustScope } from "@/platform/projectTrust";
import { askOverSplash } from "@/platform/splash";
import { registerOverlay, registerSettingsPage, registerWorkbenchBanner } from "@/workbench/contributions";
@@ -248,7 +248,7 @@ async function decide(trusted: boolean) {
await callDesktop("project_trust_set", { path, trusted, folder });
} else {
await call(commands.projectTrustSet(path, trusted, folder));
if (isRemoteRoot(path)) await call(commands.remoteTrustSet(trusted));
if (isRemoteRoot(path)) await call(commands.remoteTrustSet(trusted, folder));
const project = await commands.projectCurrent();
if (project) useProject.setState({ project, settings: project.settings });
}
@@ -348,7 +348,7 @@ export function activate(): () => void {
const path = typeof arg === "string" ? arg : useProject.getState().project?.root;
if (!path) return;
await call(commands.projectTrustSet(path, false, false));
if (isRemoteRoot(path)) await call(commands.remoteTrustSet(false));
if (isRemoteRoot(path)) await call(commands.remoteTrustSet(false, false));
},
},
{
@@ -357,7 +357,10 @@ export function activate(): () => void {
category: "Project",
hidden: true,
run: async ({ arg }) => {
if (typeof arg === "string") await call(commands.projectTrustRemoveLocation(arg));
if (typeof arg !== "string") return;
await call(commands.projectTrustRemoveLocation(arg));
// A remote window's folder is trusted on this machine too.
if (isRemoteWindow()) await call(commands.remoteTrustRemoveLocation(arg));
},
},
]),
+29 -2
Переглянути файл
@@ -32,12 +32,16 @@ vi.mock("@/platform/ipc", async (original) => {
projectTrustAddLocation: (...args: unknown[]) => addLocation(...args),
remoteTrustStatus: () => remoteStatus(),
remoteTrustSet: (...args: unknown[]) => remoteDecide(...args),
projectTrustRemoveLocation: (...args: unknown[]) => removeLocation(...args),
remoteTrustRemoveLocation: (...args: unknown[]) => remoteRemoveLocation(...args),
projectCurrent: async () => null,
},
};
});
const remoteStatus = vi.fn();
const remoteDecide = vi.fn();
const removeLocation = vi.fn();
const remoteRemoveLocation = vi.fn();
let dispose: () => void;
beforeEach(() => {
vi.mocked(invokeLocal).mockReset();
@@ -49,6 +53,8 @@ beforeEach(() => {
.mockReset()
.mockResolvedValue({ status: "ok", data: { root: "/srv/app", trusted: false, decided: false } });
remoteDecide.mockReset().mockResolvedValue({ status: "ok", data: null });
removeLocation.mockReset().mockResolvedValue({ status: "ok", data: null });
remoteRemoveLocation.mockReset().mockResolvedValue({ status: "ok", data: null });
addLocation.mockReset().mockResolvedValue({ status: "ok", data: null });
listDecisions.mockReset().mockResolvedValue({ status: "ok", data: { projects: [], locations: [], restricted: [] } });
pickFolder.mockReset().mockResolvedValue(null);
@@ -75,7 +81,28 @@ it("asks in a remote window when only the server has a trust decision, and recor
fireEvent.click(screen.getByRole("button", { name: "Preview in Restricted Mode" }));
await act(async () => opening);
expect(decide).toHaveBeenCalledWith("/srv/app", false, false);
expect(remoteDecide).toHaveBeenCalledWith(false);
expect(remoteDecide).toHaveBeenCalledWith(false, false);
});
it("trusts a remote project's folder on this machine too", async () => {
remoteSession();
render(<OverlayHost />);
const opening = confirmProjectTrust("/srv/app");
await screen.findByRole("dialog");
fireEvent.click(screen.getByRole("checkbox"));
fireEvent.click(screen.getByRole("button", { name: "Trust Folder" }));
await act(async () => opening);
expect(decide).toHaveBeenCalledWith("/srv/app", true, true);
expect(remoteDecide).toHaveBeenCalledWith(true, true);
});
it("removes a remote window's trusted folder on this machine too", async () => {
await act(async () => executeAction("project.removeTrustedLocation", "/srv"));
expect(removeLocation).toHaveBeenCalledWith("/srv");
expect(remoteRemoveLocation).not.toHaveBeenCalled();
remoteSession();
await act(async () => executeAction("project.removeTrustedLocation", "/srv"));
expect(remoteRemoveLocation).toHaveBeenCalledWith("/srv");
});
it("reuses a remote project's decision once this machine has the same one", async () => {
@@ -93,7 +120,7 @@ it("revokes a remote project's trust on this machine too", async () => {
useProject.setState({ project: { root: "/srv/app", name: "app", isGit: false, trusted: true, settings: {} } });
await act(async () => executeAction("project.revokeTrust"));
expect(decide).toHaveBeenCalledWith("/srv/app", false, false);
expect(remoteDecide).toHaveBeenCalledWith(false);
expect(remoteDecide).toHaveBeenCalledWith(false, false);
});
it("offers three choices, cancels without a trust decision, and supports restricted preview", async () => {
+1 -1
Переглянути файл
@@ -213,7 +213,7 @@ async function attachRemote(r: RemoteProject, path: string): Promise<void> {
if (takeLegacyRemoteTrust(r.target, path, r.host)) {
const status = await call(commands.projectTrustStatus(r.root));
if (!status.decided) await call(commands.projectTrustSet(r.root, true, false));
if (!(await call(commands.remoteTrustStatus())).decided) await call(commands.remoteTrustSet(true));
if (!(await call(commands.remoteTrustStatus())).decided) await call(commands.remoteTrustSet(true, false));
}
try {
await confirmProjectTrust(r.root);