use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::{ collections::{BTreeMap, BTreeSet}, fs, io::Read, path::{Path, PathBuf}, sync::{Arc, Condvar, Mutex}, time::{Duration, Instant, SystemTime, UNIX_EPOCH}, }; use tauri::{AppHandle, Emitter, Manager}; use tauri_plugin_dialog::DialogExt; use tauri_plugin_opener::OpenerExt; use uuid::Uuid; use crate::error::{Error, Result}; use crate::fsutil; const MAX_FILES: usize = 5000; const MAX_FILE: u64 = 25 * 1024 * 1024; const MAX_TOTAL: usize = 100 * 1024 * 1024; /// The longest time that an update or a removal waits for other windows to stop a plugin. const LEASE_WAIT: Duration = Duration::from_secs(10); fn uid() -> String { Uuid::new_v4().to_string() } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Manifest { schema_version: u32, pub id: String, pub name: String, pub author: String, pub description: String, pub version: String, api_version: u32, entry: String, access: String, } #[derive(Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct Installed { manifest: Manifest, hash: String, enabled: bool, #[serde(default)] installed_at: Option, #[serde(default)] removal: Option, #[serde(default)] removal_files: BTreeMap, } #[derive(Default, Serialize, Deserialize)] struct Catalog { #[serde(default)] plugins: BTreeMap, } #[derive(Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct PluginRow { pub manifest: Manifest, pub hash: String, pub enabled: bool, pub installed_at: Option, pub path: String, pub error: Option, pub removal: bool, } #[derive(Serialize)] pub struct Snapshot { pub root: String, pub plugins: Vec, } #[derive(Clone, Serialize)] pub struct CandidateRow { pub token: String, pub source: String, pub manifest: Option, pub error: Option, } struct Candidate { owner: String, source: Option, directory: PathBuf, hash: String, manifest: Manifest, created: Instant, previous: Option, } #[derive(Serialize, Deserialize)] struct UpdateJournal { previous: Installed, next_hash: String, backup: String, staged: String, } #[derive(Clone, Serialize)] pub struct RemovalPlan { pub token: String, pub plugin: PluginRow, } struct Plan { owner: String, id: String, hash: String, created: Instant, } #[derive(Serialize)] pub struct InstallResult { pub name: String, pub error: Option, } #[derive(Debug)] struct Package { manifest: Manifest, files: BTreeMap>, hash: String, } /// The names, sizes, and modification times of the entries in a package folder. It contains no file data. #[derive(PartialEq, Eq)] struct Stamp(Vec<(String, u64, Option)>); /// The result of a full package read: the manifest, the package hash, and the SHA-256 hash of each file. struct Checked { manifest: Manifest, hash: String, digests: BTreeMap, } impl From<&Package> for Checked { fn from(package: &Package) -> Self { Self { manifest: package.manifest.clone(), hash: package.hash.clone(), digests: package.files.iter().map(|(name, bytes)| (name.clone(), digest(bytes))).collect(), } } } struct Service { root: PathBuf, catalog: Catalog, /// Package checks by folder. An entry is valid while the folder has the same stamp. checked: BTreeMap)>, candidates: BTreeMap, plans: BTreeMap, leases: BTreeMap>, cleanup_errors: BTreeMap, removing: BTreeMap, } #[derive(Default)] pub struct PluginState { inner: Mutex>, /// Signals that a window released one or more plugin leases. released: Condvar, } fn normal_component(name: &str) -> bool { fsutil::is_plain_component(name) && name.len() <= 120 && name .bytes() .all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)) } fn valid_id(id: &str) -> bool { normal_component(id) && id.as_bytes()[0].is_ascii_lowercase() && id .bytes() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b".-".contains(&c)) } fn relative(name: &str) -> Result { if name.len() > 180 || !name.split('/').all(normal_component) { return Err(format!("Invalid package path: {name}").into()); } Ok(name.split('/').collect()) } fn plain(path: &Path) -> Result { let meta = fs::symlink_metadata(path)?; if fsutil::is_reparse_point(&meta) { return Err("Links and junctions are not allowed in plugin paths.".into()); } if meta.file_type().is_symlink() { return Err("Links are not allowed in plugin paths.".into()); } Ok(meta) } fn bounded(path: &Path, limit: u64) -> Result> { let meta = plain(path)?; if !meta.is_file() || meta.len() > limit { return Err("The package contains an invalid or oversized file.".into()); } fsutil::read_to_limit(fs::File::open(path)?, limit)? .ok_or_else(|| "The file exceeds the size limit.".into()) } fn add_file( files: &mut BTreeMap>, names: &mut BTreeSet, total: &mut usize, name: String, bytes: Vec, ) -> Result<()> { relative(&name)?; if !names.insert(name.to_ascii_lowercase()) { return Err("The package contains duplicate file paths.".into()); } *total += bytes.len(); if files.len() >= MAX_FILES || bytes.len() as u64 > MAX_FILE || *total > MAX_TOTAL { return Err("The package exceeds the file count or size limit.".into()); } files.insert(name, bytes); Ok(()) } fn walk( root: &Path, directory: &Path, files: &mut BTreeMap>, names: &mut BTreeSet, total: &mut usize, count: &mut usize, ) -> Result<()> { plain(directory)?; for entry in fs::read_dir(directory)? { let path = entry?.path(); *count += 1; if *count > MAX_FILES { return Err("The package contains too many entries.".into()); } let name = path .strip_prefix(root)? .to_str() .ok_or("The package path is not UTF-8.")? .replace('\\', "/"); relative(&name)?; let meta = plain(&path)?; if meta.is_dir() { walk(root, &path, files, names, total, count)?; } else { add_file(files, names, total, name, bounded(&path, MAX_FILE)?)?; } } Ok(()) } fn fingerprint(files: &BTreeMap>) -> String { let mut hash = Sha256::new(); for (name, bytes) in files { hash.update((name.len() as u64).to_le_bytes()); hash.update(name.as_bytes()); hash.update((bytes.len() as u64).to_le_bytes()); hash.update(bytes); } format!("{:x}", hash.finalize()) } fn directory_files(path: &Path) -> Result>> { let mut files = BTreeMap::new(); walk(path, path, &mut files, &mut BTreeSet::new(), &mut 0, &mut 0)?; Ok(files) } fn tree_hash(path: &Path) -> Result { Ok(fingerprint(&directory_files(path)?)) } fn digest(bytes: &[u8]) -> String { format!("{:x}", Sha256::digest(bytes)) } /// Read the metadata of every entry in a package folder. Links and junctions are errors, as in `walk`. fn stamp(root: &Path) -> Result { fn visit( root: &Path, directory: &Path, entries: &mut Vec<(String, u64, Option)>, ) -> Result<()> { plain(directory)?; for entry in fs::read_dir(directory)? { let path = entry?.path(); if entries.len() >= MAX_FILES { return Err("The package contains too many entries.".into()); } let name = path.strip_prefix(root)?.to_string_lossy().replace('\\', "/"); let meta = plain(&path)?; if meta.is_dir() { entries.push((name + "/", 0, None)); visit(root, &path, entries)?; } else { entries.push((name, meta.len(), meta.modified().ok())); } } Ok(()) } let mut entries = Vec::new(); visit(root, root, &mut entries)?; entries.sort(); Ok(Stamp(entries)) } fn valid_version(version: &str) -> bool { let parts: Vec<_> = version.split('.').collect(); if parts.len() != 3 || parts[..2].iter().any(|part| { part.is_empty() || !part.bytes().all(|byte| byte.is_ascii_digit()) }) { return false; } let digits = parts[2].bytes().take_while(|byte| byte.is_ascii_digit()).count(); digits > 0 && parts[2][digits..].bytes().all(|byte| byte.is_ascii_lowercase()) } fn package(source: &Path) -> Result { let mut files = BTreeMap::new(); let mut names = BTreeSet::new(); let mut total = 0; let meta = plain(source)?; if meta.is_dir() { walk(source, source, &mut files, &mut names, &mut total, &mut 0)?; } else { require_zip(source)?; if meta.len() > MAX_TOTAL as u64 { return Err("The archive exceeds 100 MiB.".into()); } let mut archive = zip::ZipArchive::new(fs::File::open(source)?)?; if archive.len() > MAX_FILES { return Err("The archive contains too many entries.".into()); } let mut archive_names = BTreeSet::new(); for index in 0..archive.len() { let mut file = archive.by_index(index)?; let name = std::str::from_utf8(file.name_raw())? .trim_end_matches('/') .to_string(); relative(&name)?; if !archive_names.insert(name.to_ascii_lowercase()) { return Err("The archive contains duplicate paths.".into()); } if file.unix_mode().is_some_and(|m| { m & 0o170000 != 0 && m & 0o170000 != 0o100000 && m & 0o170000 != 0o040000 }) { return Err("Archive links and special files are not allowed.".into()); } if file.is_dir() { continue; } if file.size() > MAX_FILE { return Err("An archive file exceeds 25 MiB.".into()); } let bytes = fsutil::read_to_limit(file.by_ref(), MAX_FILE)? .ok_or("The package exceeds the file count or size limit.")?; add_file(&mut files, &mut names, &mut total, name, bytes)?; } } let bytes = files .get("plugin.json") .ok_or("The package needs plugin.json at its root.")?; if bytes.len() > 64 * 1024 { return Err("The manifest exceeds 64 KiB.".into()); } let manifest: Manifest = serde_json::from_slice(bytes)?; if !valid_id(&manifest.id) { return Err("The plugin ID is invalid.".into()); } if manifest.schema_version != 1 || manifest.api_version != 1 || manifest.access != "full-app" { return Err("This plugin needs an unsupported schema, API version, or access mode.".into()); } if [ &manifest.name, &manifest.author, &manifest.description, &manifest.version, ] .iter() .any(|v| v.trim().is_empty() || v.len() > 1000) { return Err("The manifest needs a name, author, description, and version.".into()); } if !valid_version(&manifest.version) { return Err("Use a plugin version such as 1.0.0 or 1.0.0a.".into()); } relative(&manifest.entry)?; if !manifest.entry.ends_with(".js") && !manifest.entry.ends_with(".mjs") { return Err("The entry must be a compiled JavaScript module.".into()); } std::str::from_utf8( files .get(&manifest.entry) .ok_or("The entry module is missing.")?, )?; let hash = fingerprint(&files); Ok(Package { manifest, files, hash, }) } fn require_zip(source: &Path) -> Result<()> { if !source .extension() .and_then(|s| s.to_str()) .is_some_and(|s| s.eq_ignore_ascii_case("zip")) || !plain(source)?.is_file() { return Err( "Select a plugin .zip file. The archive must contain plugin.json at its root.".into(), ); } Ok(()) } fn safe_child(parent: &Path, child: &Path) -> Result<()> { plain(parent)?; plain(child)?; let parent = dunce::canonicalize(parent)?; let resolved = dunce::canonicalize(child)?; if resolved.parent() != Some(parent.as_path()) { return Err("The plugin path is outside its managed directory.".into()); } Ok(()) } fn erase(parent: &Path, target: &Path) -> Result<()> { safe_child(parent, target)?; fn descend(path: &Path, boundary: &Path) -> Result<()> { let meta = plain(path)?; if !dunce::canonicalize(path)? .starts_with(boundary) { return Err("Removal escaped its managed directory.".into()); } if meta.is_dir() { for item in fs::read_dir(path)? { descend(&item?.path(), boundary)?; } fs::remove_dir(path).map_err(Error::from) } else { fs::remove_file(path).map_err(Error::from) } } let boundary = dunce::canonicalize(target)?; descend(target, &boundary) } impl Service { fn open(root: PathBuf) -> Result { fs::create_dir_all(&root)?; plain(&root)?; for name in [ "plugins", "plugin-data", "plugin-staging", "plugin-removals", ] { let path = root.join(name); if path.exists() { plain(&path)?; } else { fs::create_dir(&path)?; } safe_child(&root, &path)?; } let state = root.join("plugin-state.json"); let catalog: Catalog = if state.exists() { serde_json::from_slice(&bounded(&state, 4 * 1024 * 1024)?)? } else { Catalog::default() }; for (id, record) in &catalog.plugins { if !valid_id(id) || record.manifest.id != *id { return Err("The plugin catalog contains an invalid ID.".into()); } if let Some(token) = &record.removal { Uuid::parse_str(token)?; } } let mut service = Self { root, catalog, checked: BTreeMap::new(), candidates: BTreeMap::new(), plans: BTreeMap::new(), leases: BTreeMap::new(), cleanup_errors: BTreeMap::new(), removing: BTreeMap::new(), }; service.recover_updates()?; let mut recovered = false; for (id, record) in &mut service.catalog.plugins { if let Some(token) = &record.removal { if service.root.join("plugins").join(id).exists() && !service.root.join("plugin-removals").join(token).exists() { record.removal = None; record.removal_files.clear(); record.enabled = false; recovered = true; } } } if recovered { service.persist()?; } Ok(service) } fn recover_updates(&mut self) -> Result<()> { let staging = self.directory("plugin-staging")?; for entry in fs::read_dir(&staging)? { let entry = entry?; let name = entry.file_name().to_string_lossy().into_owned(); if !name.starts_with("update-") || !name.ends_with(".json") { continue; } let journal: UpdateJournal = serde_json::from_slice(&bounded(&entry.path(), 128 * 1024)?)?; let id = journal.previous.manifest.id.clone(); if !valid_id(&id) { return Err("Invalid plugin update journal.".into()); } Uuid::parse_str(&journal.backup)?; Uuid::parse_str(&journal.staged)?; let target = self.directory("plugins")?.join(&id); let backup = staging.join(&journal.backup); let staged = staging.join(&journal.staged); let committed = self.catalog.plugins.get(&id).is_some_and(|record| record.hash == journal.next_hash) && package(&target).is_ok_and(|current| current.hash == journal.next_hash); if backup.exists() { safe_child(&staging, &backup)?; if package(&backup)?.hash != journal.previous.hash { return Err("The plugin update backup changed.".into()); } if committed { erase(&staging, &backup)?; } else { if target.exists() { safe_child(&self.directory("plugins")?, &target)?; if package(&target)?.hash != journal.next_hash || staged.exists() { return Err("Plugin update recovery requires inspection of the staging directory.".into()); } fs::rename(&target, &staged)?; } fs::rename(&backup, &target)?; } } if !committed { if package(&target)?.hash != journal.previous.hash { return Err("The previous plugin package changed.".into()); } let mut previous = journal.previous; previous.enabled = false; self.catalog.plugins.insert(id.clone(), previous); self.persist()?; } erase(&staging, &entry.path())?; } Ok(()) } fn directory(&self, name: &str) -> Result { let path = self.root.join(name); safe_child(&self.root, &path)?; Ok(path) } fn persist(&self) -> Result<()> { let path = self.root.join("plugin-state.json"); if path.exists() { plain(&path)?; } let temp = self.root.join(format!("plugin-state-{}.tmp", uid())); let data = serde_json::to_vec_pretty(&self.catalog)?; Ok(fsutil::replace_file(&path, &temp, &data)?) } /// Return the package check from the cache while the folder metadata stays the same. /// Otherwise read and hash the package again. Enable and load use `verify`, which always reads the files. fn check(&mut self, path: &Path) -> Result> { let Ok(stamp) = stamp(path) else { self.checked.remove(path); return package(path).map(|current| Arc::new(Checked::from(¤t))); }; if let Some((cached, checked)) = self.checked.get(path) { if *cached == stamp { return Ok(checked.clone()); } } self.remember(path, stamp, package(path)).map(|(_, checked)| checked) } /// Read and hash the package files, and replace the cached check. fn verify(&mut self, path: &Path) -> Result { let Ok(stamp) = stamp(path) else { self.checked.remove(path); return package(path); }; self.remember(path, stamp, package(path)).map(|(current, _)| current) } /// Keep a successful check with the stamp from before the read. A file that changes during the read changes the next stamp. fn remember(&mut self, path: &Path, stamp: Stamp, current: Result) -> Result<(Package, Arc)> { match current { Ok(current) => { let checked = Arc::new(Checked::from(¤t)); self.checked.insert(path.to_owned(), (stamp, checked.clone())); Ok((current, checked)) } Err(error) => { self.checked.remove(path); Err(error) } } } fn row(&mut self, id: &str) -> Result { let removal = self .catalog .plugins .get(id) .ok_or("The plugin is not installed.")? .removal .is_some(); let parent = self.directory("plugins")?; let path = parent.join(id); let checked = if removal { Err("Removal incomplete. Retry file cleanup.".into()) } else { safe_child(&parent, &path).and_then(|_| self.check(&path)) }; let record = &self.catalog.plugins[id]; let mut manifest = record.manifest.clone(); if let Ok(current) = &checked { if current.manifest.id == id { manifest = current.manifest.clone(); } } let (hash, error) = match checked { Ok(current) if current.manifest.id != id => ( current.hash.clone(), Some("The installed plugin ID changed.".into()), ), Ok(current) if current.hash != record.hash => ( current.hash.clone(), Some("Plugin files changed. Review them before enabling this plugin.".into()), ), Ok(current) => (current.hash.clone(), self.cleanup_errors.get(id).cloned()), Err(error) => (record.hash.clone(), Some(error.to_string())), }; Ok(PluginRow { manifest, hash, enabled: record.enabled && error.is_none() && !self.removing.contains_key(id), installed_at: record.installed_at, path: path.to_string_lossy().into_owned(), error, removal: record.removal.is_some(), }) } fn snapshot(&mut self) -> Result { let mut changed = false; let directory = self.directory("plugins")?; for entry in fs::read_dir(&directory)? { let path = entry?.path(); let id = path .file_name() .unwrap_or_default() .to_string_lossy() .into_owned(); if !valid_id(&id) || self.catalog.plugins.contains_key(&id) { continue; } if let Ok(current) = safe_child(&directory, &path).and_then(|_| self.check(&path)) { if current.manifest.id == id { self.catalog.plugins.insert( id, Installed { manifest: current.manifest.clone(), hash: current.hash.clone(), enabled: false, installed_at: None, removal: None, removal_files: BTreeMap::new(), }, ); changed = true; } } } // Forget the checks of folders that no longer exist. self.checked.retain(|path, _| path.exists()); let mut plugins = Vec::new(); for id in self.catalog.plugins.keys().cloned().collect::>() { if !directory.join(&id).exists() && self.catalog.plugins[&id].removal.is_none() { self.catalog.plugins.remove(&id); changed = true; continue; } let row = self.row(&id)?; if row.error.is_some() && self.catalog.plugins[&id].enabled { self.catalog.plugins.get_mut(&id).unwrap().enabled = false; changed = true; } plugins.push(row); } if changed { self.persist()?; } Ok(Snapshot { root: directory.to_string_lossy().into_owned(), plugins, }) } fn inspect(&mut self, owner: &str, source: PathBuf) -> CandidateRow { let token = uid(); let display = source.to_string_lossy().into_owned(); let result = (|| -> Result { let current = package(&source)?; let previous = self.catalog.plugins.get(¤t.manifest.id).cloned(); if let Some(record) = &previous { let row = self.row(¤t.manifest.id)?; if row.error.is_some() || record.removal.is_some() || self.removing.contains_key(¤t.manifest.id) { return Err("Finish plugin cleanup before updating it.".into()); } } else if self.directory("plugins")?.join(¤t.manifest.id).exists() { return Err("Refresh the plugin list before installing this package.".into()); } let staging = self.directory("plugin-staging")?.join(&token); fs::create_dir(&staging)?; for (name, bytes) in ¤t.files { let target = staging.join(relative(name)?); if self .root .join("plugins") .join(¤t.manifest.id) .join(relative(name)?) .as_os_str() .len() > 240 { return Err("The installed path would exceed 240 characters.".into()); } fs::create_dir_all(target.parent().unwrap())?; fs::write(target, bytes)?; } let manifest = current.manifest.clone(); self.candidates.insert( token.clone(), Candidate { owner: owner.into(), source: Some(source), directory: staging, hash: current.hash, manifest: manifest.clone(), created: Instant::now(), previous, }, ); Ok(manifest) })(); match result { Ok(manifest) => CandidateRow { token, source: display, manifest: Some(manifest), error: None, }, Err(error) => { if let Ok(parent) = self.directory("plugin-staging") { let target = parent.join(&token); if target.exists() { let _ = erase(&parent, &target); } } CandidateRow { token, source: display, manifest: None, error: Some(error.to_string()), } } } } fn inspect_download(&mut self, owner: &str, download: crate::plugin_sources::Download) -> Result { let parent = self.directory("plugin-staging")?; let archive = parent.join(format!("{}.zip", uid())); fs::write(&archive, download.bytes)?; let mut row = self.inspect(owner, archive.clone()); if let Some(candidate) = self.candidates.get_mut(&row.token) { // Review pins the downloaded bytes. Remote releases can change independently. candidate.source = None; } row.source = download.source; if let Err(error) = erase(&parent, &archive) { if let Some(candidate) = self.candidates.remove(&row.token) { let _ = erase(&parent, &candidate.directory); } return Err(error); } Ok(row) } fn install(&mut self, owner: &str, token: &str, enabled: bool) -> Result { let candidate = self .candidates .get(token) .ok_or("Select the package again.")?; if candidate.owner != owner || candidate.created.elapsed() > Duration::from_secs(1800) { return Err("The package review expired. Select it again.".into()); } let id = candidate.manifest.id.clone(); if candidate.previous.is_some() { return self.update(owner, token); } if self.catalog.plugins.contains_key(&id) { return Err("This plugin ID is already installed.".into()); } if candidate.source.as_ref().map(|source| package(source)).transpose()?.is_some_and(|source| source.hash != candidate.hash) || package(&candidate.directory)?.hash != candidate.hash { return Err("The package changed after review. Select it again.".into()); } let parent = self.directory("plugins")?; let target = parent.join(&id); if target.exists() { return Err("The plugin directory already exists.".into()); } safe_child(&self.directory("plugin-staging")?, &candidate.directory)?; let installed_at = SystemTime::now() .duration_since(UNIX_EPOCH)? .as_millis() as u64; // Persist disabled first. A crash cannot enable unreviewed or partial code. self.catalog.plugins.insert( id.clone(), Installed { manifest: candidate.manifest.clone(), hash: candidate.hash.clone(), enabled: false, installed_at: Some(installed_at), removal: None, removal_files: BTreeMap::new(), }, ); if let Err(error) = self.persist() { self.catalog.plugins.remove(&id); return Err(error); } let candidate = self.candidates.remove(token).unwrap(); self.checked.remove(&target); if let Err(error) = fs::rename(&candidate.directory, &target) { self.catalog.plugins.remove(&id); let _ = self.persist(); return Err(Error::from(error)); } if enabled { self.catalog.plugins.get_mut(&id).unwrap().enabled = true; if let Err(error) = self.persist() { self.catalog.plugins.get_mut(&id).unwrap().enabled = false; return Err(format!("Installed but disabled: {error}").into()); } } Ok(candidate.manifest.name) } fn begin_update(&mut self, owner: &str, token: &str) -> Result> { let candidate = self.candidates.get(token).ok_or("Select the package again.")?; if candidate.owner != owner || candidate.created.elapsed() > Duration::from_secs(1800) { return Err("The package review expired. Select it again.".into()); } let Some(previous) = &candidate.previous else { return Ok(None); }; let id = candidate.manifest.id.clone(); let current = self.catalog.plugins.get(&id).ok_or("The installed plugin changed. Select the package again.")?; if current.hash != previous.hash || current.enabled != previous.enabled || current.removal.is_some() || self.removing.contains_key(&id) || self.cleanup_errors.contains_key(&id) || package(&self.directory("plugins")?.join(&id))?.hash != previous.hash { return Err("The installed plugin changed. Refresh and select the package again.".into()); } self.catalog.plugins.get_mut(&id).unwrap().enabled = false; if let Err(error) = self.persist() { self.catalog.plugins.get_mut(&id).unwrap().enabled = previous.enabled; return Err(error); } self.removing.insert(id.clone(), previous.hash.clone()); Ok(Some(id)) } fn update(&mut self, owner: &str, token: &str) -> Result { let candidate = self.candidates.get(token).ok_or("Select the package again.")?; if candidate.owner != owner || candidate.created.elapsed() > Duration::from_secs(1800) { return Err("The package review expired. Select it again.".into()); } let previous = candidate.previous.clone().ok_or("The plugin update is unavailable.")?; let id = candidate.manifest.id.clone(); if self.removing.get(&id) != Some(&previous.hash) { return Err("Start the plugin update again.".into()); } if self.leased(&id) || self.cleanup_errors.contains_key(&id) { return Err("Plugin cleanup did not finish. Close other RuneStone windows and retry the update.".into()); } if candidate.source.as_ref().map(|source| package(source)).transpose()?.is_some_and(|source| source.hash != candidate.hash) || package(&candidate.directory)?.hash != candidate.hash { return Err("The package changed after review. Select it again.".into()); } let parent = self.directory("plugins")?; let target = parent.join(&id); safe_child(&parent, &target)?; if package(&target)?.hash != previous.hash { return Err("Plugin files changed during shutdown. Select the package again.".into()); } let staging = self.directory("plugin-staging")?; safe_child(&staging, &candidate.directory)?; let backup = staging.join(uid()); let journal_path = staging.join(format!("update-{}.json", uid())); let journal = UpdateJournal { previous: previous.clone(), next_hash: candidate.hash.clone(), backup: backup.file_name().unwrap().to_string_lossy().into_owned(), staged: candidate.directory.file_name().unwrap().to_string_lossy().into_owned() }; fs::write(&journal_path, serde_json::to_vec(&journal)?)?; self.checked.remove(&target); fs::rename(&target, &backup)?; if let Err(error) = fs::rename(&candidate.directory, &target) { fs::rename(&backup, &target)?; let _ = erase(&staging, &journal_path); return Err(Error::from(error)); } self.catalog.plugins.insert(id.clone(), Installed { manifest: candidate.manifest.clone(), hash: candidate.hash.clone(), enabled: previous.enabled, installed_at: Some(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64), removal: None, removal_files: BTreeMap::new(), }); if let Err(error) = self.persist() { fs::rename(&target, &candidate.directory)?; fs::rename(&backup, &target)?; self.catalog.plugins.insert(id, previous); let _ = erase(&staging, &journal_path); return Err(error); } let name = self.candidates.remove(token).unwrap().manifest.name; // The backup contains only the exact package approved before shutdown. if package(&backup).is_ok_and(|old| old.hash == previous.hash) { let _ = erase(&staging, &backup); } let _ = erase(&staging, &journal_path); Ok(name) } fn prepare(&mut self, owner: &str, id: &str) -> Result { if self.removing.contains_key(id) { return Err("This plugin is already being removed.".into()); } let plugin = self.row(id)?; if plugin.removal { return Err("Retry cleanup for the confirmed removal.".into()); } // A corrupt package cannot expand the removal target beyond its recorded folder. let current_hash = tree_hash(&self.directory("plugins")?.join(id))?; let token = uid(); self.plans.insert( token.clone(), Plan { owner: owner.into(), id: id.into(), hash: current_hash, created: Instant::now(), }, ); Ok(RemovalPlan { token, plugin }) } fn begin_remove(&mut self, owner: &str, token: &str) -> Result { let plan = self.plans.remove(token).ok_or("Start uninstall again.")?; if plan.owner != owner || plan.created.elapsed() > Duration::from_secs(300) { return Err( "The removal plan expired or belongs to another window. Start uninstall again." .into(), ); } let parent = self.directory("plugins")?; let target = parent.join(&plan.id); safe_child(&parent, &target)?; if tree_hash(&target)? != plan.hash { return Err("Plugin files changed. Confirm uninstall again.".into()); } if self.removing.contains_key(&plan.id) { return Err("This plugin is already being removed.".into()); } let record = self .catalog .plugins .get_mut(&plan.id) .ok_or("The plugin is not installed.")?; let was_enabled = record.enabled; record.enabled = false; if let Err(error) = self.persist() { self.catalog.plugins.get_mut(&plan.id).unwrap().enabled = was_enabled; return Err(error); } self.removing.insert(plan.id.clone(), plan.hash); Ok(plan.id) } fn finish_remove(&mut self, id: &str) -> Result<()> { if self.leased(id) { return Err("Removal blocked. Close other RuneStone windows and try again.".into()); } if let Some(error) = self.cleanup_errors.get(id) { return Err(format!( "Cleanup failed. Restart RuneStone before removal. {error}" ).into()); } let parent = self.directory("plugins")?; let target = parent.join(id); safe_child(&parent, &target)?; let current_files = directory_files(&target)?; let current_hash = fingerprint(¤t_files); if self.removing.get(id) != Some(¤t_hash) { return Err("Plugin files changed during shutdown. Confirm uninstall again.".into()); } let token = uid(); // This journal is the only authorization for recovery after a crash. let record = self .catalog .plugins .get_mut(id) .ok_or("The plugin is not installed.")?; record.removal = Some(token.clone()); record.removal_files = current_files .iter() .map(|(name, bytes)| (name.clone(), digest(bytes))) .collect(); self.persist()?; self.checked.remove(&target); let destination = self.directory("plugin-removals")?.join(token); if let Err(error) = fs::rename(&target, &destination) { self.catalog.plugins.get_mut(id).unwrap().removal = None; let _ = self.persist(); return Err(Error::from(error)); } if tree_hash(&destination)? != current_hash { return Err("Plugin files changed during removal. Inspect the removal directory before retrying.".into()); } self.retry_removal(id) } fn retry_removal(&mut self, id: &str) -> Result<()> { let token = self .catalog .plugins .get(id) .and_then(|record| record.removal.clone()) .ok_or("No confirmed removal exists.")?; Uuid::parse_str(&token)?; let parent = self.directory("plugin-removals")?; let target = parent.join(&token); if self.directory("plugins")?.join(id).exists() { return Err( "Removal did not move the package. Restart and confirm uninstall again.".into(), ); } if target.exists() { safe_child(&parent, &target)?; let expected = &self.catalog.plugins[id].removal_files; for (name, bytes) in directory_files(&target)? { if expected.get(&name) != Some(&digest(&bytes)) { return Err(format!( "Removal files changed. Inspect {} before retrying.", target.display() ).into()); } } erase(&parent, &target)?; } let old = self.catalog.plugins.remove(id).unwrap(); if let Err(error) = self.persist() { self.catalog.plugins.insert(id.into(), old); return Err(error); } Ok(()) } } impl Service { /// Return true when a window holds a lease for the plugin. fn leased(&self, id: &str) -> bool { self.leases.get(id).is_some_and(|windows| !windows.is_empty()) } fn set_enabled(&mut self, id: &str, enabled: bool, hash: Option<&str>) -> Result<()> { if self.removing.contains_key(id) { return Err("Wait for plugin removal to finish.".into()); } let row = self.row(id)?; if row.removal { return Err("Finish the confirmed removal first.".into()); } let old = self.catalog.plugins[id].clone(); if enabled { if self.cleanup_errors.contains_key(id) { return Err("Restart RuneStone after the cleanup failure.".into()); } // Enable reads every file. The cache alone cannot approve code. let current = self.verify(&self.directory("plugins")?.join(id))?; if current.manifest.id != id || hash != Some(current.hash.as_str()) { return Err("Plugin files changed. Refresh and review them again.".into()); } let record = self.catalog.plugins.get_mut(id).unwrap(); record.hash = current.hash; record.manifest = current.manifest; } self.catalog.plugins.get_mut(id).unwrap().enabled = enabled; if let Err(error) = self.persist() { self.catalog.plugins.insert(id.into(), old); return Err(error); } Ok(()) } /// Return the entry module and record a lease for the window `owner`. Load reads every file. fn load(&mut self, owner: &str, id: &str, hash: &str) -> Result { let row = self.row(id)?; if !row.enabled || row.hash != hash { return Err("The plugin is disabled or changed.".into()); } let mut current = self.verify(&self.directory("plugins")?.join(id))?; if current.hash != hash { return Err("The plugin changed during loading.".into()); } self.leases.entry(id.into()).or_default().insert(owner.into()); let entry = current.files.remove(¤t.manifest.entry).unwrap_or_default(); String::from_utf8(entry).map_err(Error::from) } /// Read one file of an enabled plugin. The file must have the hash from the last full package read. fn asset(&mut self, id: &str, path: &str) -> Result> { if !self.row(id)?.enabled { return Err("The plugin is disabled.".into()); } let name = relative(path)?; let folder = self.directory("plugins")?.join(id); let current = self.check(&folder)?; if current.hash != self.catalog.plugins[id].hash { return Err("Plugin assets changed. Review the package again.".into()); } let expected = current.digests.get(path).ok_or("The plugin asset is missing.")?; let bytes = bounded(&folder.join(name), MAX_FILE)?; if digest(&bytes) != *expected { // The next check reads the package again and reports the change. self.checked.remove(&folder); return Err("Plugin assets changed. Review the package again.".into()); } Ok(bytes) } /// Accept only a plugin that is enabled and loaded in the window `owner`. fn require_lease(&self, owner: &str, id: &str) -> Result<()> { let record = self.catalog.plugins.get(id); let enabled = record.is_some_and(|record| record.enabled && record.removal.is_none()); let leased = self.leases.get(id).is_some_and(|windows| windows.contains(owner)); if enabled && leased { return Ok(()); } Err(match record { Some(record) => format!("The {} plugin is not enabled in this window.", record.manifest.name), None => "This plugin is not enabled in this window.".into(), } .into()) } /// Remove the window's leases, removal plans, and reviewed packages. /// Return the staging folder and the review folders to erase. fn release_window(&mut self, owner: &str) -> (PathBuf, Vec) { for windows in self.leases.values_mut() { windows.remove(owner); } self.plans.retain(|_, plan| plan.owner != owner); let tokens: Vec<_> = self .candidates .iter() .filter(|(_, candidate)| candidate.owner == owner) .map(|(token, _)| token.clone()) .collect(); let folders = tokens .iter() .filter_map(|token| self.candidates.remove(token)) .map(|candidate| candidate.directory) .collect(); (self.root.clone(), folders) } } /// Review folders to erase after the plugin lock opens. No other code uses them. pub struct StagingCleanup(Option<(PathBuf, Vec)>); impl StagingCleanup { pub fn erase(self) { let Some((root, folders)) = self.0 else { return }; let parent = root.join("plugin-staging"); if folders.is_empty() || safe_child(&root, &parent).is_err() { return; } for folder in folders { let _ = erase(&parent, &folder); } } } impl PluginState { pub fn require_lease(&self, app: &AppHandle, owner: &str, id: &str) -> Result<()> { self.with(app, |service| service.require_lease(owner, id)) } fn with( &self, app: &AppHandle, action: impl FnOnce(&mut Service) -> Result, ) -> Result { let mut guard = self.inner.lock()?; if guard.is_none() { *guard = Some(Service::open(app.path().app_data_dir()?)?); } action(guard.as_mut().unwrap()) } /// Run `action` on a blocking worker. Package reads, hashes, and copies do not stop an async runtime thread. async fn run( app: &AppHandle, action: impl FnOnce(&mut Service) -> Result + Send + 'static, ) -> Result { let app = app.clone(); tauri::async_runtime::spawn_blocking(move || app.state::().with(&app, action)).await? } /// Wait until no window holds a lease for `id`, or until `limit` ends. Return true when no lease remains. /// The plugin lock is open while this function waits. fn wait_for_release(&self, id: &str, limit: Duration) -> Result { let deadline = Instant::now() + limit; let mut guard = self.inner.lock()?; loop { if !guard.as_ref().is_some_and(|service| service.leased(id)) { return Ok(true); } let left = deadline.saturating_duration_since(Instant::now()); if left.is_zero() { return Ok(false); } guard = self.released.wait_timeout(guard, left)?.0; } } /// Release the window without waiting. Return `None` when another command holds the plugin lock. pub fn try_release_window(&self, owner: &str) -> Option { match self.inner.try_lock() { Ok(mut guard) => { let cleanup = StagingCleanup(guard.as_mut().map(|service| service.release_window(owner))); drop(guard); self.released.notify_all(); Some(cleanup) } Err(std::sync::TryLockError::WouldBlock) => None, Err(std::sync::TryLockError::Poisoned(_)) => Some(StagingCleanup(None)), } } /// Release the window. Wait for the plugin lock, but erase the review folders after it opens. pub fn close_window(&self, owner: &str) { let cleanup = match self.inner.lock() { Ok(mut guard) => StagingCleanup(guard.as_mut().map(|service| service.release_window(owner))), Err(_) => return, }; self.released.notify_all(); cleanup.erase(); } } fn changed(app: &AppHandle) { let _ = app.emit("plugins-changed", ()); } #[tauri::command] pub async fn plugins_snapshot(app: AppHandle) -> Result { PluginState::run(&app, |service| service.snapshot()).await } #[tauri::command] pub async fn plugins_choose(app: AppHandle, window: tauri::Window) -> Result> { let picker_app = app.clone(); let source = tauri::async_runtime::spawn_blocking(move || { picker_app .dialog() .file() .set_title("Install plugin ZIP") .add_filter("Plugin ZIP archives", &["zip"]) .blocking_pick_files() }) .await?; let Some(sources) = source else { return Ok(Vec::new()); }; if sources.len() > 100 { return Err("Select at most 100 plugin ZIP files.".into()); } let paths: Vec = sources .into_iter() .map(|source| source.into_path().map_err(Error::from_display)) .collect::>()?; let owner = window.label().to_owned(); PluginState::run(&app, move |service| { for path in &paths { require_zip(path)?; } Ok(paths .into_iter() .map(|path| service.inspect(&owner, path)) .collect()) }) .await } #[tauri::command] pub async fn plugins_from_git( app: AppHandle, window: tauri::Window, url: String, tag: String, token: Option, ) -> Result> { let repository = crate::plugin_sources::Repository::parse(&url, &tag)?; // Network access never holds the plugin service lock. let download = tauri::async_runtime::spawn_blocking(move || { crate::plugin_sources::download(&repository, token.as_deref()) }).await??; let owner = window.label().to_owned(); PluginState::run(&app, move |service| { Ok(vec![service.inspect_download(&owner, download)?]) }) .await } #[tauri::command] pub async fn plugins_cancel( app: AppHandle, window: tauri::Window, tokens: Vec, ) -> Result<()> { let owner = window.label().to_owned(); PluginState::run(&app, move |service| { for token in tokens { if service .candidates .get(&token) .is_some_and(|c| c.owner == owner) { let candidate = service.candidates.remove(&token).unwrap(); let _ = erase(&service.directory("plugin-staging")?, &candidate.directory); } if service .plans .get(&token) .is_some_and(|p| p.owner == owner) { service.plans.remove(&token); } } Ok(()) }) .await } #[tauri::command] pub async fn plugins_install( app: AppHandle, window: tauri::Window, tokens: Vec, enabled: bool, ) -> Result> { let owner = window.label().to_owned(); let mut result = Vec::new(); for token in tokens { let name = PluginState::run(&app, { let token = token.clone(); move |service| Ok(service.candidates.get(&token) .map(|candidate| candidate.manifest.name.clone()).unwrap_or_else(|| "Plugin".into())) }).await?; let updating = PluginState::run(&app, { let (owner, token) = (owner.clone(), token.clone()); move |service| service.begin_update(&owner, &token) }).await; let error = match updating { Err(error) => Some(error), Ok(id) => { if let Some(id) = &id { changed(&app); let (wait_app, wait_id) = (app.clone(), id.clone()); // `install` checks the leases again and reports a window that did not stop the plugin. let _ = tauri::async_runtime::spawn_blocking(move || { wait_app.state::().wait_for_release(&wait_id, LEASE_WAIT) }).await; } let owner = owner.clone(); let installed = PluginState::run(&app, move |service| { let installed = service.install(&owner, &token, enabled); if let Some(id) = &id { service.removing.remove(id); if installed.is_err() { if let Some(previous) = service.candidates.get(&token).and_then(|candidate| candidate.previous.clone()) { if let Some(record) = service.catalog.plugins.get_mut(id) { record.enabled = previous.enabled; } service.persist()?; } } } installed }).await; installed.err() } }; result.push(InstallResult { name, error: error.map(String::from) }); } changed(&app); Ok(result) } #[tauri::command] pub async fn plugins_set_enabled( app: AppHandle, id: String, enabled: bool, hash: Option, ) -> Result<()> { let stop_browser = id == "runestone.browser" && !enabled; PluginState::run(&app, move |service| service.set_enabled(&id, enabled, hash.as_deref())).await?; if stop_browser { // Stopping the browser engine waits for its reply. let browser_app = app.clone(); tauri::async_runtime::spawn_blocking(move || browser_app.state::().close_all()).await?; } changed(&app); Ok(()) } #[tauri::command] pub async fn plugins_load( app: AppHandle, window: tauri::Window, id: String, hash: String, ) -> Result { let owner = window.label().to_owned(); PluginState::run(&app, move |service| service.load(&owner, &id, &hash)).await } #[tauri::command] pub async fn plugins_release( app: AppHandle, window: tauri::Window, id: String, error: Option, ) -> Result<()> { let owner = window.label().to_owned(); let result = PluginState::run(&app, move |service| { if let Some(error) = error { service.cleanup_errors.insert(id.clone(), error); } if let Some(windows) = service.leases.get_mut(&id) { windows.remove(&owner); } Ok(()) }) .await; app.state::().released.notify_all(); result } #[tauri::command] pub async fn plugins_prepare_remove( app: AppHandle, window: tauri::Window, id: String, ) -> Result { let owner = window.label().to_owned(); PluginState::run(&app, move |service| service.prepare(&owner, &id)).await } #[tauri::command] pub async fn plugins_remove(app: AppHandle, window: tauri::Window, token: String) -> Result<()> { let owner = window.label().to_owned(); let id = PluginState::run(&app, move |service| service.begin_remove(&owner, &token)).await?; changed(&app); let worker_app = app.clone(); let result = tauri::async_runtime::spawn_blocking(move || { let state = worker_app.state::(); // `finish_remove` checks the leases again and reports a window that did not stop the plugin. let _ = state.wait_for_release(&id, LEASE_WAIT); state .with(&worker_app, |service| { let result = service.finish_remove(&id); service.removing.remove(&id); result }) }) .await?; changed(&app); result } #[tauri::command] pub async fn plugins_retry_remove( app: AppHandle, id: String, ) -> Result<()> { let result = PluginState::run(&app, move |service| service.retry_removal(&id)).await; changed(&app); result } #[tauri::command] pub async fn plugins_reveal( app: AppHandle, id: Option, ) -> Result<()> { let open_directory = id.is_none(); let path = PluginState::run(&app, move |service| { let root = service.directory("plugins")?; if let Some(id) = id { if !service.catalog.plugins.contains_key(&id) { return Err("The plugin is not installed.".into()); } let path = root.join(id); safe_child(&root, &path)?; Ok(path) } else { Ok(root) } }).await?; if open_directory { app.opener() .open_path(path.to_string_lossy().into_owned(), None::<&str>) .map_err(Error::from) } else { app.opener().reveal_item_in_dir(path).map_err(Error::from) } } #[tauri::command] pub async fn plugins_data( app: AppHandle, id: String, value: Option, ) -> Result { let changed = value.is_some(); let plugin = id.clone(); let result = PluginState::run(&app, move |service| { let id = plugin; if !service.row(&id)?.enabled { return Err("The plugin is disabled.".into()); } let parent = service.directory("plugin-data")?; let dir = parent.join(&id); if !dir.exists() { fs::create_dir(&dir)?; } safe_child(&parent, &dir)?; let path = dir.join("settings.json"); if let Some(value) = value { if value.len() > 1024 * 1024 { return Err("Plugin settings exceed 1 MiB.".into()); } serde_json::from_str::(&value)?; if path.exists() { plain(&path)?; } let temp = dir.join(format!("{}.tmp", uid())); fsutil::replace_file(&path, &temp, value.as_bytes())?; } if path.exists() { String::from_utf8(bounded(&path, 1024 * 1024)?).map_err(Error::from) } else { Ok("null".into()) } }).await?; if changed { let _ = app.emit("plugin-settings-changed", &id); } Ok(result) } #[tauri::command] pub async fn plugins_asset( app: AppHandle, id: String, path: String, ) -> Result { use base64::Engine; PluginState::run(&app, move |service| { Ok(base64::engine::general_purpose::STANDARD.encode(service.asset(&id, &path)?)) }) .await } #[cfg(test)] mod tests { use super::*; use std::io::Write; struct Fixture { root: PathBuf, service: Service, source: PathBuf, } impl Fixture { fn new() -> Self { let root = std::env::temp_dir().join(format!("runestone-plugin-tests-{}", uid())); fs::create_dir(&root).unwrap(); let source = root.join("source"); fs::create_dir(&source).unwrap(); fs::write(source.join("plugin.json"), r#"{"schemaVersion":1,"id":"org.test.demo","name":"Demo","author":"Test","description":"Test plugin","version":"1.0.0","apiVersion":1,"entry":"main.js","access":"full-app"}"#).unwrap(); fs::write(source.join("main.js"), "export function activate() {}").unwrap(); let service = Service::open(root.join("app")).unwrap(); Self { root, service, source, } } fn install(&mut self, enabled: bool) -> String { let row = self.service.inspect("main", self.source.clone()); assert!(row.error.is_none(), "{:?}", row.error); self.service.install("main", &row.token, enabled).unwrap(); "org.test.demo".into() } } impl Drop for Fixture { fn drop(&mut self) { let root = dunce::canonicalize(&self.root).unwrap(); let parent = dunce::canonicalize(std::env::temp_dir()).unwrap(); assert_eq!(root.parent(), Some(parent.as_path())); assert!(root .file_name() .unwrap() .to_string_lossy() .starts_with("runestone-plugin-tests-")); let _ = fs::remove_dir_all(root); } } fn archive(path: &Path, entries: &[(&str, &[u8])]) { let mut zip = zip::ZipWriter::new(fs::File::create(path).unwrap()); for (name, data) in entries { zip.start_file(*name, zip::write::SimpleFileOptions::default()) .unwrap(); zip.write_all(data).unwrap(); } zip.finish().unwrap(); } fn review_remote(fixture: &mut Fixture, bytes: Vec) -> CandidateRow { use crate::plugin_sources::{tests::server, Repository}; let (asset_url, asset_server) = server(vec![("200 OK".into(), bytes)]); let metadata = serde_json::json!({"tag_name":"trial-1", "assets":[{ "name":"plugin.zip", "browser_download_url":format!("{asset_url}/plugin.zip") }]}); let (base, metadata_server) = server(vec![("200 OK".into(), serde_json::to_vec(&metadata).unwrap())]); let repository = Repository::parse(&format!("{base}/owner/plugin.git"), "trial-1").unwrap(); let download = crate::plugin_sources::download(&repository, Some("test-token")).unwrap(); let requests = metadata_server.join().unwrap(); assert!(requests[0].starts_with("GET /api/v1/repos/owner/plugin/releases/tags/trial-1 ")); assert!(requests[0].contains("authorization: token test-token")); assert!(!asset_server.join().unwrap()[0].contains("test-token")); fixture.service.inspect_download("main", download).unwrap() } #[test] fn remote_download_uses_review_and_package_checks() { let mut f = Fixture::new(); let archive_path = f.root.join("demo.zip"); let manifest = fs::read(f.source.join("plugin.json")).unwrap(); archive(&archive_path, &[("plugin.json", &manifest), ("main.js", b"export function activate() {}")]); let bytes = fs::read(&archive_path).unwrap(); let candidate = review_remote(&mut f, bytes.clone()); assert!(candidate.error.is_none(), "{:?}", candidate.error); assert!(candidate.source.contains("trial-1")); assert!(f.service.candidates[&candidate.token].source.is_none()); assert!(f.service.install("other-window", &candidate.token, false).is_err()); let staging = f.service.candidates[&candidate.token].directory.clone(); fs::write(staging.join("main.js"), "changed").unwrap(); assert!(f.service.install("main", &candidate.token, false).is_err()); let candidate = review_remote(&mut f, bytes); let id = candidate.manifest.as_ref().unwrap().id.clone(); f.service.install("main", &candidate.token, false).unwrap(); assert!(!f.service.row(&id).unwrap().enabled); assert!(f.service.install("main", &candidate.token, false).is_err()); let invalid = review_remote(&mut f, b"not a zip".to_vec()); assert!(invalid.error.is_some()); archive(&archive_path, &[("../outside", b"bad")]); let invalid = review_remote(&mut f, fs::read(&archive_path).unwrap()); assert!(invalid.error.is_some()); assert!(!f.root.join("outside").exists()); assert!(fs::read_dir(f.service.directory("plugin-staging").unwrap()).unwrap() .all(|entry| entry.unwrap().path().extension().is_none_or(|ext| ext != "zip"))); } #[test] #[ignore = "Set RUNESTONE_GIT_TRIAL_PACKAGES to the folder with the four trial ZIPs."] fn four_plugin_release_trial() { let directory = PathBuf::from(std::env::var("RUNESTONE_GIT_TRIAL_PACKAGES").unwrap()); let archives: Vec<_> = fs::read_dir(directory).unwrap().map(|entry| entry.unwrap().path()) .filter(|path| path.extension().is_some_and(|ext| ext == "zip")).collect(); assert_eq!(archives.len(), 4); let mut f = Fixture::new(); let mut ids = BTreeSet::new(); for path in archives { let expected = package(&path).unwrap(); let candidate = review_remote(&mut f, fs::read(&path).unwrap()); assert!(candidate.error.is_none(), "{:?}", candidate.error); let id = candidate.manifest.as_ref().unwrap().id.clone(); f.service.install("main", &candidate.token, false).unwrap(); assert_eq!(f.service.row(&id).unwrap().hash, expected.hash); assert!(!f.service.row(&id).unwrap().enabled); println!("Release download, review, and isolated install passed: {} {}", id, expected.manifest.version); ids.insert(id); } assert_eq!(ids.len(), 4); } #[test] #[ignore = "Requires an approved live Gitea release and repository read access."] fn live_gitea_release_trial() { let repository = crate::plugin_sources::Repository::parse( &std::env::var("RUNESTONE_GIT_TRIAL_URL").unwrap(), &std::env::var("RUNESTONE_GIT_TRIAL_TAG").unwrap(), ).unwrap(); let token = std::env::var("RUNESTONE_GIT_TRIAL_TOKEN").ok(); let download = crate::plugin_sources::download(&repository, token.as_deref()).unwrap(); let expected = package(&PathBuf::from(std::env::var("RUNESTONE_GIT_TRIAL_ZIP").unwrap())).unwrap(); let mut f = Fixture::new(); let candidate = f.service.inspect_download("main", download).unwrap(); assert!(candidate.error.is_none(), "{:?}", candidate.error); let id = candidate.manifest.as_ref().unwrap().id.clone(); f.service.install("main", &candidate.token, false).unwrap(); assert_eq!(f.service.row(&id).unwrap().hash, expected.hash); assert!(!f.service.row(&id).unwrap().enabled); println!("Live Gitea download, review, and isolated install passed: {} {}", id, expected.manifest.version); } #[test] fn install_time_survives_reload_and_state_changes() { let mut f = Fixture::new(); let before = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_millis() as u64; let id = f.install(false); let after = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_millis() as u64; let installed_at = f.service.row(&id).unwrap().installed_at.unwrap(); assert!((before..=after).contains(&installed_at)); let mut reopened = Service::open(f.root.join("app")).unwrap(); reopened.catalog.plugins.get_mut(&id).unwrap().enabled = true; reopened.persist().unwrap(); let mut reopened = Service::open(f.root.join("app")).unwrap(); let snapshot = serde_json::to_value(reopened.snapshot().unwrap()).unwrap(); assert_eq!(snapshot["plugins"][0]["installedAt"], installed_at); let plan = reopened.prepare("main", &id).unwrap(); assert_eq!(plan.plugin.installed_at, Some(installed_at)); reopened.begin_remove("main", &plan.token).unwrap(); reopened.finish_remove(&id).unwrap(); assert!(!reopened.catalog.plugins.contains_key(&id)); f.service = reopened; f.install(true); assert!(f.service.row(&id).unwrap().installed_at.unwrap() >= installed_at); } #[test] fn reviewed_update_keeps_settings_and_enabled_state_and_replaces_files() { for enabled in [false, true] { let mut f = Fixture::new(); let id = f.install(enabled); let settings = f.service.directory("plugin-data").unwrap().join(format!("{id}.json")); fs::write(&settings, r#"{"keep":true}"#).unwrap(); let manifest = fs::read_to_string(f.source.join("plugin.json")).unwrap().replace("1.0.0", "1.0.1"); fs::write(f.source.join("plugin.json"), manifest).unwrap(); fs::write(f.source.join("main.js"), "export function activate() { /* update */ }").unwrap(); let candidate = f.service.inspect("main", f.source.clone()); assert!(candidate.error.is_none(), "{:?}", candidate.error); assert!(f.service.begin_update("other", &candidate.token).is_err()); assert_eq!(f.service.begin_update("main", &candidate.token).unwrap(), Some(id.clone())); assert!(!f.service.row(&id).unwrap().enabled); f.service.install("main", &candidate.token, !enabled).unwrap(); f.service.removing.remove(&id); let row = f.service.row(&id).unwrap(); assert_eq!(row.manifest.version, "1.0.1"); assert_eq!(row.enabled, enabled); assert!(row.error.is_none()); assert_eq!(fs::read_to_string(&settings).unwrap(), r#"{"keep":true}"#); assert_eq!(Service::open(f.root.join("app")).unwrap().row(&id).unwrap().manifest.version, "1.0.1"); } } #[test] fn update_waits_for_cleanup_and_rejects_changed_packages() { let mut f = Fixture::new(); let id = f.install(true); let candidate = f.service.inspect("main", f.source.clone()); f.service.leases.entry(id.clone()).or_default().insert("main".into()); f.service.begin_update("main", &candidate.token).unwrap(); assert!(f.service.install("main", &candidate.token, true).unwrap_err().to_string().contains("cleanup")); f.service.leases.clear(); fs::write(f.source.join("main.js"), "changed after review").unwrap(); assert!(f.service.install("main", &candidate.token, true).unwrap_err().to_string().contains("changed after review")); assert_eq!(f.service.row(&id).unwrap().manifest.version, "1.0.0"); assert_eq!(fs::read_to_string(f.service.directory("plugins").unwrap().join(&id).join("main.js")).unwrap(), "export function activate() {}"); } #[test] fn interrupted_update_restores_previous_package_until_commit() { for phase in 0..4 { let mut f = Fixture::new(); let id = f.install(true); let previous = f.service.catalog.plugins[&id].clone(); let manifest = fs::read_to_string(f.source.join("plugin.json")).unwrap().replace("1.0.0", "1.0.1"); fs::write(f.source.join("plugin.json"), manifest).unwrap(); let row = f.service.inspect("main", f.source.clone()); f.service.begin_update("main", &row.token).unwrap(); let candidate = &f.service.candidates[&row.token]; let journal = UpdateJournal { previous, next_hash: candidate.hash.clone(), backup: uid(), staged: row.token.clone() }; let staging = f.service.directory("plugin-staging").unwrap(); fs::write(staging.join(format!("update-{}.json", uid())), serde_json::to_vec(&journal).unwrap()).unwrap(); let target = f.service.directory("plugins").unwrap().join(&id); if phase >= 1 { fs::rename(&target, staging.join(&journal.backup)).unwrap(); } if phase >= 2 { fs::rename(&candidate.directory, &target).unwrap(); } if phase == 3 { let record = f.service.catalog.plugins.get_mut(&id).unwrap(); record.manifest = candidate.manifest.clone(); record.hash = candidate.hash.clone(); record.enabled = true; f.service.persist().unwrap(); } let mut recovered = Service::open(f.root.join("app")).unwrap(); let row = recovered.row(&id).unwrap(); assert!(row.error.is_none()); assert_eq!(row.manifest.version, if phase == 3 { "1.0.1" } else { "1.0.0" }); assert_eq!(row.enabled, phase == 3); assert!(!staging.join(&journal.backup).exists()); } } #[test] fn legacy_and_discovered_plugins_keep_unknown_install_times() { let mut f = Fixture::new(); let id = f.install(false); let path = f.root.join("app/plugin-state.json"); let mut catalog = serde_json::to_value(&f.service.catalog).unwrap(); catalog["plugins"][&id] .as_object_mut() .unwrap() .remove("installedAt"); fs::write(&path, serde_json::to_vec(&catalog).unwrap()).unwrap(); let mut reopened = Service::open(f.root.join("app")).unwrap(); assert_eq!(reopened.snapshot().unwrap().plugins[0].installed_at, None); reopened.catalog.plugins.clear(); reopened.persist().unwrap(); assert_eq!(reopened.snapshot().unwrap().plugins[0].installed_at, None); let mut reopened = Service::open(f.root.join("app")).unwrap(); assert_eq!(reopened.snapshot().unwrap().plugins[0].installed_at, None); } #[test] fn installer_accepts_only_zip_files() { let f = Fixture::new(); assert!(require_zip(&f.source).is_err()); assert!(require_zip(&f.source.join("plugin.json")).is_err()); let legacy = f.root.join("demo.runestone-plugin"); archive(&legacy, &[("main.js", b"test")]); assert!(require_zip(&legacy).is_err()); assert!(package(&legacy).is_err()); let upper = f.root.join("demo.ZIP"); fs::copy(&legacy, &upper).unwrap(); assert!(require_zip(&upper).is_ok()); let wrapped = f.root.join("wrapped.zip"); archive(&wrapped, &[("demo/plugin.json", b"{}")]); assert!(package(&wrapped).unwrap_err().to_string().contains("at its root")); } #[test] fn author_packager_produces_an_installable_repeatable_zip() { let mut f = Fixture::new(); let manifest = fs::read_to_string(f.source.join("plugin.json")) .unwrap().replace("1.0.0", "1.0.0a"); fs::write(f.source.join("plugin.json"), manifest).unwrap(); fs::create_dir(f.source.join("assets")).unwrap(); fs::write(f.source.join("assets/style.css"), "body { color: red; }").unwrap(); let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../scripts/packagePlugin.mjs"); let output = f.root.join("releases"); let build = || { let result = std::process::Command::new("node") .arg(&script) .arg(&f.source) .arg(&output) .output() .unwrap(); assert!( result.status.success(), "{}", String::from_utf8_lossy(&result.stderr) ); }; build(); let path = output.join("org.test.demo-1.0.0a.zip"); let first = fs::read(&path).unwrap(); build(); assert_eq!(first, fs::read(&path).unwrap()); assert_eq!( package(&path).unwrap().hash, package(&f.source).unwrap().hash ); let row = f.service.inspect("main", path); assert!(row.error.is_none(), "{:?}", row.error); f.service.install("main", &row.token, false).unwrap(); let installed = f.service.row("org.test.demo").unwrap(); assert_eq!(installed.manifest.version, "1.0.0a"); assert!(!installed.enabled); assert_eq!( fs::read(Path::new(&installed.path).join("assets/style.css")).unwrap(), b"body { color: red; }" ); } #[test] fn installs_directory_and_zip_without_changing_source() { let mut f = Fixture::new(); let original = package(&f.source).unwrap(); let archive_path = f.root.join("demo.zip"); let entries: Vec<_> = original .files .iter() .map(|(name, bytes)| (name.as_str(), bytes.as_slice())) .collect(); archive(&archive_path, &entries); assert_eq!(package(&archive_path).unwrap().hash, original.hash); let row = f.service.inspect("main", archive_path); assert!(row.error.is_none()); f.service.install("main", &row.token, false).unwrap(); assert!(!f.service.row("org.test.demo").unwrap().enabled); assert_eq!(package(&f.source).unwrap().hash, original.hash); assert!(f.service.inspect("main", f.source.clone()).error.is_none()); } #[test] fn feature_packages_use_the_standard_install_and_remove_lifecycle() { for id in ["runestone.terminal", "runestone.table-formulas"] { let mut f = Fixture::new(); let manifest = fs::read_to_string(f.source.join("plugin.json")) .unwrap() .replace("org.test.demo", id); fs::write(f.source.join("plugin.json"), manifest).unwrap(); let reviewed = f.service.inspect("main", f.source.clone()); assert!(reviewed.error.is_none()); f.service.install("main", &reviewed.token, true).unwrap(); assert!(f.service.row(id).unwrap().enabled); let mut reopened = Service::open(f.root.join("app")).unwrap(); assert_eq!(reopened.snapshot().unwrap().plugins.len(), 1); let plan = reopened.prepare("main", id).unwrap(); reopened.begin_remove("main", &plan.token).unwrap(); reopened.finish_remove(id).unwrap(); assert!(reopened.snapshot().unwrap().plugins.is_empty()); assert!(f.source.join("plugin.json").exists()); } } #[test] fn old_bundled_preferences_do_not_restore_or_enable_packages() { let mut f = Fixture::new(); fs::write(f.root.join("app/plugin-state.json"), r#"{"plugins":{},"bundled":{"runestone.terminal":true,"runestone.table-formulas":true}}"#).unwrap(); f.service = Service::open(f.root.join("app")).unwrap(); let snapshot = f.service.snapshot().unwrap(); assert!(snapshot.plugins.is_empty()); assert!(serde_json::to_value(snapshot) .unwrap() .get("bundled") .is_none()); } #[test] fn hotfix_versions_validate_and_survive_zip_install() { for version in ["0.2.28", "0.2.28a", "0.2.28b", "0.2.28aa", "1.0.1000z"] { assert!(valid_version(version), "{version}"); } for version in ["", "1.0", "1.0.0.0", "1.0.a", "1.0.0A", "1.0.0a1", "1.0.0-beta", "1.0.0+build", "1.0.0é"] { assert!(!valid_version(version), "{version}"); } let mut f = Fixture::new(); let manifest = fs::read_to_string(f.source.join("plugin.json")) .unwrap().replace("1.0.0", "0.2.28a"); let path = f.root.join("hotfix.zip"); archive(&path, &[("plugin.json", manifest.as_bytes()), ("main.js", b"export function activate() {}")]); assert_eq!(package(&path).unwrap().manifest.version, "0.2.28a"); let row = f.service.inspect("main", path); assert!(row.error.is_none()); f.service.install("main", &row.token, true).unwrap(); let mut reopened = Service::open(f.root.join("app")).unwrap(); let snapshot = reopened.snapshot().unwrap(); assert_eq!(snapshot.plugins[0].manifest.version, "0.2.28a"); assert!(snapshot.plugins[0].enabled); } #[test] fn validates_paths_ids_limits_and_versions() { for name in [ "../file", "/file", "C:/file", "a\\b", "a/../b", "CON", "x/NUL.txt", "a.", "a:stream", "a//b", ] { assert!(relative(name).is_err(), "{name}"); } for id in ["", "../x", "CON", "X.test", "a."] { assert!(!valid_id(id), "{id}"); } let f = Fixture::new(); let path = f.root.join("bad.zip"); archive(&path, &[("../outside", b"test")]); assert!(package(&path).is_err()); assert!(!f.root.join("outside").exists()); archive(&path, &[("main.js", b"a"), ("MAIN.js", b"b")]); assert!(package(&path).unwrap_err().to_string().contains("duplicate")); let manifest = fs::read_to_string(f.source.join("plugin.json")) .unwrap() .replace("\"apiVersion\":1", "\"apiVersion\":99"); fs::write(f.source.join("plugin.json"), manifest).unwrap(); assert!(package(&f.source).is_err()); let huge = fs::File::create(f.source.join("big.bin")).unwrap(); huge.set_len(MAX_FILE + 1).unwrap(); assert!(package(&f.source).is_err()); } #[test] fn source_changes_expired_reviews_and_other_windows_cannot_install() { let mut f = Fixture::new(); let row = f.service.inspect("main", f.source.clone()); assert!(f.service.install("other", &row.token, true).is_err()); fs::write(f.source.join("main.js"), "changed").unwrap(); assert!(f.service.install("main", &row.token, true).is_err()); assert!(!f .service .directory("plugins") .unwrap() .join("org.test.demo") .exists()); let row = f.service.inspect("main", f.source.clone()); f.service.candidates.get_mut(&row.token).unwrap().created = Instant::now() - Duration::from_secs(1900); assert!(f.service.install("main", &row.token, false).is_err()); } #[test] fn confirmation_uses_a_valid_plan_and_cancel_does_not_disable() { let mut f = Fixture::new(); let id = f.install(true); assert!(f.service.begin_remove("main", "missing-plan").is_err()); let plan = f.service.prepare("main", &id).unwrap(); assert!(f.service.row(&id).unwrap().enabled); f.service.plans.remove(&plan.token); assert!(f.service.begin_remove("main", &plan.token).is_err()); assert!(f.service.row(&id).unwrap().enabled); let plan = f.service.prepare("main", &id).unwrap(); assert!(f.service.begin_remove("other", &plan.token).is_err()); assert!(f.service.row(&id).unwrap().enabled); let plan = f.service.prepare("main", &id).unwrap(); f.service.plans.get_mut(&plan.token).unwrap().created = Instant::now() - Duration::from_secs(301); assert!(f.service.begin_remove("main", &plan.token).is_err()); assert!(f.service.row(&id).unwrap().enabled); let plan = f.service.prepare("main", &id).unwrap(); f.service.begin_remove("main", &plan.token).unwrap(); assert!(f.service.begin_remove("main", &plan.token).is_err()); f.service.finish_remove(&id).unwrap(); assert!(!f.service.directory("plugins").unwrap().join(id).exists()); } #[test] fn changed_target_requires_new_confirmation() { let mut f = Fixture::new(); let id = f.install(true); let plan = f.service.prepare("main", &id).unwrap(); let path = f.service.directory("plugins").unwrap().join(&id); fs::write(path.join("main.js"), "changed").unwrap(); assert!(f.service.begin_remove("main", &plan.token).is_err()); assert!(path.exists()); let plan = f.service.prepare("main", &id).unwrap(); f.service.begin_remove("main", &plan.token).unwrap(); fs::write(path.join("main.js"), "changed again").unwrap(); assert!(f.service.finish_remove(&id).is_err()); assert!(path.exists()); } #[test] fn lease_errors_name_the_plugin_that_is_not_enabled() { let mut f = Fixture::new(); let id = f.install(true); let error = f.service.require_lease("main", &id).unwrap_err().to_string(); assert_eq!(error, "The Demo plugin is not enabled in this window."); assert!(!error.contains("browser")); assert_eq!( f.service.require_lease("main", "runestone.backgrounds").unwrap_err().to_string(), "This plugin is not enabled in this window." ); f.service.leases.entry(id.clone()).or_default().insert("main".into()); f.service.require_lease("main", &id).unwrap(); assert!(f.service.require_lease("other", &id).is_err()); f.service.catalog.plugins.get_mut(&id).unwrap().enabled = false; assert!(f.service.require_lease("main", &id).is_err()); } #[test] fn closing_a_window_releases_its_leases_and_erases_its_reviews() { let mut f = Fixture::new(); let id = f.install(true); f.service.leases.entry(id.clone()).or_default().extend(["main".to_owned(), "other".to_owned()]); let mine = f.service.inspect("main", f.source.clone()); let theirs = f.service.inspect("other", f.source.clone()); let folder = f.service.candidates[&mine.token].directory.clone(); let kept = f.service.candidates[&theirs.token].directory.clone(); assert!(folder.is_dir()); let (root, folders) = f.service.release_window("main"); // The plugin lock is open again before the files are erased. assert!(folder.is_dir()); StagingCleanup(Some((root, folders))).erase(); assert!(!folder.exists()); assert!(kept.is_dir()); assert!(!f.service.candidates.contains_key(&mine.token)); assert!(f.service.candidates.contains_key(&theirs.token)); assert_eq!(f.service.leases[&id], BTreeSet::from(["other".to_owned()])); let state = PluginState::default(); assert!(state.try_release_window("main").is_some()); let _guard = state.inner.lock().unwrap(); assert!(state.try_release_window("main").is_none(), "A busy plugin lock must not stop the caller."); } #[test] fn removal_waits_for_every_window_and_preserves_user_data() { let mut f = Fixture::new(); let id = f.install(true); let data = f.service.directory("plugin-data").unwrap().join(&id); fs::create_dir(&data).unwrap(); fs::write(data.join("settings.json"), "retained").unwrap(); let document = f.root.join("note.md"); fs::write(&document, "retained note").unwrap(); let plan = f.service.prepare("main", &id).unwrap(); f.service.begin_remove("main", &plan.token).unwrap(); f.service .leases .insert(id.clone(), BTreeSet::from(["main".into(), "other".into()])); assert!(f.service.finish_remove(&id).is_err()); f.service.leases.get_mut(&id).unwrap().remove("main"); assert!(f.service.finish_remove(&id).is_err()); f.service.leases.remove(&id); f.service.cleanup_errors.insert(id.clone(), "Failed".into()); assert!(f.service.finish_remove(&id).is_err()); f.service.cleanup_errors.clear(); f.service.finish_remove(&id).unwrap(); assert_eq!( fs::read_to_string(data.join("settings.json")).unwrap(), "retained" ); assert_eq!(fs::read_to_string(document).unwrap(), "retained note"); assert!(f.source.join("main.js").exists()); } #[test] fn crash_before_move_preserves_package_and_resets_removal() { let mut f = Fixture::new(); let id = f.install(true); let record = f.service.catalog.plugins.get_mut(&id).unwrap(); record.enabled = false; record.removal = Some(uid()); f.service.persist().unwrap(); let mut recovered = Service::open(f.service.root.clone()).unwrap(); assert!(recovered.catalog.plugins[&id].removal.is_none()); assert!(!recovered.row(&id).unwrap().enabled); } #[test] fn partial_removal_recovery_checks_remaining_files() { let mut f = Fixture::new(); let id = f.install(false); let source = f.service.directory("plugins").unwrap().join(&id); let files = directory_files(&source).unwrap(); let token = uid(); let record = f.service.catalog.plugins.get_mut(&id).unwrap(); record.removal = Some(token.clone()); record.removal_files = files .iter() .map(|(name, bytes)| (name.clone(), format!("{:x}", Sha256::digest(bytes)))) .collect(); f.service.persist().unwrap(); let target = f.service.directory("plugin-removals").unwrap().join(token); fs::rename(source, &target).unwrap(); fs::remove_file(target.join("main.js")).unwrap(); fs::write(target.join("unexpected.txt"), "keep").unwrap(); let mut recovered = Service::open(f.service.root.clone()).unwrap(); assert!(recovered.retry_removal(&id).is_err()); assert!(target.join("unexpected.txt").exists()); fs::remove_file(target.join("unexpected.txt")).unwrap(); recovered.retry_removal(&id).unwrap(); assert!(!target.exists()); assert!(f.service.directory("plugin-data").unwrap().exists()); } #[test] fn malformed_catalog_cannot_create_a_deletion_target() { let f = Fixture::new(); fs::write(f.service.root.join("plugin-state.json"), "{broken").unwrap(); assert!(Service::open(f.service.root.clone()).is_err()); assert!(safe_child(&f.service.directory("plugins").unwrap(), &f.source).is_err()); } #[test] fn package_checks_are_cached_until_file_metadata_changes() { let mut f = Fixture::new(); let id = f.install(true); let folder = f.service.directory("plugins").unwrap().join(&id); let first = f.service.check(&folder).unwrap(); f.service.snapshot().unwrap(); assert!(Arc::ptr_eq(&first, &f.service.check(&folder).unwrap()), "A scan without file changes reuses the hash."); fs::create_dir(folder.join("empty")).unwrap(); assert!(!Arc::ptr_eq(&first, &f.service.check(&folder).unwrap()), "A new entry starts a new read."); fs::write(folder.join("main.js"), "export function activate() { /* edited */ }").unwrap(); let row = f.service.row(&id).unwrap(); assert_eq!(row.error.as_deref(), Some("Plugin files changed. Review them before enabling this plugin.")); assert!(!row.enabled); } #[test] fn changed_packages_stop_and_need_a_new_enable_decision() { let mut f = Fixture::new(); let id = f.install(true); let reviewed = f.service.row(&id).unwrap().hash; let entry = f.service.directory("plugins").unwrap().join(&id).join("main.js"); assert_eq!(f.service.load("main", &id, &reviewed).unwrap(), "export function activate() {}"); assert_eq!(f.service.asset(&id, "main.js").unwrap(), b"export function activate() {}"); assert!(f.service.asset(&id, "missing.js").unwrap_err().to_string().contains("missing")); f.service.leases.clear(); // The same size and modification time hide the edit from the cache, but not from a file read. let modified = fs::metadata(&entry).unwrap().modified().unwrap(); fs::write(&entry, "export function activatE() {}").unwrap(); fs::File::options().write(true).open(&entry).unwrap().set_modified(modified).unwrap(); assert!(f.service.row(&id).unwrap().enabled); assert!(f.service.asset(&id, "main.js").unwrap_err().to_string().contains("changed")); assert!(f.service.load("main", &id, &reviewed).is_err()); assert!(!f.service.leased(&id)); let row = f.service.row(&id).unwrap(); assert!(row.error.is_some() && !row.enabled); // A scan stops the plugin in every window: the snapshot reports it as disabled and saves that state. let snapshot = f.service.snapshot().unwrap(); assert!(!snapshot.plugins[0].enabled); assert!(!Service::open(f.root.join("app")).unwrap().catalog.plugins[&id].enabled); // Enable needs the hash that the user saw for the current files. assert!(f.service.set_enabled(&id, true, Some(&reviewed)).is_err()); assert!(f.service.set_enabled(&id, true, None).is_err()); f.service.set_enabled(&id, true, Some(&row.hash)).unwrap(); assert!(f.service.row(&id).unwrap().enabled); assert_eq!(f.service.load("main", &id, &row.hash).unwrap(), "export function activatE() {}"); } #[test] fn lease_wait_ends_when_the_last_window_releases_its_lease() { let mut f = Fixture::new(); let id = f.install(true); f.service.leases.entry(id.clone()).or_default().extend(["main".to_owned(), "other".to_owned()]); let reopened = Service::open(f.root.join("app")).unwrap(); let state = Arc::new(PluginState::default()); *state.inner.lock().unwrap() = Some(std::mem::replace(&mut f.service, reopened)); let start = Instant::now(); assert!(!state.wait_for_release(&id, Duration::from_millis(100)).unwrap()); assert!(start.elapsed() >= Duration::from_millis(100)); let waiter = { let (state, id) = (state.clone(), id.clone()); std::thread::spawn(move || { let start = Instant::now(); (state.wait_for_release(&id, LEASE_WAIT).unwrap(), start.elapsed()) }) }; std::thread::sleep(Duration::from_millis(50)); state.close_window("main"); std::thread::sleep(Duration::from_millis(50)); assert!(!waiter.is_finished(), "One window still holds a lease."); state.close_window("other"); let (released, elapsed) = waiter.join().unwrap(); assert!(released); assert!(elapsed < Duration::from_secs(5), "The wait ends without the full time limit."); assert!(state.wait_for_release("org.test.missing", LEASE_WAIT).unwrap()); } }