fix(security): anchor plugin file access on rust-side consent

This commit is contained in:
Jinpy authored and GitHub committed 2026-09-29 17:39:31 +08:00
1 parent 5c8c7e0192
commit 3db93307d0
5 files changed
+247 -28

No files matched your search

@@ -73,8 +73,10 @@ let bootCacheHit = false;
// keeps File objects and in-memory save buffers (`w<n>` ids). Handle ids are // keeps File objects and in-memory save buffers (`w<n>` ids). Handle ids are
// opaque strings end to end — never run them through Number(): ids above // opaque strings end to end — never run them through Number(): ids above
// Number.MAX_SAFE_INTEGER silently round, and the registry then rejects every // 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 // read with "unknown plugin file handle". Every path is consented to on the
// dialog or an OS drop reach plugin_file_open — never a plugin-supplied string. // 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; let webFileSequence = 0;
const webPickedFiles = new Map<string, File>(); const webPickedFiles = new Map<string, File>();
@@ -104,6 +106,9 @@ async function tauriFileApi() {
return import("@/lib/backend/tauri"); 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<PluginFileHandleMeta> { async function openTauriPluginFile(pluginId: string, path: string, write: boolean): Promise<PluginFileHandleMeta> {
const { openPluginLocalFile } = await tauriFileApi(); const { openPluginLocalFile } = await tauriFileApi();
const handle = await openPluginLocalFile(pluginId, path, write); 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<PluginFileHandleMeta[]> { async function pickPluginFiles(pluginId: string, options: PluginPickFilesOptions): Promise<PluginFileHandleMeta[]> {
if (isTauriRuntime()) { if (isTauriRuntime()) {
const { open } = await import("@tauri-apps/plugin-dialog"); // The native dialog is opened on the Rust side: paths never round-trip
const selected = await open({ multiple: options.multiple === true }); // through renderer-controlled arguments, the handles are the only result.
const paths = Array.isArray(selected) ? selected : selected ? [selected] : []; const { pickPluginLocalFiles } = await tauriFileApi();
const files: PluginFileHandleMeta[] = []; const files: PluginFileHandleMeta[] = [];
for (const path of paths) { for (const handle of await pickPluginLocalFiles(pluginId, options.multiple === true)) {
try { // Track read AND write handles: unmount must reclaim both (leaked fds
files.push(await openTauriPluginFile(pluginId, path, false)); // also burn the shared 64-handle registry quota).
} catch (error) { openTauriHandles.add(handle.handleId);
console.warn("[DBX][plugin-workbench:pick]", error); files.push({ handleId: `${tauriHandlePrefix}${handle.handleId}`, name: handle.name, size: handle.size, contentType: handle.contentType });
}
} }
return files; return files;
} }
@@ -205,19 +209,15 @@ async function deletePluginStorage(pluginId: string, key: string): Promise<void>
async function beginPluginFileSave(pluginId: string, request: { name?: string; contentType?: string; size?: number }): Promise<{ handleId: string; chunkBytes: number } | null> { async function beginPluginFileSave(pluginId: string, request: { name?: string; contentType?: string; size?: number }): Promise<{ handleId: string; chunkBytes: number } | null> {
if (isTauriRuntime()) { if (isTauriRuntime()) {
const { save } = await import("@tauri-apps/plugin-dialog"); // The save dialog runs on the Rust side and returns an already-consented
const fileName = request.name || "download.bin"; // write handle; only the suggested file name crosses the bridge. Track it
const extension = fileName.includes(".") ? fileName.split(".").pop() : ""; // in openTauriHandles: a beginSave the plugin abandons must still be
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
// reclaimed on unmount instead of burning the shared registry quota. // reclaimed on unmount instead of burning the shared registry quota.
const handle = await openTauriPluginFile(pluginId, path, true); const { savePluginLocalFileAs } = await tauriFileApi();
return { handleId: handle.handleId, chunkBytes: PLUGIN_SAVE_CHUNK_BYTES }; 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}`; const handleId = `${webHandlePrefix}${++webFileSequence}`;
webSaveBuffers.set(handleId, { name: request.name || "download.bin", contentType: request.contentType || "application/octet-stream", chunks: new Map() }); webSaveBuffers.set(handleId, { name: request.name || "download.bin", contentType: request.contentType || "application/octet-stream", chunks: new Map() });
+8
View File
@@ -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"); throw new Error("Plugin local file access is not available in the web backend");
} }
export async function pickPluginLocalFiles(_pluginId: string, _multiple: boolean): Promise<PluginLocalFileHandle[]> {
throw new Error("Plugin local file access is not available in the web backend");
}
export async function savePluginLocalFileAs(_pluginId: string, _defaultFileName: string): Promise<PluginLocalFileHandle | null> {
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<PluginLocalFileChunk> { export async function readPluginLocalFileChunk(_pluginId: string, _handleId: string, _offset: number, _length?: number): Promise<PluginLocalFileChunk> {
throw new Error("Plugin local file access is not available in the web backend"); throw new Error("Plugin local file access is not available in the web backend");
} }
+12
View File
@@ -2724,6 +2724,18 @@ export async function openPluginLocalFile(pluginId: string, path: string, write:
return invoke("plugin_file_open", { pluginId, path, 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<PluginLocalFileHandle[]> {
return invoke("plugin_file_pick_files", { pluginId, multiple });
}
export async function savePluginLocalFileAs(pluginId: string, defaultFileName: string): Promise<PluginLocalFileHandle | null> {
return invoke("plugin_file_save_as", { pluginId, defaultFileName });
}
export async function readPluginLocalFileChunk(pluginId: string, handleId: string, offset: number, length?: number): Promise<PluginLocalFileChunk> { export async function readPluginLocalFileChunk(pluginId: string, handleId: string, offset: number, length?: number): Promise<PluginLocalFileChunk> {
return invoke("plugin_file_read", { pluginId, handleId, offset, length }); return invoke("plugin_file_read", { pluginId, handleId, offset, length });
} }
+185 -5
View File
@@ -2,10 +2,15 @@
//! //!
//! Plugin sandboxes run with an opaque origin, so they can neither read local //! 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 //! files dropped onto the window nor stream multi-gigabyte transfers through a
//! one-shot IPC. The workbench host opens handles through this registry after //! one-shot IPC. Handles are opened through this registry, and every path
//! the user picked the file in a native dialog or dropped it onto the plugin's //! enters it through a Rust-anchored consent channel — never a path string the
//! workbench area — both are explicit user consent, and every open goes through //! renderer merely claims:
//! the workbench-host TS layer, which is the only caller of these commands. //! - `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 //! 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 //! 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 base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use serde::Serialize; use serde::Serialize;
use tauri::State; use tauri::State;
use tauri_plugin_dialog::DialogExt;
use uuid::Uuid; use uuid::Uuid;
/// Mirrors the bridge binary cap: one read/write chunk never exceeds it. /// Mirrors the bridge binary cap: one read/write chunk never exceeds it.
@@ -41,12 +47,46 @@ struct OpenFile {
#[derive(Default)] #[derive(Default)]
pub struct PluginFileState { pub struct PluginFileState {
handles: Mutex<HashMap<String, OpenFile>>, handles: Mutex<HashMap<String, OpenFile>>,
/// 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<HashMap<String, Vec<String>>>,
} }
impl PluginFileState { impl PluginFileState {
pub fn new() -> Self { pub fn new() -> Self {
Self::default() 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<String>) {
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)] #[derive(Debug, Serialize)]
@@ -247,11 +287,115 @@ pub fn close_plugin_file(state: &PluginFileState, plugin_id: &str, handle_id: &s
#[tauri::command] #[tauri::command]
pub fn plugin_file_open( pub fn plugin_file_open(
state: State<'_, PluginFileState>, state: State<'_, PluginFileState>,
webview: tauri::Webview,
plugin_id: String, plugin_id: String,
path: String, path: String,
write: Option<bool>, write: Option<bool>,
) -> Result<PluginFileHandle, String> { ) -> Result<PluginFileHandle, String> {
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<PluginFileHandle, String> {
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<bool>,
) -> Result<Vec<PluginFileHandle>, 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<String>,
) -> Result<Option<PluginFileHandle>, 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] #[tauri::command]
@@ -397,6 +541,42 @@ mod tests {
let _ = std::fs::remove_file(path); 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] #[test]
fn content_type_is_guessed_from_extension() { fn content_type_is_guessed_from_extension() {
let mut path = temp_file("ctype.svg", b"<svg/>"); let mut path = temp_file("ctype.svg", b"<svg/>");
+19
View File
@@ -1779,6 +1779,23 @@ pub fn run() {
Ok(()) Ok(())
}) })
.on_window_event(|window, event| { .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<String> = 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::<commands::plugin_file::PluginFileState>() {
state.register_dropped_paths(window.label(), dropped);
}
}
return;
}
if let tauri::WindowEvent::Destroyed = event { if let tauri::WindowEvent::Destroyed = event {
if let Some(tab_id) = window.label().strip_prefix("detached-tab-") { if let Some(tab_id) = window.label().strip_prefix("detached-tab-") {
let _ = window.emit("dbx:detached-tab-lost", serde_json::json!({ "tabId": tab_id })); 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::load_table_vgroups,
commands::connection::delete_table_vgroups_for_connection, commands::connection::delete_table_vgroups_for_connection,
commands::plugin_file::plugin_file_open, 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_read,
commands::plugin_file::plugin_file_write, commands::plugin_file::plugin_file_write,
commands::plugin_file::plugin_file_close, commands::plugin_file::plugin_file_close,