diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 59ea6048d0..09c0b63204 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -21,8 +21,9 @@ //! Plug-ins Folder preference is not copied: it is loaded from where it is. `grants.json` holds what the user granted the plug-ins //! stored there that list permissions (id, module hash, permissions); a stored plug-in whose //! permissions it doesn't grant is skipped with a log record, and stays in the folder. The file -//! carries a MAC of its grants and its folder, made with a key the user's key store keeps -//! ([`grant_keys`]); a file without that MAC grants nothing. +//! carries a generation and a MAC of its generation, grants and folder, made with a key the user's +//! key store keeps ([`grant_keys`]); a file without that MAC, or at another generation than the +//! one the key store keeps for the folder, grants nothing. //! * **Plug-in settings and caches**: `storage/id-/` in the plug-in store, the id written as //! [`case_safe`] writes it, holds what a plug-in //! keeps with the `settings` and `cache` permissions ([`PluginStorage`]): `settings.json` and a @@ -725,11 +726,13 @@ impl Session { /// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's /// other grants as they are; with none left, remove the file. Entries this version can't use - /// are written back as they were, except one for `id`. The file is written with the MAC of its - /// grants for this folder ([`grant_keys`]), making the key when the key store holds none. A file + /// are written back as they were, except one for `id`. The file is written at the folder's next + /// generation with the MAC of its grants for this folder ([`grant_keys`]), making the key when + /// the key store holds none, and the key store then keeps that generation ([`put_grants`]); a + /// signed file left empty is removed after raising the generation ([`take_signed_grants`]). A file /// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant - /// replaces it with a file that holds that grant alone, and removing one takes out the entry for - /// `id` and leaves the rest unsigned. When the key store can't be reached ([`Trust::Unknown`], or + /// replaces it with a file that holds that grant alone, and removing one raises the generation + /// ([`raise_generation`]), then takes out the entry for `id` and leaves the rest unsigned. When the key store can't be reached ([`Trust::Unknown`], or /// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry /// for `id` stays. A grants file that is too large, can't /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; @@ -824,10 +827,15 @@ impl Session { } let mut entries: Vec = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect(); entries.extend(file.other); - if entries.is_empty() { - return take(dir, GRANTS_FILE); + if signed { + return if entries.is_empty() { take_signed_grants(dir) } else { put_grants(dir, entries, true) }; } - put_grants(dir, entries, signed) + // An unsigned file loses an entry: the generation is raised first, so that no signed copy + // made before brings the entry back. + if raise_generation(dir).is_none() { + return false; + } + if entries.is_empty() { take(dir, GRANTS_FILE) } else { put_grants(dir, entries, false) } } /// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this @@ -1501,11 +1509,14 @@ impl GrantsFile { /// Whether a grants file was written by VectorCraft for its folder ([`grant_keys`]). #[derive(Default, Clone, Copy, PartialEq, Eq, Debug)] enum Trust { - /// There is no file, or it carries the MAC of its grants and folder made with the user's key. + /// There is no file, or it is at the generation kept for its folder and carries the MAC of that + /// generation, its grants and its folder made with the user's key. #[default] Signed, /// It doesn't: an older version wrote it, another program wrote or changed it, it was copied - /// from another folder or machine, or the key store holds no key. It grants nothing. + /// from another folder or machine, it is an earlier copy or a write whose generation wasn't kept + /// (its generation is not the one the key store keeps), or the key store holds no key. It grants + /// nothing. Unsigned, /// The key store can't be reached, so it is not known which. It grants nothing, and is left as /// it is. @@ -1515,25 +1526,31 @@ enum Trust { /// The version of the grants file this version writes ([`SignedGrants::version`]). const GRANTS_VERSION: u64 = 1; -/// The grants file as this version writes it: the grants, and their MAC ([`grant_keys::sign`]) over -/// the list written as compact JSON. +/// The grants file as this version writes it: its generation ([`grant_keys::current_generation`]), +/// the grants, and their MAC ([`grant_keys::sign`]) over the generation and the list written as +/// compact JSON. #[derive(serde::Serialize, serde::Deserialize)] struct SignedGrants { version: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + generation: Option, grants: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] mac: Option, } /// Tests: a grants file for the plug-in store `dir` that holds `grants` (a JSON list, written as it -/// is) with their MAC made with the key in use, as VectorCraft writes one. +/// is) at the generation kept for `dir`, with their MAC made with the key in use, as VectorCraft +/// writes one. #[cfg(test)] pub(crate) fn signed_grants_file(dir: &Path, grants: &str) -> Vec { let entries: Vec = serde_json::from_str(grants).unwrap_or_default(); let key = grant_keys::signing_key().unwrap_or_else(|e| panic!("no key: {e}")); + let folder = plugin_store_key(dir); + let generation = grant_keys::current_generation(&folder).unwrap_or_else(|e| panic!("no generation: {e}")); let canonical = serde_json::to_vec(&entries).unwrap_or_default(); - let mac = grant_keys::sign(&key, &plugin_store_key(dir), &canonical).unwrap_or_default(); - format!(r#"{{"version":{GRANTS_VERSION},"grants":{grants},"mac":"{mac}"}}"#).into_bytes() + let mac = grant_keys::sign(&key, &folder, generation, &canonical).unwrap_or_default(); + format!(r#"{{"version":{GRANTS_VERSION},"generation":{generation},"grants":{grants},"mac":"{mac}"}}"#).into_bytes() } /// Tests: the entries of the grants file `bytes`, signed or not. @@ -1549,13 +1566,17 @@ pub(crate) fn grant_entries(bytes: &[u8]) -> Vec { } } -/// Whether `signed`, read from the grants file of the plug-in store `dir`, carries the MAC of its -/// grants and of `dir` made with the user's key. +/// Whether `signed`, read from the grants file of the plug-in store `dir`, is at the generation kept +/// for `dir` and carries the MAC of that generation, its grants and `dir` made with the user's key. +/// A file at another generation, one behind or one ahead of the kept one included, is +/// [`Trust::Unsigned`]. fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust { - let (Some(tag), true) = (&signed.mac, signed.version == GRANTS_VERSION) else { return Trust::Unsigned }; + let (Some(tag), Some(generation), true) = (&signed.mac, signed.generation, signed.version == GRANTS_VERSION) else { return Trust::Unsigned }; let Ok(grants) = serde_json::to_vec(&signed.grants) else { return Trust::Unsigned }; - match grant_keys::current_key() { - Ok(Some(key)) if grant_keys::verify(&key, &plugin_store_key(dir), &grants, tag) => Trust::Signed, + let folder = plugin_store_key(dir); + let kept = grant_keys::current_key().and_then(|key| key.map(|key| Ok((key, grant_keys::current_generation(&folder)?))).transpose()); + match kept { + Ok(Some((key, kept))) if generation == kept && grant_keys::verify(&key, &folder, generation, &grants, tag) => Trust::Signed, Ok(_) => Trust::Unsigned, Err(e) => { log::warn!("can't check the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); @@ -1564,30 +1585,36 @@ fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust { } } -/// Write `entries` as the grants file of the plug-in store `dir`, with their MAC for `dir` when -/// `signed`, pretty-printed, or compact when that is larger than [`MAX_GRANTS_FILE`] → whether it went -/// there; the file is not written when the key can't be had or it is too large either way. +/// Write `entries` as the grants file of the plug-in store `dir`, pretty-printed, or compact when +/// that is larger than [`MAX_GRANTS_FILE`] → whether it went there; the file is not written when the +/// key or the generation can't be had or it is too large either way. When `signed`, the file is at +/// the next generation for `dir` with its MAC, and that generation is kept after the file is written; +/// when it can't be kept, the file is at a generation the key store doesn't hold, so it grants +/// nothing, and the write reports a failure. Call it in the store's turn ([`StoreTurn`]). fn put_grants(dir: &Path, entries: Vec, signed: bool) -> bool { let path = dir.join(GRANTS_FILE); - let file = if signed { - let key = match grant_keys::signing_key() { - Ok(key) => key, + let folder = plugin_store_key(dir); + let (file, next) = if signed { + let signing = grant_keys::signing_key().and_then(|key| Ok((key, grant_keys::current_generation(&folder)?))); + let (key, generation) = match signing { + Ok(signing) => signing, Err(e) => { log::warn!("not updating the stored plug-in grants {}: {e}", path.display()); return false; } }; - let mac = serde_json::to_vec(&entries).ok().and_then(|grants| grant_keys::sign(&key, &plugin_store_key(dir), &grants)); + let Some(next) = generation.checked_add(1) else { return false }; + let mac = serde_json::to_vec(&entries).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants)); let Some(mac) = mac else { return false }; - serde_json::to_value(SignedGrants { version: GRANTS_VERSION, grants: entries, mac: Some(mac) }) + (serde_json::to_value(SignedGrants { version: GRANTS_VERSION, generation: Some(next), grants: entries, mac: Some(mac) }), Some(next)) } else { - serde_json::to_value(entries) + (serde_json::to_value(entries), None) }; // The file is read back only up to its cap: written compactly when pretty-printed is larger, // and not at all when that is too. let fits = |bytes: &Vec| bytes.len() as u64 <= MAX_GRANTS_FILE; match file.ok().and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits))) { - Some(bytes) => put(dir, GRANTS_FILE, &bytes), + Some(bytes) => put(dir, GRANTS_FILE, &bytes) && next.is_none_or(|next| keep_generation(dir, &folder, next)), None => { log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); false @@ -1595,6 +1622,50 @@ fn put_grants(dir: &Path, entries: Vec, signed: bool) -> bool } } +/// Keep `generation` for the grants file of the plug-in store `dir` (whose folder is `folder`) → +/// whether the key store kept it; a failure is logged. +fn keep_generation(dir: &Path, folder: &Path, generation: u64) -> bool { + match grant_keys::set_current_generation(folder, generation) { + Ok(()) => true, + Err(e) => { + log::warn!("the stored plug-in grants {} grant nothing: their generation wasn't kept ({e})", dir.join(GRANTS_FILE).display()); + false + } + } +} + +/// Remove the signed grants file of the plug-in store `dir` → whether it is gone. Its generation is +/// raised first, so that no copy of the file grants anything once it is gone; when the file can't be +/// removed, the generation is put back, so the file keeps its grants, and when that can't be put back +/// either, the file grants nothing. The file holds no grant but the one being removed. Nothing is +/// removed when the generation can't be raised. Call it in the store's turn ([`StoreTurn`]). +fn take_signed_grants(dir: &Path) -> bool { + let Some(generation) = raise_generation(dir) else { return false }; + if take(dir, GRANTS_FILE) { + return true; + } + keep_generation(dir, &plugin_store_key(dir), generation); + false +} + +/// Keep the next generation for the grants file of the plug-in store `dir`, so that no signed copy +/// of the file made before grants anything → the generation kept before; `None`, with a log record, +/// when the key store can't read or keep it. +fn raise_generation(dir: &Path) -> Option { + let folder = plugin_store_key(dir); + let raised = grant_keys::current_generation(&folder).and_then(|generation| { + let next = generation.checked_add(1).ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?; + grant_keys::set_current_generation(&folder, next).map(|()| generation) + }); + match raised { + Ok(generation) => Some(generation), + Err(e) => { + log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + None + } + } +} + /// Why the grants file of a plug-in store gave no grants. struct GrantsError { /// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is diff --git a/crates/engine/src/store/grant_keys.rs b/crates/engine/src/store/grant_keys.rs index a77cce19a7..2ae59dc825 100644 --- a/crates/engine/src/store/grant_keys.rs +++ b/crates/engine/src/store/grant_keys.rs @@ -5,11 +5,17 @@ //! an older version wrote, one another program wrote or changed, one copied from another folder or //! machine) grants nothing. //! +//! The key store also keeps a generation for each plug-in folder, raised on every signed write of +//! its grants file, and the file carries its generation inside the MAC. A file whose generation is +//! not the one kept (an earlier copy put back over the current file, or a write whose generation +//! the key store didn't keep) grants nothing either. +//! //! The process uses one key store ([`set_grant_key_store`]); the apps use the system's //! ([`use_os_grant_keys`]). In a process that sets none, every grants file counts as one whose key //! store can't be reached: a grant holds for the session only. -use std::path::Path; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; use std::sync::{Arc, LazyLock, Mutex}; /// The length of a key, in bytes, and of the MAC. @@ -66,18 +72,25 @@ pub trait GrantKeyStore: Send + Sync { self.set_key(&GrantKey::random()?)?; self.key()?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) } + /// The generation kept for the grants file of the plug-in store whose folder is `folder` + /// ([`super::plugin_store_key`]), read from the store each time; `None` when none is kept. + fn generation(&self, folder: &Path) -> Result, KeyStoreError>; + /// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError>; } -/// A key store in memory: the key lasts as long as the store. For tests and embedders. +/// A key store in memory: the key and the generations last as long as the store. For tests and +/// embedders. #[derive(Default)] pub struct MemoryGrantKeys { key: Mutex>, + generations: Mutex>, } impl MemoryGrantKeys { /// A store that holds `key`. pub fn with_key(key: GrantKey) -> Self { - MemoryGrantKeys { key: Mutex::new(Some(key)) } + MemoryGrantKeys { key: Mutex::new(Some(key)), ..MemoryGrantKeys::default() } } } @@ -90,6 +103,15 @@ impl GrantKeyStore for MemoryGrantKeys { *self.key.lock().unwrap_or_else(|e| e.into_inner()) = Some(key.clone()); Ok(()) } + + fn generation(&self, folder: &Path) -> Result, KeyStoreError> { + Ok(self.generations.lock().unwrap_or_else(|e| e.into_inner()).get(folder).copied()) + } + + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + self.generations.lock().unwrap_or_else(|e| e.into_inner()).insert(folder.to_path_buf(), generation); + Ok(()) + } } /// The key store of the process ([`set_grant_key_store`]). @@ -154,49 +176,64 @@ pub(crate) fn signing_key() -> Result { } } +/// The generation kept for the grants file of the plug-in store whose folder is `folder`: 0 when +/// none is kept yet, an error when there is no key store or it can't be reached. +pub(crate) fn current_generation(folder: &Path) -> Result { + Ok(current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.generation(folder)?.unwrap_or(0)) +} + +/// Keep `generation` for the grants file of the plug-in store whose folder is `folder`. +pub(crate) fn set_current_generation(folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.set_generation(folder, generation) +} + /// The start of every MAC input: what it is a MAC of, and the version of the file. #[cfg(not(target_arch = "wasm32"))] const DOMAIN: &[u8] = b"VectorCraft plug-in grants v1\0"; -/// The MAC of `grants` (the grants list as compact JSON) in the plug-in store whose folder is -/// `folder` ([`super::plugin_store_key`]), made with `key`. +/// The MAC of `grants` (the grants list as compact JSON) at `generation` in the plug-in store whose +/// folder is `folder` ([`super::plugin_store_key`]), made with `key`. The folder and the generation +/// go in with their lengths first. #[cfg(not(target_arch = "wasm32"))] -fn mac_of(key: &GrantKey, folder: &Path, grants: &[u8]) -> Option> { +fn mac_of(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option> { use hmac::Mac; let mut mac = hmac::Hmac::::new_from_slice(&key.0).ok()?; let folder = folder.as_os_str().as_encoded_bytes(); + let generation = generation.to_be_bytes(); mac.update(DOMAIN); mac.update(&(folder.len() as u64).to_be_bytes()); mac.update(folder); + mac.update(&(generation.len() as u64).to_be_bytes()); + mac.update(&generation); mac.update(grants); Some(mac) } -/// The MAC of `grants` in `folder` with `key`, as 64 lower-case hexadecimal digits. +/// The MAC of `grants` at `generation` in `folder` with `key`, as 64 lower-case hexadecimal digits. #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn sign(key: &GrantKey, folder: &Path, grants: &[u8]) -> Option { +pub(crate) fn sign(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8]) -> Option { use hmac::Mac; - Some(mac_of(key, folder, grants)?.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()) + Some(mac_of(key, folder, generation, grants)?.finalize().into_bytes().iter().map(|b| format!("{b:02x}")).collect()) } -/// Whether `tag` is the whole MAC of `grants` in `folder` with `key` ([`sign`]), compared in constant -/// time; a shorter or longer tag is not. +/// Whether `tag` is the whole MAC of `grants` at `generation` in `folder` with `key` ([`sign`]), +/// compared in constant time; a shorter or longer tag is not. #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn verify(key: &GrantKey, folder: &Path, grants: &[u8], tag: &str) -> bool { +pub(crate) fn verify(key: &GrantKey, folder: &Path, generation: u64, grants: &[u8], tag: &str) -> bool { use hmac::Mac; let Some(tag) = from_hex(tag) else { return false }; - mac_of(key, folder, grants).is_some_and(|mac| mac.verify_slice(&tag).is_ok()) + mac_of(key, folder, generation, grants).is_some_and(|mac| mac.verify_slice(&tag).is_ok()) } /// The browser keeps no grants file. #[cfg(target_arch = "wasm32")] -pub(crate) fn sign(_: &GrantKey, _: &Path, _: &[u8]) -> Option { +pub(crate) fn sign(_: &GrantKey, _: &Path, _: u64, _: &[u8]) -> Option { None } /// The browser keeps no grants file. #[cfg(target_arch = "wasm32")] -pub(crate) fn verify(_: &GrantKey, _: &Path, _: &[u8], _: &str) -> bool { +pub(crate) fn verify(_: &GrantKey, _: &Path, _: u64, _: &[u8], _: &str) -> bool { false } @@ -242,6 +279,15 @@ impl OsGrantKeys { Err(e) => Err(store_error(e)), } } + + /// The entry of the generation of the plug-in store whose folder is `folder`: the account + /// `generation-v1-` followed by the SHA-256 of the folder in hexadecimal digits. + fn generation_entry(folder: &Path) -> Result { + use sha2::Digest; + let digest = sha2::Sha256::digest(folder.as_os_str().as_encoded_bytes()); + let account: String = digest.iter().map(|b| format!("{b:02x}")).collect(); + keyring::Entry::new(Self::SERVICE, &format!("generation-v1-{account}")).map_err(store_error) + } } #[cfg(not(target_arch = "wasm32"))] @@ -281,6 +327,22 @@ impl GrantKeyStore for OsGrantKeys { *read = Some(key.clone()); Ok(key) } + + /// Read from the key store each time, since another process on the folder may have raised it. + /// A kept value that is not 8 bytes is an error, so that nothing counts as signed with it. + fn generation(&self, folder: &Path) -> Result, KeyStoreError> { + match Self::generation_entry(folder)?.get_secret() { + Ok(secret) => <[u8; 8]>::try_from(secret.as_slice()) + .map(|bytes| Some(u64::from_be_bytes(bytes))) + .map_err(|_| KeyStoreError("the key store holds a generation of another length".into())), + Err(keyring::Error::NoEntry) => Ok(None), + Err(e) => Err(store_error(e)), + } + } + + fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> { + Self::generation_entry(folder)?.set_secret(&generation.to_be_bytes()).map_err(store_error) + } } /// `vectorcraft-plugin-grant-key.lock` in a folder of this user's own, locked until the file is diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 13e66bda91..2061465570 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4215,6 +4215,58 @@ impl crate::store::grant_keys::GrantKeyStore for UnreachableKeys { fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) } + + fn generation(&self, _: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } + + fn set_generation(&self, _: &std::path::Path, _: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } +} + +/// A memory key store the test keeps a handle on; it fails to keep a generation while +/// `generation_writes_fail` is set. +struct SharedKeys { + keys: std::sync::Arc, + generation_writes_fail: std::sync::Arc, +} + +impl SharedKeys { + fn new(keys: &std::sync::Arc) -> Self { + SharedKeys { keys: keys.clone(), generation_writes_fail: std::sync::Arc::default() } + } +} + +impl crate::store::grant_keys::GrantKeyStore for SharedKeys { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::key(self.keys.as_ref()) + } + + fn set_key(&self, key: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::set_key(self.keys.as_ref(), key) + } + + fn generation(&self, folder: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + crate::store::grant_keys::GrantKeyStore::generation(self.keys.as_ref(), folder) + } + + fn set_generation(&self, folder: &std::path::Path, generation: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + if self.generation_writes_fail.load(std::sync::atomic::Ordering::SeqCst) { + return Err(crate::store::grant_keys::KeyStoreError("the key store can't keep it".into())); + } + crate::store::grant_keys::GrantKeyStore::set_generation(self.keys.as_ref(), folder, generation) + } +} + +/// The generation the grants file `bytes` is at. +fn generation_of(bytes: &[u8]) -> Option { + serde_json::from_slice::(bytes).ok()?["generation"].as_u64() +} + +/// The generation `keys` keeps for the plug-in store `dir`. +fn kept_generation(keys: &crate::store::grant_keys::MemoryGrantKeys, dir: &std::path::Path) -> Option { + crate::store::grant_keys::GrantKeyStore::generation(keys, &crate::store::plugin_store_key(dir)).unwrap() } /// Whether the stored plug-in `id` loads from the plug-in store `dir` at a new start, and whether @@ -4348,16 +4400,7 @@ fn a_grants_file_without_its_key_is_replaced_by_the_next_approval() { std::fs::write(&grants, &signed).unwrap(); std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); let keys = std::sync::Arc::new(MemoryGrantKeys::default()); - struct Shared(std::sync::Arc); - impl GrantKeyStore for Shared { - fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { - self.0.key() - } - fn set_key(&self, key: &GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { - self.0.set_key(key) - } - } - let _keys = ThreadKeys::using(Shared(keys.clone())); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); assert_eq!(starts_from(&folder.0, id, &data), (false, true), "no key, no grant"); assert!(keys.key().unwrap().is_none(), "reading makes no key"); assert_eq!(std::fs::read(&grants).unwrap(), signed, "the file is left as it is"); @@ -4413,22 +4456,23 @@ fn an_unreachable_key_store_keeps_approvals_in_the_session() { assert!(!grants.exists()); } -/// A MAC is made over the grants and the folder, and only the whole MAC of the same key, grants and -/// folder verifies. A key's bytes are never printed. +/// A MAC is made over the generation, the grants and the folder, and only the whole MAC of the same +/// key, generation, grants and folder verifies. A key's bytes are never printed. #[test] fn a_grants_mac_verifies_only_for_its_key_grants_and_folder() { use crate::store::grant_keys::{GrantKey, sign, verify}; let (key, other) = (GrantKey::from_bytes([1; 32]), GrantKey::from_bytes([2; 32])); let folder = std::path::Path::new("/plug-ins"); - let tag = sign(&key, folder, b"[]").unwrap(); + let tag = sign(&key, folder, 4, b"[]").unwrap(); assert_eq!(tag.len(), 64); - assert!(verify(&key, folder, b"[]", &tag)); - assert!(!verify(&other, folder, b"[]", &tag), "another key"); - assert!(!verify(&key, std::path::Path::new("/other"), b"[]", &tag), "another folder"); - assert!(!verify(&key, folder, b"[ ]", &tag), "other grants"); - assert!(!verify(&key, folder, b"[]", &tag[..62]), "a MAC cut short"); - assert!(!verify(&key, folder, b"[]", &tag.to_uppercase()), "upper case"); - assert!(!verify(&key, folder, b"[]", "")); + assert!(verify(&key, folder, 4, b"[]", &tag)); + assert!(!verify(&other, folder, 4, b"[]", &tag), "another key"); + assert!(!verify(&key, std::path::Path::new("/other"), 4, b"[]", &tag), "another folder"); + assert!(!verify(&key, folder, 3, b"[]", &tag), "another generation"); + assert!(!verify(&key, folder, 4, b"[ ]", &tag), "other grants"); + assert!(!verify(&key, folder, 4, b"[]", &tag[..62]), "a MAC cut short"); + assert!(!verify(&key, folder, 4, b"[]", &tag.to_uppercase()), "upper case"); + assert!(!verify(&key, folder, 4, b"[]", "")); assert_eq!(format!("{key:?}"), "GrantKey(..)"); } @@ -4449,6 +4493,14 @@ impl crate::store::grant_keys::GrantKeyStore for KeptFirstElsewhere { fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { Ok(()) } + + fn generation(&self, _: &std::path::Path) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Ok(None) + } + + fn set_generation(&self, _: &std::path::Path, _: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Ok(()) + } } #[test] @@ -4458,7 +4510,183 @@ fn a_new_grants_key_is_the_one_the_key_store_kept() { let key = crate::store::grant_keys::signing_key().unwrap(); assert_eq!(key, GrantKey::from_bytes([7; 32]), "the key kept first signs"); let folder = std::path::Path::new("/plug-ins"); - assert!(verify(&GrantKey::from_bytes([7; 32]), folder, b"[]", &sign(&key, folder, b"[]").unwrap())); + assert!(verify(&GrantKey::from_bytes([7; 32]), folder, 1, b"[]", &sign(&key, folder, 1, b"[]").unwrap())); +} + +/// An earlier copy of the grants file put back over the current one grants nothing: after one +/// plug-in's grant is revoked while another's stays, and after the last grant is revoked and the +/// file removed. +#[test] +fn an_earlier_grants_file_put_back_grants_nothing() { + let folder = crate::tests_links::Folder::new("plugin-store-earlier-copy"); + let id = "test.engine.permissions.earlier"; + let other = "test.engine.permissions.earlierother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []})); + let (data, other_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&other_wasm)); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + let both = std::fs::read(&grants).unwrap(); + run(&mut s, "plugin.remove", json!({"id": other})); + let one = std::fs::read(&grants).unwrap(); + + std::fs::write(&grants, &both).unwrap(); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true), "the revoked grant doesn't come back"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the earlier copy grants nothing"); + std::fs::write(&grants, &one).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the current file keeps its grant"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + std::fs::write(&grants, &one).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the last revoked grant doesn't come back"); + + // A grant revoked from a file edited outside VectorCraft doesn't come back with a signed copy + // made before the edit either. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + let mut edited: Value = serde_json::from_slice(&signed).unwrap(); + edited["mac"] = json!("0".repeat(64)); + std::fs::write(&grants, serde_json::to_vec(&edited).unwrap()).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked from the edited file doesn't come back"); +} + +/// Every signed write of the grants file is at the next generation, which the key store then keeps, +/// and the file stays signed; removing the last grant raises the generation too. +#[test] +fn a_signed_grants_write_raises_the_generation_and_stays_signed() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-generation"); + let id = "test.engine.permissions.generation"; + let other = "test.engine.permissions.generationother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(1), Some(1))); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(2), Some(2))); + run(&mut s, "plugin.remove", json!({"id": other})); + assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(3), Some(3))); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file stays signed"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); + assert_eq!(kept(&folder.0), Some(4), "removing the file raises the generation"); +} + +/// Each plug-in folder has a generation of its own. +#[test] +fn two_plugin_folders_keep_their_own_generations() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let first = crate::tests_links::Folder::new("plugin-store-generation-a"); + let second = crate::tests_links::Folder::new("plugin-store-generation-b"); + let ids = ["test.engine.permissions.foldera", "test.engine.permissions.folderaother", "test.engine.permissions.folderb"]; + let data: Vec = ids.iter().map(|id| vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})))).collect(); + let mut a = session(); + a.attach_plugin_store(first.0.clone()); + run(&mut a, "plugin.install", json!({"dataBase64": data[0], "grant": ["doc.read"]})); + run(&mut a, "plugin.install", json!({"dataBase64": data[1], "grant": ["doc.read"]})); + let mut b = session(); + b.attach_plugin_store(second.0.clone()); + run(&mut b, "plugin.install", json!({"dataBase64": data[2], "grant": ["doc.read"]})); + assert_eq!((kept(&first.0), kept(&second.0)), (Some(2), Some(1))); + assert_eq!(starts_from(&first.0, ids[0], &data[0]), (true, false)); + assert_eq!(starts_from(&second.0, ids[2], &data[2]), (true, false)); + let (mut a, mut b) = (session(), session()); + a.attach_plugin_store(first.0.clone()); + b.attach_plugin_store(second.0.clone()); + run(&mut a, "plugin.remove", json!({"id": ids[0]})); + run(&mut a, "plugin.remove", json!({"id": ids[1]})); + run(&mut b, "plugin.remove", json!({"id": ids[2]})); +} + +/// A key store that holds a key and no generation for the folder, as one does the first time this +/// version runs, reads generation 0: a file signed at 0 keeps its grants, and the next write is at 1. +#[test] +fn a_key_without_a_generation_reads_generation_zero() { + use vectorcraft_plugins::permissions::sha256_hex; + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([5; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-generation-zero"); + let id = "test.engine.permissions.generationzero"; + let other = "test.engine.permissions.generationzeroother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + assert_eq!(crate::store::grant_keys::current_generation(&crate::store::plugin_store_key(&folder.0)), Ok(0)); + let file = crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string()); + assert_eq!(generation_of(&file), Some(0)); + std::fs::write(&grants, &file).unwrap(); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at generation 0 keeps its grant"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]})); + assert_eq!(generation_of(&std::fs::read(&grants).unwrap()), Some(1)); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": other})); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// When the key store can't keep the generation of a write, the file written is one generation ahead +/// of the kept one and grants nothing, so its plug-ins ask again; so does a file one generation +/// behind the kept one, as a write that kept its generation and then failed to write the file would +/// leave it. +#[test] +fn a_grants_file_whose_generation_was_not_kept_grants_nothing() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.generation_writes_fail.clone(); + let _keys = ThreadKeys::using(shared); + let folder = crate::tests_links::Folder::new("plugin-store-generation-unkept"); + let store = crate::store::plugin_store_key(&folder.0); + let id = "test.engine.permissions.generationunkept"; + let other = "test.engine.permissions.generationunkeptother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let written = std::fs::read(&grants).unwrap(); + + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let ahead = std::fs::read(&grants).unwrap(); + let kept = crate::store::grant_keys::GrantKeyStore::generation(keys.as_ref(), &store).unwrap(); + assert_eq!((generation_of(&ahead), kept), (Some(2), Some(1)), "the file is one generation ahead"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "and grants nothing"); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true)); + + std::fs::write(&grants, &written).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at the kept generation keeps its grant"); + crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 2).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "a file one generation behind grants nothing"); } /// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next diff --git a/docs/mcp.md b/docs/mcp.md index 812e3b9446..7fc070afcc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13224,8 +13224,9 @@ flag lasts for that session only. In other sessions the approval, or a `grant` a hash, counts as approved in later sessions and in the desktop app, and covers only that module: the same bytes install again without one, also from a headless session that reads the same `grants.json`, and a module with other bytes has `needsApproval: true` and needs a new one even when it lists the same permissions. A -`grants.json` that does not carry VectorCraft's MAC for its folder (see [plug-ins](plugins.md#grants-file-integrity)) -grants nothing, and its plug-ins have `needsApproval: true` again. When the system key store can't be reached, an +`grants.json` that does not carry VectorCraft's MAC for its folder, or is at another generation than the one the key +store keeps for the folder, such as an earlier copy put back (see [plug-ins](plugins.md#grants-file-integrity)), grants +nothing, and its plug-ins have `needsApproval: true` again. When the system key store can't be reached, an approval lasts for that session only and the file is left as it is. `plugin.remove` forgets the approval, and so does installing a module that lists no permissions under that id: the earlier bytes then need a new approval. A refused install keeps the grant. A failed write of the module to the plug-in store leaves the diff --git a/docs/plugins.md b/docs/plugins.md index a2571e1ff3..972590bb2a 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -358,11 +358,11 @@ each time it is drawn, and a paint linked to a global swatch is drawn in that sw #### Grants file integrity -`grants.json` holds the grants in a JSON object, `{"version": 1, "grants": [...], "mac": "..."}`. `mac` is an -HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)), in lower-case hexadecimal, of the `grants` list -written as compact JSON and of the folder the file is in. The key is 32 random bytes that VectorCraft makes when it -records the first grant. VectorCraft keeps the key in the system key store, as the secret of the account -`hmac-sha256-v1` of the service `org.storytold.vectorcraft.plugin-grants`, and never in a file: +`grants.json` holds the grants in a JSON object, `{"version": 1, "generation": 3, "grants": [...], "mac": "..."}`. +`mac` is an HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)), in lower-case hexadecimal, of the +folder the file is in, the `generation` and the `grants` list written as compact JSON. The key is 32 random bytes that +VectorCraft makes when it records the first grant. VectorCraft keeps the key in the system key store, as the secret of +the account `hmac-sha256-v1` of the service `org.storytold.vectorcraft.plugin-grants`, and never in a file: - On macOS the key is in the user's Keychain. - On Windows the key is a generic credential in Credential Manager. @@ -373,14 +373,25 @@ VectorCraft makes the key while it holds `vectorcraft-plugin-grant-key.lock` in macOS, and in `$XDG_RUNTIME_DIR` elsewhere. When that file can't be locked, or `$XDG_RUNTIME_DIR` is not set, no key is made, and approvals last for the session only, as when the key store can't be reached. -VectorCraft compares the MAC in constant time. A `grants.json` without the MAC of its grants and its folder grants -nothing, and each plug-in it names that lists permissions asks for approval again. This covers a file that an earlier -version wrote (a plain JSON list), a grant that another program edited or added, a file whose `mac` was removed or -changed, a file copied from another `Plug-ins` folder or another computer, and a file whose key is no longer in the key +The key store also keeps a generation for each `Plug-ins` folder, as an 8-byte secret of the account `generation-v1-` +followed by the SHA-256 of the folder's resolved path in hexadecimal, in the same service. A key store that holds no +generation for a folder counts as generation 0. Each time VectorCraft writes a signed `grants.json`, in the folder's +turn (`disabled.lock`), it writes the file at the next generation and then keeps that generation. When it removes a +signed `grants.json`, it keeps the next generation first, and puts the earlier one back when the file can't be removed; +when the key store can't put it back either, the file grants nothing. +When the key store can't keep the generation of a write, the file just written grants nothing, and the write reports a +failure. + +VectorCraft compares the MAC in constant time. A `grants.json` without the MAC of its generation, its grants and its +folder, or at another generation than the one the key store keeps for the folder, grants nothing, and each plug-in it +names that lists permissions asks for approval again. This covers a file that an earlier version wrote (a plain JSON +list), a grant that another program edited or added, a file whose `mac` was removed or changed, a file copied from +another `Plug-ins` folder or another computer, an earlier copy of the file put back after a grant was revoked or the +file was removed, a write whose generation the key store didn't keep, and a file whose key is no longer in the key store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when the key store has none. When a grant is forgotten without an approval (`plugin.remove`, installing a module that lists -no permissions under that id, or a folder load that forgets the grant), VectorCraft takes that entry out of such a file -and leaves the rest unsigned. +no permissions under that id, or a folder load that forgets the grant), VectorCraft keeps the next generation, then +takes that entry out of such a file and leaves the rest unsigned, so no earlier signed copy brings the entry back. When the key store can't be reached (it is locked, or a headless Linux session has no Secret Service), no `grants.json` grants anything and VectorCraft writes none: an approval lasts for the session only, the module stored diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c8eff38c84..686e392e49 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2660,7 +2660,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **A grant that can't be forgotten stops counting in the whole process (G17):** when such a grant can't be removed from `grants.json`, no session in the process that uses the same `Plug-ins` folder, by any path to it, counts it for `plugin.inspect`, `plugin.install` or loading plug-ins, until `grants.json` can be written for that plug-in; another process on the folder reads `grants.json` as it is. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. -- **An edited grants file grants nothing (G17):** `grants.json` carries an HMAC-SHA-256 of its grants and its folder, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time. A file without that MAC (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file. When the key store can't be reached, an approval lasts for the session only and the file is left as it is. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **An edited grants file grants nothing (G17):** `grants.json` carries a generation and an HMAC-SHA-256 of its folder, generation and grants, made with a random key kept in the system key store (Keychain, Credential Manager, the Secret Service) and compared in constant time; the key store keeps each folder's generation, raised on every signed write and removal. A file without that MAC or at another generation (an earlier version's plain list, an edited or added grant, a removed or changed MAC, a file copied from another folder, an earlier copy put back after a revoke, a write whose generation wasn't kept) grants nothing, and its plug-ins ask for approval again; the next approval replaces it with a signed file. When the key store can't be reached, an approval lasts for the session only and the file is left as it is. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) whatever menu the manifest names, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. A command counts as taking a file or folder when its params description or schema names a file key as a param; a word in the description's prose or result does not count. Each exemption for a key that names part of the document names a param its command takes, which `every_command_is_sorted` checks, and Image Trace's path fidelity setting (`params.paths`, `savedPreset.paths`) is exempt only inside those settings. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **The command sweep sends file and folder params into its temp folder by the command catalog:** the sweeps in `crates/engine/tests/command_sweep.rs` take each command's file and folder keys from the catalog (`cmd::location_keys`, the same key list the plug-in call rules use, less the keys that name part of the document in a command), read every key a params description names (`{path | name …}`, `{folder? (…)}` included) and its schema's params, and send every string under such a key, in arrays and in objects inside them (`paths: [{ids, path}]`), as a location in the temp folder, so a command added later is swept and checked without editing the sweep. `diffPath` counts as a file key, and Slice Options' `url` and Export for Screens' `folders` do not. Regressions: `sweep_cases_name_files_only_inside_the_temp_folder` and `sweep_cases_send_the_file_keys_of_the_command_catalog` in `command_sweep`, `location_keys_come_from_the_command_catalog` in `cmd::plugin_call`. Scores and hours unchanged.