diff --git a/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue b/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue index 87e9f6f6b7..28baa05b92 100644 --- a/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue +++ b/apps/desktop/src/components/plugins/PluginWorkbenchHost.vue @@ -73,8 +73,10 @@ let bootCacheHit = false; // keeps File objects and in-memory save buffers (`w` ids). Handle ids are // opaque strings end to end — never run them through Number(): ids above // Number.MAX_SAFE_INTEGER silently round, and the registry then rejects every -// read with "unknown plugin file handle". Only paths that came from a native -// dialog or an OS drop reach plugin_file_open — never a plugin-supplied string. +// read with "unknown plugin file handle". Every path is consented to on the +// Rust side — dialogs open there (plugin_file_pick_files / plugin_file_save_as) +// and drops are registered by the native drag-drop pipeline before +// plugin_file_open accepts them — never a plugin-supplied string. let webFileSequence = 0; const webPickedFiles = new Map(); @@ -104,6 +106,9 @@ async function tauriFileApi() { return import("@/lib/backend/tauri"); } +// OS drops are the one flow where the renderer still names a path: the native +// drag-drop pipeline registered the dropped files for THIS webview, and +// plugin_file_open accepts exactly those (one open per dropped file). async function openTauriPluginFile(pluginId: string, path: string, write: boolean): Promise { const { openPluginLocalFile } = await tauriFileApi(); const handle = await openPluginLocalFile(pluginId, path, write); @@ -115,16 +120,15 @@ async function openTauriPluginFile(pluginId: string, path: string, write: boolea async function pickPluginFiles(pluginId: string, options: PluginPickFilesOptions): Promise { if (isTauriRuntime()) { - const { open } = await import("@tauri-apps/plugin-dialog"); - const selected = await open({ multiple: options.multiple === true }); - const paths = Array.isArray(selected) ? selected : selected ? [selected] : []; + // The native dialog is opened on the Rust side: paths never round-trip + // through renderer-controlled arguments, the handles are the only result. + const { pickPluginLocalFiles } = await tauriFileApi(); const files: PluginFileHandleMeta[] = []; - for (const path of paths) { - try { - files.push(await openTauriPluginFile(pluginId, path, false)); - } catch (error) { - console.warn("[DBX][plugin-workbench:pick]", error); - } + for (const handle of await pickPluginLocalFiles(pluginId, options.multiple === true)) { + // Track read AND write handles: unmount must reclaim both (leaked fds + // also burn the shared 64-handle registry quota). + openTauriHandles.add(handle.handleId); + files.push({ handleId: `${tauriHandlePrefix}${handle.handleId}`, name: handle.name, size: handle.size, contentType: handle.contentType }); } return files; } @@ -205,19 +209,15 @@ async function deletePluginStorage(pluginId: string, key: string): Promise async function beginPluginFileSave(pluginId: string, request: { name?: string; contentType?: string; size?: number }): Promise<{ handleId: string; chunkBytes: number } | null> { if (isTauriRuntime()) { - const { save } = await import("@tauri-apps/plugin-dialog"); - const fileName = request.name || "download.bin"; - const extension = fileName.includes(".") ? fileName.split(".").pop() : ""; - const path = await save({ - defaultPath: fileName, - filters: extension ? [{ name: extension.toUpperCase(), extensions: [extension] }] : undefined, - }); - if (!path) return null; - // Route through openTauriPluginFile so the write handle joins - // openTauriHandles: a beginSave the plugin abandons must still be + // The save dialog runs on the Rust side and returns an already-consented + // write handle; only the suggested file name crosses the bridge. Track it + // in openTauriHandles: a beginSave the plugin abandons must still be // reclaimed on unmount instead of burning the shared registry quota. - const handle = await openTauriPluginFile(pluginId, path, true); - return { handleId: handle.handleId, chunkBytes: PLUGIN_SAVE_CHUNK_BYTES }; + const { savePluginLocalFileAs } = await tauriFileApi(); + const handle = await savePluginLocalFileAs(pluginId, request.name || "download.bin"); + if (!handle) return null; + openTauriHandles.add(handle.handleId); + return { handleId: `${tauriHandlePrefix}${handle.handleId}`, chunkBytes: PLUGIN_SAVE_CHUNK_BYTES }; } const handleId = `${webHandlePrefix}${++webFileSequence}`; webSaveBuffers.set(handleId, { name: request.name || "download.bin", contentType: request.contentType || "application/octet-stream", chunks: new Map() }); diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts index fecfa5d99b..9bc66e4051 100644 --- a/apps/desktop/src/lib/backend/http.ts +++ b/apps/desktop/src/lib/backend/http.ts @@ -5383,6 +5383,14 @@ export async function openPluginLocalFile(_pluginId: string, _path: string, _wri throw new Error("Plugin local file access is not available in the web backend"); } +export async function pickPluginLocalFiles(_pluginId: string, _multiple: boolean): Promise { + throw new Error("Plugin local file access is not available in the web backend"); +} + +export async function savePluginLocalFileAs(_pluginId: string, _defaultFileName: string): Promise { + throw new Error("Plugin local file access is not available in the web backend"); +} + export async function readPluginLocalFileChunk(_pluginId: string, _handleId: string, _offset: number, _length?: number): Promise { throw new Error("Plugin local file access is not available in the web backend"); } diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts index 7f18ad9a38..868ea6e2b7 100644 --- a/apps/desktop/src/lib/backend/tauri.ts +++ b/apps/desktop/src/lib/backend/tauri.ts @@ -2724,6 +2724,18 @@ export async function openPluginLocalFile(pluginId: string, path: string, write: return invoke("plugin_file_open", { pluginId, path, write }); } +// The native open/save dialogs run on the Rust side: the host never passes +// paths into the plugin-file registry, it only receives handles for what the +// user picked. Only the OS drop flow still goes through openPluginLocalFile, +// and the Rust command accepts exactly the paths its own drop pipeline granted. +export async function pickPluginLocalFiles(pluginId: string, multiple: boolean): Promise { + return invoke("plugin_file_pick_files", { pluginId, multiple }); +} + +export async function savePluginLocalFileAs(pluginId: string, defaultFileName: string): Promise { + return invoke("plugin_file_save_as", { pluginId, defaultFileName }); +} + export async function readPluginLocalFileChunk(pluginId: string, handleId: string, offset: number, length?: number): Promise { return invoke("plugin_file_read", { pluginId, handleId, offset, length }); } diff --git a/src-tauri/src/commands/plugin_file.rs b/src-tauri/src/commands/plugin_file.rs index 8d50ba9981..d6372d79a3 100644 --- a/src-tauri/src/commands/plugin_file.rs +++ b/src-tauri/src/commands/plugin_file.rs @@ -2,10 +2,15 @@ //! //! Plugin sandboxes run with an opaque origin, so they can neither read local //! files dropped onto the window nor stream multi-gigabyte transfers through a -//! one-shot IPC. The workbench host opens handles through this registry after -//! the user picked the file in a native dialog or dropped it onto the plugin's -//! workbench area — both are explicit user consent, and every open goes through -//! the workbench-host TS layer, which is the only caller of these commands. +//! one-shot IPC. Handles are opened through this registry, and every path +//! enters it through a Rust-anchored consent channel — never a path string the +//! renderer merely claims: +//! - `plugin_file_pick_files` / `plugin_file_save_as` open the native dialog +//! on the Rust side and return handles for exactly what the user picked; +//! - OS drops are captured by the native drag-drop pipeline +//! ([`tauri::Builder::on_window_event`]) and registered per webview, and +//! `plugin_file_open` only accepts a path that this webview actually +//! received, consuming the grant on use. //! //! Every handle is owned by the plugin that opened it: all operations carry the //! caller's plugin id and are rejected unless it matches, and ids come from @@ -20,6 +25,7 @@ use std::sync::Mutex; use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; use serde::Serialize; use tauri::State; +use tauri_plugin_dialog::DialogExt; use uuid::Uuid; /// Mirrors the bridge binary cap: one read/write chunk never exceeds it. @@ -41,12 +47,46 @@ struct OpenFile { #[derive(Default)] pub struct PluginFileState { handles: Mutex>, + /// Local paths the native drag-drop pipeline delivered to each webview, + /// waiting to be claimed by `plugin_file_open`. Registered only by the + /// window-event hook (one grant per dropped file), consumed on open. + dropped_paths: Mutex>>, } impl PluginFileState { pub fn new() -> Self { Self::default() } + + /// Records the files the native drop pipeline just delivered to a webview. + pub fn register_dropped_paths(&self, webview_label: &str, paths: Vec) { + if paths.is_empty() { + return; + } + if let Ok(mut dropped) = self.dropped_paths.lock() { + dropped.entry(webview_label.to_string()).or_default().extend(paths); + } + } + + /// Claims a dropped path for opening: one drop authorizes exactly one + /// open, in the webview that received it. + fn consume_dropped_path(&self, webview_label: &str, path: &str) -> bool { + let Ok(mut dropped) = self.dropped_paths.lock() else { + return false; + }; + let Some(entries) = dropped.get_mut(webview_label) else { + return false; + }; + if let Some(position) = entries.iter().position(|granted| granted == path) { + entries.remove(position); + if entries.is_empty() { + dropped.remove(webview_label); + } + true + } else { + false + } + } } #[derive(Debug, Serialize)] @@ -247,11 +287,115 @@ pub fn close_plugin_file(state: &PluginFileState, plugin_id: &str, handle_id: &s #[tauri::command] pub fn plugin_file_open( state: State<'_, PluginFileState>, + webview: tauri::Webview, plugin_id: String, path: String, write: Option, ) -> Result { - open_plugin_file(&state, &plugin_id, &path, write == Some(true)) + open_dropped_plugin_file(&state, webview.label(), &plugin_id, &path, write == Some(true)) +} + +/// The command-level gate for `plugin_file_open`: after the dialog flows moved +/// to Rust, the only renderer path into this registry is the OS drop flow, so +/// a path alone is never consent — the native drag-drop pipeline must have +/// delivered it to THIS webview. Write handles are dialog-only: a path string +/// is not authorization to create or truncate a file. +fn open_dropped_plugin_file( + state: &PluginFileState, + webview_label: &str, + plugin_id: &str, + path: &str, + write: bool, +) -> Result { + if write { + return Err("write handles are only available through the host save dialog".to_string()); + } + if !state.consume_dropped_path(webview_label, path) { + // Indistinguishable from an OS error to the caller; the host log is + // where a probe attempt can be told apart from a stale drop grant. + log::warn!("plugin_file_open rejected a path the drop pipeline did not grant to webview \"{webview_label}\" (plugin: {plugin_id})"); + return Err("cannot open file: path was not provided by the host".to_string()); + } + open_plugin_file(state, plugin_id, path, false) +} + +/// Opens the native open dialog on the Rust side and returns read handles for +/// exactly the files the user picked. The renderer never sees the paths and +/// cannot pass its own: user consent happens inside this command. +#[tauri::command] +pub async fn plugin_file_pick_files( + app: tauri::AppHandle, + state: State<'_, PluginFileState>, + plugin_id: String, + multiple: Option, +) -> Result, String> { + if plugin_id.trim().is_empty() { + return Err("plugin id is required".to_string()); + } + let picked = if multiple == Some(true) { + let (sender, receiver) = tokio::sync::oneshot::channel(); + app.dialog().file().pick_files(move |paths| { + let _ = sender.send(paths); + }); + receiver.await.map_err(|error| error.to_string())? + } else { + let (sender, receiver) = tokio::sync::oneshot::channel(); + app.dialog().file().pick_file(move |path| { + let _ = sender.send(path); + }); + receiver.await.map_err(|error| error.to_string())?.map(|path| vec![path]) + }; + let mut handles = Vec::new(); + for path in picked.into_iter().flatten() { + let Ok(path) = path.into_path() else { continue }; + match open_plugin_file(&state, &plugin_id, &path.to_string_lossy(), false) { + Ok(handle) => handles.push(handle), + Err(error) => log::warn!("plugin file pick: cannot open {}: {error}", path.display()), + } + } + Ok(handles) +} + +/// Opens the native save dialog on the Rust side and returns a write handle +/// for the path the user confirmed. The renderer only controls the suggested +/// file name: the dialog itself is the consent, and the path never round-trips +/// through renderer-controlled arguments. +#[tauri::command] +pub async fn plugin_file_save_as( + app: tauri::AppHandle, + state: State<'_, PluginFileState>, + plugin_id: String, + default_file_name: Option, +) -> Result, String> { + if plugin_id.trim().is_empty() { + return Err("plugin id is required".to_string()); + } + // The name comes from the plugin; keep it a bare file name. + let file_name = default_file_name + .as_deref() + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(|name| name.rsplit(['/', '\\']).next().unwrap_or("download.bin").to_string()); + let mut dialog = app.dialog().file(); + if let Some(name) = &file_name { + dialog = dialog.set_file_name(name); + } + let extension = file_name + .as_deref() + .and_then(|name| Path::new(name).extension()) + .and_then(|extension| extension.to_str()) + .map(|extension| extension.to_ascii_lowercase()); + if let Some(extension) = &extension { + dialog = dialog.add_filter(extension.to_ascii_uppercase(), &[extension.as_str()]); + } + let (sender, receiver) = tokio::sync::oneshot::channel(); + dialog.save_file(move |path| { + let _ = sender.send(path); + }); + let chosen = receiver.await.map_err(|error| error.to_string())?; + let Some(chosen) = chosen else { return Ok(None) }; + let path = chosen.into_path().map_err(|error| error.to_string())?; + open_plugin_file(&state, &plugin_id, &path.to_string_lossy(), true).map(Some) } #[tauri::command] @@ -397,6 +541,42 @@ mod tests { let _ = std::fs::remove_file(path); } + #[test] + fn dropped_paths_gate_the_open_command() { + let path = temp_file("dropped.bin", b"dropped"); + let state = PluginFileState::new(); + // A path the renderer merely claims is rejected. + let rejected = + open_dropped_plugin_file(&state, "main", OWNER, path.to_string_lossy().as_ref(), false).unwrap_err(); + assert!(rejected.contains("not provided by the host"), "{rejected}"); + // A path granted to a DIFFERENT webview is rejected for this one. + state.register_dropped_paths("other-window", vec![path.to_string_lossy().into_owned()]); + assert!(open_dropped_plugin_file(&state, "main", OWNER, path.to_string_lossy().as_ref(), false).is_err()); + // The granting webview can open exactly once. + state.register_dropped_paths("main", vec![path.to_string_lossy().into_owned()]); + let handle = open_dropped_plugin_file(&state, "main", OWNER, path.to_string_lossy().as_ref(), false) + .expect("open dropped"); + let chunk = read_plugin_file_chunk(&state, OWNER, &handle.handle_id, 0, None).expect("read"); + assert_eq!(BASE64.decode(chunk.data_base64).unwrap(), b"dropped"); + close_plugin_file(&state, OWNER, &handle.handle_id).expect("close"); + assert!( + open_dropped_plugin_file(&state, "main", OWNER, path.to_string_lossy().as_ref(), false).is_err(), + "the drop grant is consumed after one open" + ); + let _ = std::fs::remove_file(path); + } + + #[test] + fn write_handles_are_dialog_only() { + let path = temp_file("no-write.bin", b"keep"); + let state = PluginFileState::new(); + state.register_dropped_paths("main", vec![path.to_string_lossy().into_owned()]); + let error = open_dropped_plugin_file(&state, "main", OWNER, path.to_string_lossy().as_ref(), true).unwrap_err(); + assert!(error.contains("save dialog"), "{error}"); + assert_eq!(std::fs::read(&path).unwrap(), b"keep", "a path string alone must not truncate a file"); + let _ = std::fs::remove_file(path); + } + #[test] fn content_type_is_guessed_from_extension() { let mut path = temp_file("ctype.svg", b""); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 3b8f1ed77e..a774902014 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1779,6 +1779,23 @@ pub fn run() { Ok(()) }) .on_window_event(|window, event| { + // Anchor the plugin-file drop consent on the Rust side: paths are + // registered for the webview that physically received the drop, + // and plugin_file_open consumes them there. Renderer-side drop + // events stay display-only; they cannot mint file access. + if let tauri::WindowEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event { + let dropped: Vec = paths + .iter() + .filter(|path| path.is_file()) + .map(|path| path.to_string_lossy().into_owned()) + .collect(); + if !dropped.is_empty() { + if let Some(state) = window.try_state::() { + state.register_dropped_paths(window.label(), dropped); + } + } + return; + } if let tauri::WindowEvent::Destroyed = event { if let Some(tab_id) = window.label().strip_prefix("detached-tab-") { let _ = window.emit("dbx:detached-tab-lost", serde_json::json!({ "tabId": tab_id })); @@ -1954,6 +1971,8 @@ pub fn run() { commands::connection::load_table_vgroups, commands::connection::delete_table_vgroups_for_connection, commands::plugin_file::plugin_file_open, + commands::plugin_file::plugin_file_pick_files, + commands::plugin_file::plugin_file_save_as, commands::plugin_file::plugin_file_read, commands::plugin_file::plugin_file_write, commands::plugin_file::plugin_file_close,