Make Background a native feature

- Background replaces the Background Slideshow plugin and the background image of Appearance. It shows a folder as a slideshow, or one image.
- It is on by default. Its module loads at launch only when a folder or an image is chosen.
- Rust keeps the one folder in background-folder.json. The interface never sends a path. Eight background_* commands replace the six deprecated backgrounds_* commands.
- The first start moves the slideshow folder and settings, and keeps the saved image as the image source.
- One blur worker with a cache, fewer folder reads, and a decode before each fade. The hub writes only the changed properties.
- Remove the deprecated folder methods of api.backgrounds. set, get, and subscribe stay for the Project Management plugin.
- Show the view buttons in the workbench test without text, after UI-056.
- Update the tests, the measurement tool, the docs, and UI-057.
This commit is contained in:
Knotty Wyvern
2026-10-29 17:25:17 -07:00
parent 115c32fa92
commit ab868bbe8e
81 changed files with 3179 additions and 812 deletions
+402 -312
View File
@@ -1,99 +1,46 @@
//! The image folder of the Background feature (`src/lib/features/background/`).
//!
//! The host keeps one folder in `background-folder.json` in the app data folder. Only the folder dialog
//! sets it, so the interface never sends a folder path. The commands read the image files directly in
//! that folder and the sidecar file `.runestone-backgrounds.json` with the per-image settings.
//! They use the rules of the plugin folder grants (`folders.rs`): plain file names only, no links,
//! raster images up to 64 MiB, a sidecar up to 1 MiB, and at most 10,000 files in the folder.
use crate::error::{Error, Result};
use crate::folders;
use crate::fsutil::{self, is_link};
use crate::plugins::PluginState;
use base64::Engine;
use serde::Serialize;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use tauri::{AppHandle, Manager, Window};
use tauri_plugin_dialog::DialogExt;
const IMAGE_LIMIT: u64 = 50 * 1024 * 1024;
const SETTINGS_LIMIT: u64 = 1024 * 1024;
const SETTINGS_FILE: &str = ".runestone-backgrounds.json";
const FOLDER_FILE: &str = "background-folder.json";
const SIDECAR: &str = ".runestone-backgrounds.json";
/// The old plugin whose folder grant the migration takes.
const LEGACY_PLUGIN: &str = "runestone.bg-slideshow";
const FOLDER_FILE_LIMIT: u64 = 64 * 1024;
#[derive(Debug, Serialize)]
pub struct BackgroundFile {
name: String,
/// Serializes changes to the folder file.
static LOCK: Mutex<()> = Mutex::new(());
#[derive(Debug, Serialize, Deserialize)]
struct FolderFile {
schema: u32,
path: PathBuf,
}
fn require_plugin(app: &AppHandle, label: &str, id: &str) -> Result<()> {
app.state::<PluginState>().require_lease(app, label, id)
/// The folder file and the plugin data of one app data folder.
struct Host {
data: PathBuf,
}
/// Check the lease on a blocking worker, because the plugin lock can wait for package work.
async fn check_plugin(app: &AppHandle, window: &Window, id: &str) -> Result<()> {
let (app, label, id) = (app.clone(), window.label().to_owned(), id.to_owned());
tauri::async_runtime::spawn_blocking(move || require_plugin(&app, &label, &id)).await?
}
fn folder_root(folder: &Path) -> Result<PathBuf> {
if !folder.is_absolute()
|| folder
.components()
.any(|part| matches!(part, Component::ParentDir))
{
return Err("Supply an absolute background folder path without parent segments.".into());
}
let root = dunce::canonicalize(folder)?;
if !root.is_dir() {
return Err("The background folder does not exist.".into());
}
Ok(root)
}
fn supported(name: &str) -> bool {
fn raster(name: &str) -> bool {
Path::new(name)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
matches!(
extension.to_ascii_lowercase().as_str(),
"png" | "jpg" | "jpeg" | "gif" | "webp"
)
})
}
fn image_path(root: &Path, name: &str) -> Result<PathBuf> {
if name.is_empty()
|| name.contains(['/', '\\', ':'])
|| name.ends_with(['.', ' '])
|| !supported(name)
|| Path::new(name).components().count() != 1
|| !matches!(
Path::new(name).components().next(),
Some(Component::Normal(_))
)
{
return Err("Supply one PNG, JPEG, GIF, or WebP filename.".into());
}
let path = root.join(name);
let metadata = fs::symlink_metadata(&path)?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Background images must be ordinary files, not links.".into());
}
let resolved = dunce::canonicalize(&path)?;
if resolved.parent() != Some(root) {
return Err("The background image is outside its folder.".into());
}
Ok(path)
}
fn list_images(folder: &Path) -> Result<Vec<BackgroundFile>> {
let root = folder_root(folder)?;
let mut images = 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;
};
if supported(&name) && image_path(&root, &name).is_ok() {
images.push(BackgroundFile { name });
}
}
images.sort_by(|a, b| a.name.cmp(&b.name));
Ok(images)
.is_some_and(|extension| matches!(extension.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "gif" | "webp"))
}
fn raster_signature(bytes: &[u8]) -> bool {
@@ -104,176 +51,205 @@ fn raster_signature(bytes: &[u8]) -> bool {
|| (bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP")
}
fn read_image(folder: &Path, name: &str) -> Result<Vec<u8>> {
let root = folder_root(folder)?;
let path = image_path(&root, name)?;
// Open the entry itself so a replaced link cannot redirect the read.
let file = fsutil::open_entry(&path)?;
let metadata = file.metadata()?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Background images must be ordinary files, not links.".into());
}
if metadata.len() > IMAGE_LIMIT {
return Err("The background image exceeds 50 MiB.".into());
}
image_path(&root, name)?;
let Some(bytes) = fsutil::read_to_limit(file, IMAGE_LIMIT)? else {
return Err("The background image exceeds 50 MiB.".into());
};
if !raster_signature(&bytes) {
return Err("The file is not a supported raster image.".into());
}
Ok(bytes)
}
#[tauri::command]
pub async fn backgrounds_default_folder(
app: AppHandle,
window: Window,
id: String,
) -> Result<String> {
check_plugin(&app, &window, &id).await?;
let pictures = app.path().picture_dir()?;
let folder = pictures.join("RuneStone Backgrounds");
let created = folder.clone();
tauri::async_runtime::spawn_blocking(move || fs::create_dir_all(created)).await??;
check_plugin(&app, &window, &id).await?;
folder_root(&folder).map(|root| root.to_string_lossy().into_owned())
}
#[tauri::command]
pub async fn backgrounds_choose_folder(
app: AppHandle,
window: Window,
id: String,
) -> Result<Option<String>> {
check_plugin(&app, &window, &id).await?;
let picker_app = app.clone();
let picker_window = window.clone();
let selected = tauri::async_runtime::spawn_blocking(move || {
picker_app
.dialog()
.file()
.set_parent(&picker_window)
.set_title("Choose background image folder")
.blocking_pick_folder()
})
.await?;
check_plugin(&app, &window, &id).await?;
selected
.map(|source| {
let path = source.into_path().map_err(Error::from_display)?;
folder_root(&path).map(|root| root.to_string_lossy().into_owned())
})
.transpose()
}
#[tauri::command]
pub async fn backgrounds_list(
app: AppHandle,
window: Window,
id: String,
folder: String,
) -> Result<Vec<BackgroundFile>> {
check_plugin(&app, &window, &id).await?;
let result = tauri::async_runtime::spawn_blocking(move || list_images(Path::new(&folder)))
.await??;
check_plugin(&app, &window, &id).await?;
Ok(result)
}
#[tauri::command]
pub async fn backgrounds_read(
app: AppHandle,
window: Window,
id: String,
folder: String,
name: String,
) -> Result<String> {
check_plugin(&app, &window, &id).await?;
let result =
tauri::async_runtime::spawn_blocking(move || read_image(Path::new(&folder), &name))
.await??;
check_plugin(&app, &window, &id).await?;
Ok(base64::engine::general_purpose::STANDARD.encode(result))
}
fn read_image_settings(folder: &Path) -> Result<Option<String>> {
let root = folder_root(folder)?;
let path = root.join(SETTINGS_FILE);
let metadata = match fs::symlink_metadata(&path) {
/// Read a small JSON file. A missing file gives `None`. A link or a folder is an error.
fn read_json<T: for<'de> Deserialize<'de>>(path: &Path, limit: u64) -> Result<Option<T>> {
let metadata = match fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(Error::from(error)),
Err(error) => return Err(error.into()),
};
if !metadata.is_file() || is_link(&metadata) || metadata.len() > SETTINGS_LIMIT {
return Err("Image settings must be an ordinary file within 1 MiB.".into());
}
let file = fsutil::open_entry(&path)?;
let metadata = file.metadata()?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Image settings must be an ordinary file, not a link.".into());
return Err(Error::new(format!("{} must be an ordinary file.", path.display())));
}
let Some(bytes) = fsutil::read_to_limit(file, SETTINGS_LIMIT)? else {
return Err("Image settings exceed 1 MiB.".into());
let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(path)?, limit)? else {
return Err(Error::new(format!("{} is too large.", path.display())));
};
String::from_utf8(bytes).map(Some).map_err(Error::from)
Ok(Some(serde_json::from_slice(&bytes)?))
}
fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) -> Result<()> {
static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _lock = WRITE_LOCK.lock()?;
if contents.len() as u64 > SETTINGS_LIMIT {
return Err("Image settings exceed 1 MiB.".into());
impl Host {
fn file(&self) -> PathBuf {
self.data.join(FOLDER_FILE)
}
let value: serde_json::Value = serde_json::from_str(contents)?;
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1)
|| !value.get("images").is_some_and(serde_json::Value::is_object)
{
return Err("Use image settings with schema 1 and an images object.".into());
fn stored(&self) -> Result<Option<PathBuf>> {
let Some(file) = read_json::<FolderFile>(&self.file(), FOLDER_FILE_LIMIT)? else { return Ok(None) };
if file.schema != 1 {
return Err("Unknown background folder file schema.".into());
}
Ok(Some(file.path))
}
let root = folder_root(folder)?;
if read_image_settings(&root)?.as_deref() != expected {
return Err("Image settings changed. Reload them before saving.".into());
fn save(&self, path: &Path) -> Result<()> {
fs::create_dir_all(&self.data)?;
let bytes = serde_json::to_vec_pretty(&FolderFile { schema: 1, path: path.to_path_buf() })?;
let temp = self.data.join(format!("{FOLDER_FILE}.{}.tmp", uuid::Uuid::new_v4()));
Ok(fsutil::replace_file(&self.file(), &temp, &bytes)?)
}
let path = root.join(SETTINGS_FILE);
if expected.is_some() {
fsutil::write_text(&path, contents, expected)
} else {
// Publish a complete new file without replacing a file created by another process.
let temp = root.join(format!(".runestone-backgrounds-{}.tmp", uuid::Uuid::new_v4()));
Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?)
/// Keep `folder` as the background folder. It must be an existing folder, not a whole drive.
fn choose(&self, folder: &Path) -> Result<String> {
let root = folders::granted_root(folder)?;
let _lock = LOCK.lock()?;
self.save(&root)?;
Ok(root.to_string_lossy().into_owned())
}
/// The kept folder for display, or `None`.
fn folder(&self) -> Result<Option<String>> {
Ok(self.stored()?.map(|path| path.to_string_lossy().into_owned()))
}
fn clear(&self) -> Result<()> {
let _lock = LOCK.lock()?;
match fs::remove_file(self.file()) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()),
_ => Ok(()),
}
}
/// The kept folder, still an ordinary folder at the same resolved path.
/// A folder that became a link or a file does not redirect the access.
fn root(&self) -> Result<PathBuf> {
let path = self.stored()?.ok_or_else(|| Error::new("Choose a background folder first."))?;
let metadata = fs::symlink_metadata(&path).map_err(|_| Error::new("The background folder is missing. Choose the folder again."))?;
if !metadata.is_dir() || is_link(&metadata) || dunce::canonicalize(&path)? != path {
return Err("The background folder changed into a link or a file. Choose the folder again.".into());
}
Ok(path)
}
/// The names of the raster images directly in the folder.
fn list(&self) -> Result<Vec<String>> {
Ok(folders::list_files(&self.root()?)?
.into_iter()
.map(|entry| entry.name)
.filter(|name| raster(name))
.collect())
}
fn read(&self, name: &str) -> Result<Vec<u8>> {
if !raster(name) {
return Err("Supply one PNG, JPEG, GIF, or WebP file name.".into());
}
let bytes = folders::read_file(&self.root()?, name)?;
if !raster_signature(&bytes) {
return Err("The file is not a supported raster image.".into());
}
Ok(bytes)
}
fn read_sidecar(&self) -> Result<Option<String>> {
folders::read_sidecar(&self.root()?, SIDECAR)
}
/// Save the per-image settings only if the file still holds `expected` (`None` when it does not exist).
fn write_sidecar(&self, contents: &str, expected: Option<&str>) -> Result<()> {
let value: serde_json::Value = serde_json::from_str(contents)?;
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1) || !value.get("images").is_some_and(serde_json::Value::is_object) {
return Err("Use image settings with schema 1 and an images object.".into());
}
folders::write_sidecar(&self.root()?, SIDECAR, contents, expected)
}
/// Take the folder of the old Background Slideshow grant when the host has no folder yet.
/// Returns the folder after the migration, or `None`. It changes no plugin file.
fn migrate(&self) -> Result<Option<String>> {
let _lock = LOCK.lock()?;
if let Some(path) = self.stored()? {
return Ok(Some(path.to_string_lossy().into_owned()));
}
let plugin_data = self.data.join("plugin-data");
let settings = plugin_data.join(LEGACY_PLUGIN).join("settings.json");
let Some(value) = read_json::<serde_json::Value>(&settings, 1024 * 1024).ok().flatten() else { return Ok(None) };
let Some(grant) = value.get("grant").and_then(serde_json::Value::as_str).filter(|grant| !grant.is_empty()) else { return Ok(None) };
let Ok(path) = folders::plugin_grant(&plugin_data, LEGACY_PLUGIN, grant) else { return Ok(None) };
self.save(&path)?;
Ok(Some(path.to_string_lossy().into_owned()))
}
}
fn host(app: &AppHandle) -> Result<Host> {
Ok(Host { data: app.path().app_data_dir()? })
}
/// Run `work` on a blocking worker, because the file system calls can wait.
async fn run<T: Send + 'static>(app: &AppHandle, work: impl FnOnce(Host) -> Result<T> + Send + 'static) -> Result<T> {
let host = host(app)?;
tauri::async_runtime::spawn_blocking(move || work(host)).await?
}
/// Show the folder dialog and keep the chosen folder. Returns the folder for display, or `None` after Cancel.
#[tauri::command]
pub async fn background_choose_folder(app: AppHandle, window: Window, title: Option<String>) -> Result<Option<String>> {
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 the background 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)?;
run(&app, move |host| host.choose(&folder)).await.map(Some)
}
#[tauri::command]
pub async fn backgrounds_read_image_settings(app: AppHandle, window: Window, id: String, folder: String) -> Result<Option<String>> {
check_plugin(&app, &window, &id).await?;
let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await??;
check_plugin(&app, &window, &id).await?;
Ok(result)
pub async fn background_folder(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.folder()).await
}
#[tauri::command]
pub async fn backgrounds_write_image_settings(app: AppHandle, window: Window, id: String, folder: String, contents: String, expected: Option<String>) -> Result<()> {
check_plugin(&app, &window, &id).await?;
// Check the lease again immediately before the write on the blocking worker.
tauri::async_runtime::spawn_blocking(move || {
require_plugin(&app, window.label(), &id)?;
write_image_settings(Path::new(&folder), &contents, expected.as_deref())
}).await?
pub async fn background_clear_folder(app: AppHandle) -> Result<()> {
run(&app, |host| host.clear()).await
}
#[tauri::command]
pub async fn background_list(app: AppHandle) -> Result<Vec<String>> {
run(&app, |host| host.list()).await
}
/// Return the bytes as an `ArrayBuffer`, not as JSON or base64 text.
#[tauri::command]
pub async fn background_read(app: AppHandle, name: String) -> Result<tauri::ipc::Response> {
Ok(tauri::ipc::Response::new(run(&app, move |host| host.read(&name)).await?))
}
#[tauri::command]
pub async fn background_read_sidecar(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.read_sidecar()).await
}
#[tauri::command]
pub async fn background_write_sidecar(app: AppHandle, contents: String, expected: Option<String>) -> Result<()> {
run(&app, move |host| host.write_sidecar(&contents, expected.as_deref())).await
}
#[tauri::command]
pub async fn background_migrate(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.migrate()).await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::folders::LIST_LIMIT;
const PNG: &[u8] = b"\x89PNG\r\n\x1a\n";
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let root = std::env::temp_dir()
.join(format!("runestone-backgrounds-{}", uuid::Uuid::new_v4()));
let root = std::env::temp_dir().join(format!("runestone-background-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
Self(root)
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 host(&self) -> Host {
Host { data: self.folder("app") }
}
}
impl Drop for Fixture {
@@ -282,103 +258,217 @@ mod tests {
}
}
#[test]
fn image_settings_preserve_external_changes_and_validate_file_limits() {
let fixture = Fixture::new();
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
let next = r#"{"schema":1,"images":{}}"#;
assert_eq!(read_image_settings(&fixture.0).unwrap(), None);
write_image_settings(&fixture.0, first, None).unwrap();
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
assert!(write_image_settings(&fixture.0, next, None).is_err());
assert!(write_image_settings(&fixture.0, next, Some("stale")).is_err());
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
write_image_settings(&fixture.0, next, Some(first)).unwrap();
assert!(write_image_settings(&fixture.0, r#"{"schema":2,"images":{}}"#, Some(next)).is_err());
assert!(write_image_settings(&fixture.0, &"x".repeat(SETTINGS_LIMIT as usize + 1), Some(next)).is_err());
fs::File::create(fixture.0.join(SETTINGS_FILE)).unwrap().set_len(SETTINGS_LIMIT + 1).unwrap();
assert!(read_image_settings(&fixture.0).is_err());
}
#[test]
fn listing_is_nonrecursive_and_filters_extensions() {
let fixture = Fixture::new();
fs::write(fixture.0.join("a.PNG"), b"\x89PNG\r\n\x1a\n").unwrap();
fs::write(fixture.0.join("b.jpg"), b"\xff\xd8\xff").unwrap();
fs::write(fixture.0.join("text.svg"), b"<svg />").unwrap();
fs::create_dir(fixture.0.join("nested.gif")).unwrap();
fs::write(fixture.0.join("nested.gif/hidden.png"), b"png").unwrap();
let names: Vec<_> = list_images(&fixture.0)
.unwrap()
.into_iter()
.map(|image| image.name)
.collect();
assert_eq!(names, vec!["a.PNG", "b.jpg"]);
assert_eq!(
read_image(&fixture.0, "a.PNG").unwrap(),
b"\x89PNG\r\n\x1a\n"
);
}
#[test]
fn reads_reject_traversal_invalid_images_and_oversized_files() {
let fixture = Fixture::new();
for name in [
"../escape.png",
"nested/image.png",
"nested\\image.png",
"C:\\image.png",
"image.png:stream",
"image.svg",
] {
assert!(read_image(&fixture.0, name).is_err(), "{name}");
/// 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}"),
}
}
assert!(list_images(Path::new("relative")).is_err());
fs::write(fixture.0.join("invalid.png"), b"<svg />").unwrap();
assert!(read_image(&fixture.0, "invalid.png")
.unwrap_err()
.to_string()
.contains("raster"));
let file = fs::File::create(fixture.0.join("large.png")).unwrap();
file.set_len(IMAGE_LIMIT + 1).unwrap();
assert!(read_image(&fixture.0, "large.png")
.unwrap_err()
.to_string()
.contains("50 MiB"));
}
#[test]
fn raster_types_are_recognized() {
for bytes in [
b"\x89PNG\r\n\x1a\n".as_slice(),
b"\xff\xd8\xff",
b"GIF87a",
b"GIF89a",
b"RIFF0000WEBP",
] {
assert!(raster_signature(bytes));
fn the_host_keeps_one_folder_until_it_is_cleared() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let other = fixture.folder("other");
let host = fixture.host();
assert_eq!(host.folder().unwrap(), None);
assert!(host.list().unwrap_err().to_string().contains("Choose a background folder"));
assert_eq!(host.choose(&images).unwrap(), images.to_string_lossy());
// A new host reads the kept folder, as after a restart.
assert_eq!(fixture.host().folder().unwrap(), Some(images.to_string_lossy().into_owned()));
host.choose(&other).unwrap();
assert_eq!(host.folder().unwrap(), Some(other.to_string_lossy().into_owned()));
host.clear().unwrap();
host.clear().unwrap();
assert_eq!(host.folder().unwrap(), None);
}
#[test]
fn the_chosen_folder_must_be_an_existing_folder() {
let fixture = Fixture::new();
let host = fixture.host();
let images = fixture.folder("images");
assert!(host.choose(Path::new("relative")).is_err());
assert!(host.choose(&images.join("..").join("images")).is_err());
assert!(host.choose(&fixture.0.join("missing")).is_err());
fs::write(fixture.0.join("file.txt"), "x").unwrap();
assert!(host.choose(&fixture.0.join("file.txt")).is_err());
let drive = images.ancestors().last().unwrap().to_path_buf();
assert!(host.choose(&drive).is_err());
assert_eq!(host.folder().unwrap(), None);
// A damaged folder file is an error, not a silent reset.
fs::write(host.file(), "{damaged").unwrap();
assert!(host.folder().is_err());
fs::write(host.file(), r#"{"schema":2,"path":"C:\\"}"#).unwrap();
assert!(host.folder().is_err());
}
#[test]
fn the_listing_has_only_the_raster_files_directly_in_the_folder() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
fs::write(images.join("b.PNG"), PNG).unwrap();
fs::write(images.join("a.jpg"), b"\xff\xd8\xff").unwrap();
fs::write(images.join("c.webp"), b"RIFF0000WEBP").unwrap();
fs::write(images.join("text.svg"), b"<svg />").unwrap();
fs::write(images.join("notes.md"), b"# notes").unwrap();
fs::write(images.join(SIDECAR), b"{}").unwrap();
fixture.folder("images/nested.gif");
fs::write(images.join("nested.gif/hidden.png"), PNG).unwrap();
assert_eq!(host.list().unwrap(), vec!["a.jpg", "b.PNG", "c.webp"]);
assert_eq!(host.read("b.PNG").unwrap(), PNG);
}
#[test]
fn reads_reject_other_names_other_types_and_large_files() {
let fixture = Fixture::new();
let images = fixture.folder("images");
fs::write(fixture.0.join("outside.png"), PNG).unwrap();
let host = fixture.host();
host.choose(&images).unwrap();
for name in ["../outside.png", "nested/image.png", "nested\\image.png", "C:\\image.png", "image.png:stream", "image.svg", "notes.md", "", "nul.png"] {
assert!(host.read(name).is_err(), "{name}");
}
assert!(!raster_signature(b"RIFF0000WAVE"));
fs::write(images.join("fake.png"), b"<svg />").unwrap();
assert!(host.read("fake.png").unwrap_err().to_string().contains("raster"));
fs::File::create(images.join("large.png")).unwrap().set_len(folders::READ_LIMIT + 1).unwrap();
assert!(host.read("large.png").unwrap_err().to_string().contains("64 MiB"));
}
#[test]
fn the_listing_has_a_size_limit() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
for index in 0..=LIST_LIMIT {
fs::write(images.join(format!("{index}.png")), b"").unwrap();
}
assert!(host.list().unwrap_err().to_string().contains("10000"));
}
#[test]
fn links_cannot_escape_the_folder() {
let fixture = Fixture::new();
let outside = Fixture::new();
let original = outside.0.join("outside.png");
fs::write(&original, b"\x89PNG\r\n\x1a\n").unwrap();
let link = fixture.0.join("link.png");
#[cfg(unix)]
std::os::unix::fs::symlink(&original, &link).unwrap();
#[cfg(windows)]
if let Err(error) = std::os::windows::fs::symlink_file(&original, &link) {
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.");
return;
}
panic!("{error}");
let images = fixture.folder("images");
let outside = fixture.folder("outside");
fs::write(outside.join("secret.png"), PNG).unwrap();
let host = fixture.host();
host.choose(&images).unwrap();
if !link(&outside.join("secret.png"), &images.join("link.png"), false) {
return;
}
assert!(list_images(&fixture.0).unwrap().is_empty());
assert!(read_image(&fixture.0, "link.png").is_err());
assert!(host.list().unwrap().is_empty());
assert!(host.read("link.png").is_err());
// A kept folder that is replaced by a link loses its access.
let moved = fixture.folder("moved");
host.choose(&moved).unwrap();
fs::remove_dir(&moved).unwrap();
assert!(link(&outside, &moved, true));
assert!(host.list().unwrap_err().to_string().contains("Choose the folder again"));
}
#[test]
fn the_sidecar_keeps_external_changes_and_needs_schema_one() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
let next = r#"{"schema":1,"images":{}}"#;
assert_eq!(host.read_sidecar().unwrap(), None);
host.write_sidecar(first, None).unwrap();
assert_eq!(host.read_sidecar().unwrap().as_deref(), Some(first));
assert!(host.write_sidecar(next, None).is_err());
assert!(host.write_sidecar(next, Some("stale")).is_err());
host.write_sidecar(next, Some(first)).unwrap();
assert_eq!(fs::read_to_string(images.join(SIDECAR)).unwrap(), next);
for bad in [r#"{"schema":2,"images":{}}"#, r#"{"schema":1,"images":[]}"#, "not json"] {
assert!(host.write_sidecar(bad, Some(next)).is_err(), "{bad}");
}
assert!(host.write_sidecar(&format!(r#"{{"schema":1,"images":{{}},"x":"{}"}}"#, "x".repeat(folders::SIDECAR_LIMIT as usize)), Some(next)).is_err());
fs::File::create(images.join(SIDECAR)).unwrap().set_len(folders::SIDECAR_LIMIT + 1).unwrap();
assert!(host.read_sidecar().is_err());
}
fn seed_plugin(fixture: &Fixture, folder: &Path, settings: &str) -> String {
let grant = uuid::Uuid::new_v4().to_string();
let data = fixture.folder(&format!("app/plugin-data/{LEGACY_PLUGIN}"));
fs::write(data.join("folder-grants.json"), serde_json::to_vec(&serde_json::json!({ "schema": 1, "grants": [{ "id": grant, "path": folder }] })).unwrap()).unwrap();
fs::write(data.join("settings.json"), settings.replace("GRANT", &grant)).unwrap();
grant
}
#[test]
fn the_migration_takes_the_folder_of_the_old_grant() {
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT","enabled":true}"#);
let data = fixture.0.join("app/plugin-data").join(LEGACY_PLUGIN);
let before = (fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap());
let host = fixture.host();
assert_eq!(host.migrate().unwrap(), Some(images.to_string_lossy().into_owned()));
assert_eq!(host.folder().unwrap(), Some(images.to_string_lossy().into_owned()));
assert_eq!((fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap()), before, "The migration changes no plugin file.");
}
#[test]
fn the_migration_keeps_an_existing_host_folder() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let chosen = fixture.folder("chosen");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#);
let host = fixture.host();
host.choose(&chosen).unwrap();
assert_eq!(host.migrate().unwrap(), Some(chosen.to_string_lossy().into_owned()));
assert_eq!(host.folder().unwrap(), Some(chosen.to_string_lossy().into_owned()));
}
#[test]
fn the_migration_without_a_usable_grant_keeps_no_folder() {
// No plugin data.
let fixture = Fixture::new();
assert_eq!(fixture.host().migrate().unwrap(), None);
// Settings without a grant, with an unknown grant, and with damaged JSON.
for settings in [r#"{"folder":"D:\\Pictures"}"#, r#"{"grant":"6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90"}"#, r#"{"grant":"not-a-uuid"}"#, "{damaged"] {
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, settings);
let host = fixture.host();
assert_eq!(host.migrate().unwrap(), None, "{settings}");
assert_eq!(host.folder().unwrap(), None);
}
// A granted folder that no longer exists.
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#);
fs::remove_dir(&images).unwrap();
assert_eq!(fixture.host().migrate().unwrap(), None);
}
#[test]
fn raster_types_are_recognized() {
for bytes in [PNG, b"\xff\xd8\xff", b"GIF87a", b"GIF89a", b"RIFF0000WEBP"] {
assert!(raster_signature(bytes));
}
assert!(!raster_signature(b"RIFF0000WAVE"));
assert!(raster("A.JPEG") && raster("b.gif") && !raster("c.svg") && !raster("png"));
}
}
+3 -2
View File
@@ -8,7 +8,7 @@ use crate::error::{Error, Result};
use crate::plugins::{legacy_packages, LegacyPackage};
/// The packages that native features replace. A request for another ID fails.
pub const LEGACY_PACKAGES: [&str; 1] = ["runestone.git"];
pub const LEGACY_PACKAGES: [&str; 2] = ["runestone.git", "runestone.bg-slideshow"];
fn check(ids: &[String]) -> Result<()> {
if ids.len() > LEGACY_PACKAGES.len() {
@@ -33,10 +33,11 @@ mod tests {
#[test]
fn only_the_packages_of_native_features_are_read() {
assert!(check(&["runestone.git".into()]).is_ok());
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok());
assert!(check(&[]).is_ok());
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
assert!(check(&[id.into()]).is_err(), "{id}");
}
assert!(check(&["runestone.git".into(), "runestone.git".into()]).is_err());
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into(), "runestone.git".into()]).is_err());
}
}
+16 -10
View File
@@ -18,9 +18,9 @@ use tauri_plugin_dialog::DialogExt;
const GRANTS_FILE: &str = "folder-grants.json";
const GRANT_LIMIT: usize = 64;
const READ_LIMIT: u64 = 64 * 1024 * 1024;
const SIDECAR_LIMIT: u64 = 1024 * 1024;
const LIST_LIMIT: usize = 10_000;
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(());
@@ -47,7 +47,7 @@ pub struct FolderGrant {
#[derive(Debug, Serialize, PartialEq)]
pub struct FolderEntry {
name: String,
pub(crate) name: String,
size: u64,
}
@@ -172,7 +172,7 @@ impl Grants {
}
/// Resolve a chosen folder. Reject relative paths, parent segments, files, and whole drives.
fn granted_root(folder: &Path) -> Result<PathBuf> {
pub(crate) fn granted_root(folder: &Path) -> Result<PathBuf> {
if !folder.is_absolute() || folder.components().any(|part| matches!(part, Component::ParentDir)) {
return Err("Supply an absolute folder path without parent segments.".into());
}
@@ -200,7 +200,7 @@ fn file_path(root: &Path, name: &str) -> Result<PathBuf> {
}
/// Open one ordinary file. Reject links, also a link that replaces the file after the check.
fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
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());
@@ -213,7 +213,7 @@ fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
Ok((file, opened.len()))
}
fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
pub(crate) fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
let mut entries = Vec::new();
for entry in fs::read_dir(root)? {
let entry = entry?;
@@ -232,7 +232,7 @@ fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
Ok(entries)
}
fn read_file(root: &Path, name: &str) -> Result<Vec<u8>> {
pub(crate) fn read_file(root: &Path, name: &str) -> Result<Vec<u8>> {
let path = file_path(root, name)?;
let (file, size) = open_plain(root, &path)?;
if size > READ_LIMIT {
@@ -251,7 +251,7 @@ fn sidecar_path(root: &Path, name: &str) -> Result<PathBuf> {
file_path(root, name)
}
fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
pub(crate) fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
let path = sidecar_path(root, name)?;
match fs::symlink_metadata(&path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
@@ -267,7 +267,7 @@ fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
}
/// Save a sidecar only if it still holds `expected` (`None` when the file does not exist).
fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> {
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());
@@ -285,6 +285,12 @@ fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>
}
}
/// 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<PathBuf> {
Grants { data: data.to_path_buf() }.resolve(plugin, id)
}
fn grants(app: &AppHandle) -> Result<Grants> {
Ok(Grants { data: app.path().app_data_dir()?.join("plugin-data") })
}
+8 -6
View File
@@ -38,12 +38,14 @@ pub fn run() {
.manage(preferences::PreferencesState::default())
.manage(tab_transfer::TabTransferState::default())
.invoke_handler(tauri::generate_handler![
backgrounds::backgrounds_choose_folder,
backgrounds::backgrounds_default_folder,
backgrounds::backgrounds_list,
backgrounds::backgrounds_read,
backgrounds::backgrounds_read_image_settings,
backgrounds::backgrounds_write_image_settings,
backgrounds::background_choose_folder,
backgrounds::background_folder,
backgrounds::background_clear_folder,
backgrounds::background_list,
backgrounds::background_read,
backgrounds::background_read_sidecar,
backgrounds::background_write_sidecar,
backgrounds::background_migrate,
folders::folders_choose,
folders::folders_picture,
folders::folders_grants,
+2 -2
View File
@@ -20,8 +20,8 @@ use crate::fsutil;
pub const FILE_NAME: &str = "settings.json";
pub const SCHEMA: u64 = 1;
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
/// `features` holds the switches of the native features.
pub const SECTIONS: [&str; 6] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features"];
/// `features` holds the switches of the native features. `background` holds the settings of the Background feature.
pub const SECTIONS: [&str; 7] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background"];
/// The appearance section can hold an image data URL of up to 3,000,000 characters.
pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
pub const CHANGED_EVENT: &str = "settings-changed";