//! Folder grants for plugins. //! //! A plugin gets access to a folder outside the workspace only through a grant. The user makes a //! grant with the folder picker, or the host makes one for a `RuneStone ` folder in Pictures. //! Each plugin has its own grant list in its retained data (`plugin-data//folder-grants.json`). //! A grant gives access to the ordinary files directly in its folder. Names with folder parts, //! links, and files that resolve outside the folder are rejected. The plugin cannot supply a path. use crate::error::{Error, Result}; use crate::fsutil::{self, is_link}; use crate::plugins::PluginState; use serde::{Deserialize, Serialize}; use std::fs; use std::path::{Component, Path, PathBuf}; use std::sync::Mutex; use tauri::{AppHandle, Manager, Window}; use tauri_plugin_dialog::DialogExt; const GRANTS_FILE: &str = "folder-grants.json"; const GRANT_LIMIT: usize = 64; pub(crate) const READ_LIMIT: u64 = 64 * 1024 * 1024; pub(crate) const SIDECAR_LIMIT: u64 = 1024 * 1024; pub(crate) const LIST_LIMIT: usize = 10_000; /// Serializes changes to grant files and sidecar files. static LOCK: Mutex<()> = Mutex::new(()); #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] struct StoredGrant { id: String, path: PathBuf, } #[derive(Debug, Default, Serialize, Deserialize)] struct GrantFile { schema: u32, grants: Vec, } /// What a plugin receives: an opaque ID and the folder path for display. #[derive(Clone, Debug, Serialize, PartialEq)] pub struct FolderGrant { id: String, path: String, name: String, } #[derive(Debug, Serialize, PartialEq)] pub struct FolderEntry { pub(crate) name: String, size: u64, } impl From<&StoredGrant> for FolderGrant { fn from(grant: &StoredGrant) -> Self { Self { id: grant.id.clone(), path: grant.path.to_string_lossy().into_owned(), name: grant .path .file_name() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_else(|| grant.path.to_string_lossy().into_owned()), } } } /// The grant lists of all plugins, in the folder that holds the retained plugin data. struct Grants { data: PathBuf, } impl Grants { fn plugin_folder(&self, plugin: &str, create: bool) -> Result { if plugin.is_empty() || plugin.len() > 128 || !plugin.bytes().all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-') || !fsutil::is_plain_component(plugin) { return Err("Invalid plugin ID.".into()); } let folder = self.data.join(plugin); match fs::symlink_metadata(&folder) { Ok(metadata) if metadata.is_dir() && !is_link(&metadata) => Ok(folder), Ok(_) => Err("The plugin data folder must be an ordinary folder.".into()), Err(error) if error.kind() == std::io::ErrorKind::NotFound && create => { fs::create_dir(&folder)?; Ok(folder) } Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(folder), Err(error) => Err(error.into()), } } fn load(&self, plugin: &str) -> Result> { let path = self.plugin_folder(plugin, false)?.join(GRANTS_FILE); let metadata = match fs::symlink_metadata(&path) { Ok(metadata) => metadata, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), Err(error) => return Err(error.into()), }; if !metadata.is_file() || is_link(&metadata) { return Err("The folder grant list must be an ordinary file.".into()); } let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(&path)?, SIDECAR_LIMIT)? else { return Err("The folder grant list exceeds 1 MiB.".into()); }; let file: GrantFile = serde_json::from_slice(&bytes)?; if file.schema != 1 { return Err("Unknown folder grant list schema.".into()); } Ok(file.grants) } fn save(&self, plugin: &str, grants: Vec) -> Result<()> { let folder = self.plugin_folder(plugin, true)?; let bytes = serde_json::to_vec_pretty(&GrantFile { schema: 1, grants })?; let temp = folder.join(format!("{GRANTS_FILE}.{}.tmp", uuid::Uuid::new_v4())); Ok(fsutil::replace_file(&folder.join(GRANTS_FILE), &temp, &bytes)?) } /// Grant `folder` to `plugin`. Return the existing grant when the plugin already has the folder. fn add(&self, plugin: &str, folder: &Path) -> Result { let path = granted_root(folder)?; let _lock = LOCK.lock()?; let mut grants = self.load(plugin)?; if let Some(existing) = grants.iter().find(|grant| grant.path == path) { return Ok(existing.into()); } if grants.len() >= GRANT_LIMIT { return Err(format!("A plugin can keep at most {GRANT_LIMIT} folder grants. Remove a grant first.").into()); } let grant = StoredGrant { id: uuid::Uuid::new_v4().to_string(), path }; let result = FolderGrant::from(&grant); grants.push(grant); self.save(plugin, grants)?; Ok(result) } fn list(&self, plugin: &str) -> Result> { Ok(self.load(plugin)?.iter().map(FolderGrant::from).collect()) } fn revoke(&self, plugin: &str, id: &str) -> Result { let _lock = LOCK.lock()?; let mut grants = self.load(plugin)?; let count = grants.len(); grants.retain(|grant| grant.id != id); if grants.len() == count { return Ok(false); } self.save(plugin, grants)?; Ok(true) } /// Return the folder of a grant of this plugin. The folder must still be an ordinary folder /// at the same resolved path, so a folder that became a link does not redirect access. fn resolve(&self, plugin: &str, id: &str) -> Result { uuid::Uuid::parse_str(id).map_err(|_| Error::new("Invalid folder grant."))?; let grant = self .load(plugin)? .into_iter() .find(|grant| grant.id == id) .ok_or_else(|| Error::new("This plugin has no grant for the folder. Choose the folder again."))?; let metadata = fs::symlink_metadata(&grant.path) .map_err(|_| Error::new("The granted folder is missing. Choose the folder again."))?; if !metadata.is_dir() || is_link(&metadata) || dunce::canonicalize(&grant.path)? != grant.path { return Err("The granted folder changed into a link or a file. Choose the folder again.".into()); } Ok(grant.path) } } /// Resolve a chosen folder. Reject relative paths, parent segments, files, and whole drives. pub(crate) fn granted_root(folder: &Path) -> Result { if !folder.is_absolute() || folder.components().any(|part| matches!(part, Component::ParentDir)) { return Err("Supply an absolute folder path without parent segments.".into()); } let root = dunce::canonicalize(folder)?; if !root.is_dir() { return Err("The folder does not exist.".into()); } if root.parent().is_none() { return Err("Choose a folder, not a whole drive.".into()); } Ok(root) } /// The path of one ordinary file directly in `root`. fn file_path(root: &Path, name: &str) -> Result { if !fsutil::is_plain_component(name) || name.contains(['/', '\\', ':']) || name.ends_with(' ') || Path::new(name).components().count() != 1 || !matches!(Path::new(name).components().next(), Some(Component::Normal(_))) { return Err("Supply one file name without folder parts.".into()); } Ok(root.join(name)) } /// Open one ordinary file. Reject links, also a link that replaces the file after the check. pub(crate) fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> { let metadata = fs::symlink_metadata(path)?; if !metadata.is_file() || is_link(&metadata) { return Err("Granted folder access is limited to ordinary files, not links or folders.".into()); } let file = fsutil::open_entry(path)?; let opened = file.metadata()?; if !opened.is_file() || is_link(&opened) || dunce::canonicalize(path)?.parent() != Some(root) { return Err("Granted folder access is limited to ordinary files, not links or folders.".into()); } Ok((file, opened.len())) } pub(crate) fn list_files(root: &Path) -> Result> { let mut entries = Vec::new(); for entry in fs::read_dir(root)? { let entry = entry?; let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue }; let Ok(metadata) = entry.metadata() else { continue }; // `DirEntry::metadata` does not follow links. if !metadata.is_file() || is_link(&metadata) || file_path(root, &name).is_err() { continue; } entries.push(FolderEntry { name, size: metadata.len() }); if entries.len() > LIST_LIMIT { return Err(format!("The folder has more than {LIST_LIMIT} files.").into()); } } entries.sort_by(|a, b| a.name.cmp(&b.name)); Ok(entries) } pub(crate) fn read_file(root: &Path, name: &str) -> Result> { let path = file_path(root, name)?; let (file, size) = open_plain(root, &path)?; if size > READ_LIMIT { return Err("The file exceeds 64 MiB.".into()); } fsutil::read_to_limit(file, READ_LIMIT)?.ok_or_else(|| Error::new("The file exceeds 64 MiB.")) } /// A sidecar is a small JSON file that a plugin keeps beside the user's files, such as /// `.runestone-backgrounds.json`. Its name starts with `.runestone-` and ends with `.json`. fn sidecar_path(root: &Path, name: &str) -> Result { let stem = name.strip_prefix(".runestone-").and_then(|rest| rest.strip_suffix(".json")); if !stem.is_some_and(|stem| !stem.is_empty() && stem.len() <= 64 && stem.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')) { return Err("A sidecar file name has the form .runestone-.json.".into()); } file_path(root, name) } pub(crate) fn read_sidecar(root: &Path, name: &str) -> Result> { let path = sidecar_path(root, name)?; match fs::symlink_metadata(&path) { Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(error) => return Err(error.into()), Ok(_) => {} } let (file, size) = open_plain(root, &path)?; if size > SIDECAR_LIMIT { return Err("The sidecar file exceeds 1 MiB.".into()); } let bytes = fsutil::read_to_limit(file, SIDECAR_LIMIT)?.ok_or_else(|| Error::new("The sidecar file exceeds 1 MiB."))?; String::from_utf8(bytes).map(Some).map_err(Error::from) } /// Save a sidecar only if it still holds `expected` (`None` when the file does not exist). pub(crate) fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> { let path = sidecar_path(root, name)?; if contents.len() as u64 > SIDECAR_LIMIT { return Err("The sidecar file exceeds 1 MiB.".into()); } serde_json::from_str::(contents)?; let _lock = LOCK.lock()?; if read_sidecar(root, name)?.as_deref() != expected { return Err("The sidecar file changed. Read it again before you save.".into()); } if expected.is_some() { fsutil::write_text(&path, contents, expected) } else { let temp = root.join(format!(".runestone-sidecar-{}.tmp", uuid::Uuid::new_v4())); Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?) } } /// The folder of one grant of `plugin` in the plugin data folder `data`, with the checks of a normal access. /// The Background feature uses it to take the folder of the old Background Slideshow plugin. It changes no file. pub(crate) fn plugin_grant(data: &Path, plugin: &str, id: &str) -> Result { Grants { data: data.to_path_buf() }.resolve(plugin, id) } fn grants(app: &AppHandle) -> Result { Ok(Grants { data: app.path().app_data_dir()?.join("plugin-data") }) } /// Accept only a plugin that is enabled and loaded in the calling window. /// Check the lease on a blocking worker, because the plugin lock can wait for package work. async fn check(app: &AppHandle, window: &Window, plugin: &str) -> Result<()> { let (app, label, plugin) = (app.clone(), window.label().to_owned(), plugin.to_owned()); tauri::async_runtime::spawn_blocking(move || app.state::().require_lease(&app, &label, &plugin)).await? } /// Check the lease, run `work` on a blocking worker, and check the lease again, /// so that a plugin that stopped during the work receives no result. async fn run( app: &AppHandle, window: &Window, plugin: &str, work: impl FnOnce(Grants) -> Result + Send + 'static, ) -> Result { check(app, window, plugin).await?; let store = grants(app)?; let result = tauri::async_runtime::spawn_blocking(move || work(store)).await??; check(app, window, plugin).await?; Ok(result) } #[tauri::command] pub async fn folders_choose(app: AppHandle, window: Window, plugin: String, title: Option) -> Result> { check(&app, &window, &plugin).await?; let (picker_app, picker_window) = (app.clone(), window.clone()); let title = title.filter(|title| !title.trim().is_empty() && title.len() <= 200).unwrap_or_else(|| "Choose a folder".into()); let selected = tauri::async_runtime::spawn_blocking(move || { picker_app.dialog().file().set_parent(&picker_window).set_title(title).blocking_pick_folder() }) .await?; let Some(selected) = selected else { return Ok(None) }; let folder = selected.into_path().map_err(Error::from_display)?; let id = plugin.clone(); run(&app, &window, &plugin, move |store| store.add(&id, &folder)).await.map(Some) } /// Grant `RuneStone ` in the Pictures folder of the user. Create the folder if necessary. #[tauri::command] pub async fn folders_picture(app: AppHandle, window: Window, plugin: String, name: String) -> Result { if name.is_empty() || name.len() > 64 || name.starts_with([' ', '-', '_']) || !name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_')) || name.ends_with(' ') { return Err("Supply a folder name with letters, digits, spaces, hyphens, or underscores.".into()); } let folder = app.path().picture_dir()?.join(format!("RuneStone {name}")); let id = plugin.clone(); run(&app, &window, &plugin, move |store| { fs::create_dir_all(&folder)?; let metadata = fs::symlink_metadata(&folder)?; if !metadata.is_dir() || is_link(&metadata) { return Err("The Pictures folder entry must be an ordinary folder.".into()); } store.add(&id, &folder) }) .await } #[tauri::command] pub async fn folders_grants(app: AppHandle, window: Window, plugin: String) -> Result> { let id = plugin.clone(); run(&app, &window, &plugin, move |store| store.list(&id)).await } #[tauri::command] pub async fn folders_revoke(app: AppHandle, window: Window, plugin: String, grant: String) -> Result { let id = plugin.clone(); run(&app, &window, &plugin, move |store| store.revoke(&id, &grant)).await } #[tauri::command] pub async fn folders_list(app: AppHandle, window: Window, plugin: String, grant: String) -> Result> { let id = plugin.clone(); run(&app, &window, &plugin, move |store| list_files(&store.resolve(&id, &grant)?)).await } /// Return the bytes as an `ArrayBuffer`, not as JSON or base64 text. #[tauri::command] pub async fn folders_read(app: AppHandle, window: Window, plugin: String, grant: String, name: String) -> Result { let id = plugin.clone(); let bytes = run(&app, &window, &plugin, move |store| read_file(&store.resolve(&id, &grant)?, &name)).await?; Ok(tauri::ipc::Response::new(bytes)) } #[tauri::command] pub async fn folders_read_sidecar(app: AppHandle, window: Window, plugin: String, grant: String, name: String) -> Result> { let id = plugin.clone(); run(&app, &window, &plugin, move |store| read_sidecar(&store.resolve(&id, &grant)?, &name)).await } #[tauri::command] pub async fn folders_write_sidecar(app: AppHandle, window: Window, plugin: String, grant: String, name: String, contents: String, expected: Option) -> Result<()> { check(&app, &window, &plugin).await?; let store = grants(&app)?; // Check the lease again immediately before the write, on the blocking worker. tauri::async_runtime::spawn_blocking(move || { app.state::().require_lease(&app, window.label(), &plugin)?; write_sidecar(&store.resolve(&plugin, &grant)?, &name, &contents, expected.as_deref()) }) .await? } #[cfg(test)] mod tests { use super::*; struct Fixture(PathBuf); impl Fixture { fn new() -> Self { let root = std::env::temp_dir().join(format!("runestone-folders-{}", uuid::Uuid::new_v4())); fs::create_dir(&root).unwrap(); Self(dunce::canonicalize(root).unwrap()) } fn folder(&self, name: &str) -> PathBuf { let path = self.0.join(name); fs::create_dir_all(&path).unwrap(); path } fn store(&self) -> Grants { Grants { data: self.folder("plugin-data") } } } impl Drop for Fixture { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } } /// Make a link, or return `false` when Windows does not allow links for this user. fn link(original: &Path, link: &Path, folder: bool) -> bool { #[cfg(unix)] { let _ = folder; std::os::unix::fs::symlink(original, link).unwrap(); true } #[cfg(windows)] { let result = if folder { std::os::windows::fs::symlink_dir(original, link) } else { std::os::windows::fs::symlink_file(original, link) }; match result { Ok(()) => true, Err(error) if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => { eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege."); false } Err(error) => panic!("{error}"), } } } #[test] fn grants_persist_per_plugin_and_can_be_revoked() { let fixture = Fixture::new(); let images = fixture.folder("images"); fs::write(images.join("a.png"), b"png").unwrap(); let store = fixture.store(); let grant = store.add("org.test.one", &images).unwrap(); assert_eq!(grant.path, images.to_string_lossy()); assert_eq!(grant.name, "images"); // The same folder gives the same grant. assert_eq!(store.add("org.test.one", &images).unwrap().id, grant.id); // A new store reads the saved grants, as after a restart. let reopened = fixture.store(); assert_eq!(reopened.list("org.test.one").unwrap(), vec![grant.clone()]); assert_eq!(read_file(&reopened.resolve("org.test.one", &grant.id).unwrap(), "a.png").unwrap(), b"png"); // Another plugin cannot use the grant ID of the first plugin. assert!(reopened.resolve("org.test.two", &grant.id).is_err()); assert!(reopened.list("org.test.two").unwrap().is_empty()); assert!(!reopened.revoke("org.test.two", &grant.id).unwrap()); assert!(reopened.resolve("org.test.one", &grant.id).is_ok()); assert!(reopened.revoke("org.test.one", &grant.id).unwrap()); assert!(reopened.resolve("org.test.one", &grant.id).is_err()); assert!(reopened.list("org.test.one").unwrap().is_empty()); } #[test] fn grants_reject_invalid_plugins_ids_and_folders() { let fixture = Fixture::new(); let store = fixture.store(); let folder = fixture.folder("images"); for plugin in ["", "..", "../escape", "Upper", "a/b", "a\\b", "con"] { assert!(store.add(plugin, &folder).is_err(), "{plugin}"); } assert!(store.add("org.test.one", Path::new("relative")).is_err()); assert!(store.add("org.test.one", &folder.join("..").join("images")).is_err()); assert!(store.add("org.test.one", &fixture.0.join("missing")).is_err()); fs::write(fixture.0.join("file.txt"), "x").unwrap(); assert!(store.add("org.test.one", &fixture.0.join("file.txt")).is_err()); let drive = folder.ancestors().last().unwrap().to_path_buf(); assert!(store.add("org.test.one", &drive).is_err()); assert!(store.resolve("org.test.one", "not-a-uuid").is_err()); assert!(store.resolve("org.test.one", &uuid::Uuid::new_v4().to_string()).is_err()); } #[test] fn names_cannot_leave_the_granted_folder() { let fixture = Fixture::new(); let root = fixture.folder("images"); fs::write(fixture.0.join("secret.txt"), "secret").unwrap(); fixture.folder("images/nested"); fs::write(root.join("nested/inner.png"), "inner").unwrap(); for name in ["../secret.txt", "..", ".", "nested/inner.png", "nested\\inner.png", "C:\\secret.txt", "/secret.txt", "a.png:stream", "", "nul", "trailing."] { assert!(read_file(&root, name).is_err(), "{name}"); } assert!(read_file(&root, "nested").is_err(), "a folder is not a file"); fs::write(root.join("b.txt"), "b").unwrap(); fs::write(root.join("a.png"), "a").unwrap(); assert_eq!(list_files(&root).unwrap(), vec![FolderEntry { name: "a.png".into(), size: 1 }, FolderEntry { name: "b.txt".into(), size: 1 }]); } #[test] fn links_are_rejected() { let fixture = Fixture::new(); let root = fixture.folder("images"); let outside = fixture.folder("outside"); fs::write(outside.join("secret.png"), "secret").unwrap(); if !link(&outside.join("secret.png"), &root.join("link.png"), false) { return; } assert!(list_files(&root).unwrap().is_empty(), "the listing skips links"); assert!(read_file(&root, "link.png").is_err()); // A granted folder that is replaced by a link loses its access. let store = fixture.store(); let moved = fixture.folder("moved"); let grant = store.add("org.test.one", &moved).unwrap(); fs::remove_dir(&moved).unwrap(); assert!(link(&outside, &moved, true)); assert!(store.resolve("org.test.one", &grant.id).is_err()); } #[test] fn reads_have_a_size_limit() { let fixture = Fixture::new(); let root = fixture.folder("images"); fs::File::create(root.join("large.bin")).unwrap().set_len(READ_LIMIT + 1).unwrap(); assert!(read_file(&root, "large.bin").unwrap_err().to_string().contains("64 MiB")); fs::File::create(root.join(".runestone-large.json")).unwrap().set_len(SIDECAR_LIMIT + 1).unwrap(); assert!(read_sidecar(&root, ".runestone-large.json").is_err()); } #[test] fn sidecars_keep_external_changes_and_accept_only_sidecar_names() { let fixture = Fixture::new(); let root = fixture.folder("images"); let name = ".runestone-backgrounds.json"; let first = r#"{"schema":1,"images":{}}"#; let next = r#"{"schema":1,"images":{"a.png":{}}}"#; assert_eq!(read_sidecar(&root, name).unwrap(), None); write_sidecar(&root, name, first, None).unwrap(); assert!(write_sidecar(&root, name, next, None).is_err()); assert!(write_sidecar(&root, name, next, Some("stale")).is_err()); write_sidecar(&root, name, next, Some(first)).unwrap(); assert_eq!(read_sidecar(&root, name).unwrap().as_deref(), Some(next)); assert!(write_sidecar(&root, name, "not json", Some(next)).is_err()); assert!(write_sidecar(&root, name, &format!("\"{}\"", "x".repeat(SIDECAR_LIMIT as usize)), Some(next)).is_err()); for bad in ["a.png", "settings.json", ".runestone-.json", ".runestone-a/b.json", ".runestone-a.json.png", "../.runestone-a.json"] { assert!(write_sidecar(&root, bad, "{}", None).is_err(), "{bad}"); assert!(read_sidecar(&root, bad).is_err(), "{bad}"); } } }