Plug-ins: manifests list permissions, the user grants them at install, and the host enforces the grant

A manifest may list `permissions` (doc.read, doc.write, state,
effect.render, export.write) and an `api` level. doc.read, doc.write
and state follow the capability model proposed in
storytold/photocraft#662; the other names are VectorCraft's own. An
unknown, reserved, duplicate or wrong-kind name is refused by name. A
manifest without the key gets the permissions its kind implies and
installs as before.

- Install Plug-in... and File > Open show the name, id, version, file
  SHA-256 and each permission in plain words, with control and
  bidirectional characters escaped and each string cut to 64
  characters. OK installs the module only if it still has the SHA-256
  shown; Cancel installs nothing. The heavy-budget prompt and the
  status line show the escaped name too, and OK keeps the `replace` it
  was given.
- `plugin.install` needs `grant` listing every permission, and
  `plugin.inspect` reports `needsApproval`. `hash` pins the module:
  one with another SHA-256 is refused. The grant is kept with the
  module's hash in the store's `grants.json`, and only that store's
  grants count while it is attached; the same set does not ask again,
  more permissions do, and `plugin.remove` forgets it.
- The Additional Plug-ins Folder and `plugin.reload` install only
  plug-ins the attached store has granted and report the others as
  needing approval. At startup the store skips an ungranted plug-in.
- A filter run without doc.read is given no objects; without state it
  neither reads nor writes `documentData`; without doc.write an output
  that changes the document is refused and the document is unchanged.

Docs: docs/plugins.md, docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo
2026-11-07 15:20:07 -08:00
parent ff9deee46d
commit 1f352bc7c1
45 changed files with 1583 additions and 50 deletions
+103 -25
View File
@@ -13,6 +13,12 @@
//! packing or simulation). It installs only once the user agrees (`plugin.install {allowHeavy}`),
//! which loading a folder doesn't ask, so folders skip it; the app runs it in the background with
//! Cancel ([`FilterRun`]).
//!
//! A plug-in whose manifest lists permissions installs once the user grants them
//! (`plugin.install {grant}`, recorded with the module's hash and kept in the plug-in store), and
//! a filter does only what they allow: without `doc.read` it is given no objects, without
//! `doc.write` an output that changes the document is refused, and without `state` it neither
//! reads nor writes the data it keeps with the document.
use std::sync::{Arc, Mutex};
@@ -22,6 +28,8 @@ use vectorcraft_plugins::{Budget, Kind, Plugin, effect, export, objects, registr
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
use vectorcraft_plugins::permissions::{self, Grant, Permission};
/// What a plug-in error looks like to the user. A run the caller cancelled changed nothing.
fn err(e: vectorcraft_plugins::Error) -> EngineError {
match e {
@@ -37,6 +45,7 @@ pub fn describe(p: &Plugin) -> Value {
"id": m.id, "name": m.name, "version": m.version, "kind": m.kind.name(), "author": m.author, "description": m.description,
"params": m.params_doc(), "paramsSchema": serde_json::to_value(m).ok().and_then(|v| v.get("params").cloned()),
"size": p.size(), "source": p.source(),
"permissions": permissions::names(&m.permissions()), "hash": p.hash(),
});
match m.kind {
Kind::Effect => v["effect"] = json!(effect::effect_id(&m.id)),
@@ -122,15 +131,17 @@ impl FilterRun {
}
// Bad parameters fail before anything runs.
let mut params = Value::Object(m.resolve_params(&plugin_params(p)).map_err(|e| bad(C, e.to_string()))?);
let may = m.permissions();
let st = s.doc()?;
let selected = ids_param(p, "ids").unwrap_or_else(|| st.selection.objects.clone());
let inputs = objects::filter_targets(&st.doc, &selected);
// Without `doc.read` a filter is given no objects: it can only add new ones.
let inputs = if may.contains(&Permission::DocRead) { objects::filter_targets(&st.doc, &selected) } else { Vec::new() };
let parent = st.insertion_parent();
let bounds = st.doc.bounds_of(&inputs, false);
let board = bounds.and_then(|b| st.doc.artboard_at(b.center())).and_then(|i| st.doc.artboards.get(i)).or(st.doc.artboards.first());
let rect = |r: vectorcraft_geom::Rect| json!([r.x0, r.y0, r.x1, r.y1]);
// What the plug-in keeps with the document, as it last wrote it.
let data = st.doc.plugin_data(&m.id).cloned().unwrap_or(Value::Null);
let data = st.doc.plugin_data(&m.id).filter(|_| may.contains(&Permission::State)).cloned().unwrap_or(Value::Null);
params["_context"] = json!({"mode": "filter", "bounds": bounds.map(rect), "artboard": board.map(|a| rect(a.rect)), "documentData": data});
let input = objects::encode_input(&st.doc, &inputs);
let params = serde_json::to_vec(&params).map_err(|e| bad(C, e.to_string()))?;
@@ -175,13 +186,23 @@ impl FilterRun {
}
/// Applies the plug-in's `output` to the active document as one undo step: its objects, and what
/// it keeps with the document from now on.
/// it keeps with the document from now on. An output its permissions don't allow is refused,
/// and the document stays as it was.
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
let m = self.plugin.manifest();
let may = m.permissions();
let out = objects::decode_output(output).map_err(err)?;
if out.document_data.is_some() && !may.contains(&Permission::State) {
return Err(not_granted(&m.name, Permission::State));
}
let may_write = may.contains(&Permission::DocWrite);
let (inputs, parent) = (self.inputs, self.parent);
let ids = s.edit(m.name.trim_end_matches('…'), |d, sel| {
let before = (!may_write).then(|| d.layers.clone());
let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
if before.is_some_and(|b| b != d.layers) {
return Err(not_granted(&m.name, Permission::DocWrite));
}
if let Some(data) = out.document_data {
d.set_plugin_data(&m.id, data);
}
@@ -192,6 +213,12 @@ impl FilterRun {
}
}
/// The error of a filter `name` whose output needs `permission`, which it wasn't granted.
fn not_granted(name: &str, permission: Permission) -> EngineError {
let (name, p) = (permissions::display_text(name, permissions::MAX_SHOWN_NAME), permission.name());
err(vectorcraft_plugins::Error::Output(format!("“{name}” wasn't granted `{p}`, which its output needs: nothing was changed")))
}
/// `plugin.run`: runs filter `id` on `ids` (else the selected paths and compound paths) with its
/// parameters and `_context` (what it keeps with the document included), and applies its output as
/// one undo step ([`objects::apply_output`]; effect records as [`admit_effects`] admits them), with
@@ -283,13 +310,37 @@ fn load_given(c: &str, p: &Value) -> Result<(Plugin, Vec<u8>)> {
}
}
/// The permissions `grant` lists in command `c`'s params: `None` when it is left out (or null).
/// Anything but a list of permission names is an error.
fn grant_param(c: &str, p: &Value) -> Result<Option<Vec<Permission>>> {
let Some(v) = p.get("grant").filter(|v| !v.is_null()) else {
return Ok(None);
};
let names = v.as_array().ok_or_else(|| bad(c, "`grant` must be a list of permission names"))?;
let mut out = Vec::with_capacity(names.len());
for n in names {
let name = n.as_str().ok_or_else(|| bad(c, "`grant` must be a list of permission names"))?;
let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD);
out.push(Permission::parse(name).ok_or_else(|| bad(c, format!("`grant` names an unknown permission `{shown}`")))?);
}
Ok(Some(out))
}
/// `plugin.install`: loads and checks the module, refuses one that asks for a heavy budget unless
/// `allowHeavy` says the user agreed, keeps it for the next start and installs it → its
/// `plugin.list` entry.
/// `allowHeavy` says the user agreed, and one that lists permissions the user hasn't granted its id
/// unless `grant` lists them all, and one whose SHA-256 isn't the `hash` given; records the grant
/// with the module's hash, keeps it for the next start and installs it → its `plugin.list` entry.
fn install(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "plugin.install";
let (replace, allow_heavy) = (switch_or(p, "replace", true, C)?, switch_or(p, "allowHeavy", false, C)?);
let grant = grant_param(C, p)?;
let (plugin, bytes) = load_given(C, p)?;
// `hash` pins the module the user was shown: one with other bytes is refused.
if let Some(h) = p.get("hash").filter(|v| !v.is_null())
&& h.as_str() != Some(plugin.hash())
{
return Err(bad(C, "the module doesn't have the SHA-256 `hash` gives: nothing was installed"));
}
if !replace && registry::get(plugin.id()).is_some() {
return Err(bad(C, format!("a plug-in with id {:?} is already installed", plugin.id())));
}
@@ -304,14 +355,33 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
),
));
}
// A plug-in that lists permissions installs once the user grants them: whoever installs it
// asks them first, unless they already granted its id all of them.
let m = plugin.manifest();
let wanted = m.permissions();
if !s.plugin_approved(&plugin) && !grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))) {
let name = permissions::display_text(&m.name, permissions::MAX_SHOWN_NAME);
let asked = permissions::names(&wanted).join(", ");
return Err(bad(C, format!("“{name}” asks for the permissions {asked}: install it with `grant` listing them once the user agrees")));
}
if m.asks_permissions() {
let g = Grant { id: m.id.clone(), hash: plugin.hash().to_string(), permissions: wanted };
registry::grant(g.clone());
s.store_grant(&m.id, Some(g));
}
// Installed plug-ins stay installed after a restart (#2541).
s.store_plugin(plugin.id(), &bytes);
Ok(describe(&registry::install(plugin)))
}
/// `plugin.inspect`: what installing the module would install, without installing it.
fn inspect(_: &mut Session, p: &Value) -> Result<Value> {
load_given("plugin.inspect", p).map(|(plugin, _)| describe(&plugin))
/// `plugin.inspect`: what installing the module would install, without installing it, and whether
/// that needs the user to grant its permissions first (`needsApproval`).
fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
load_given("plugin.inspect", p).map(|(plugin, _)| {
let mut v = describe(&plugin);
v["needsApproval"] = json!(!s.plugin_approved(&plugin));
v
})
}
/// The plug-in in the `.wasm` file `path`, and its module.
@@ -328,35 +398,40 @@ fn load_path(_: &str) -> Result<(Plugin, Vec<u8>)> {
Err(EngineError::Other("installing from a path is not available on the web; pass the module as `dataBase64`".into()))
}
/// The plug-in folder last loaded from the preferences, and what happened.
static FOLDER: Mutex<Option<(String, Value)>> = Mutex::new(None);
/// The plug-in folder last loaded, the plug-in store whose grants it was loaded with, and what
/// happened.
static FOLDER: Mutex<Option<(String, Option<std::path::PathBuf>, Value)>> = Mutex::new(None);
/// Loads the Additional Plug-ins Folder preference (`*.wasm`) when it is set and has changed since
/// the last load. Runs whenever preferences are applied (startup, `prefs.set`). Native only.
/// Loads the Additional Plug-ins Folder preference (`*.wasm`) when it is set and it, or the
/// session's plug-in store, has changed since the last load. Runs whenever preferences are applied
/// (startup, `prefs.set`). Native only.
pub(crate) fn sync_prefs(s: &Session) {
let folder = s.prefs.plugins_folder.trim();
if folder.is_empty() {
return;
}
let mut last = FOLDER.lock().unwrap_or_else(|e| e.into_inner());
if last.as_ref().is_some_and(|(f, _)| f == folder) {
if last.as_ref().is_some_and(|(f, store, _)| f == folder && *store == s.plugin_dir) {
return;
}
*last = Some((folder.to_string(), load_folder(folder)));
*last = Some((folder.to_string(), s.plugin_dir.clone(), load_folder(s, folder)));
}
/// Loads the plug-ins in `folder`, those that list permissions only when `s` has them granted
/// ([`Session::plugin_approved`], with the store's grants read once).
#[cfg(not(target_arch = "wasm32"))]
fn load_folder(folder: &str) -> Value {
fn load_folder(s: &Session, folder: &str) -> Value {
if let Err(e) = crate::file_access::check_read(folder) {
return json!({"folder": folder, "error": e});
}
// A file in it may be a link to one elsewhere.
match registry::load_folder_where(std::path::Path::new(folder), |f| match f.to_str() {
let allow = |f: &std::path::Path| match f.to_str() {
Some(f) => crate::file_access::check_read(f),
// A lossy name would check another file than the one loaded.
None if crate::file_access::current().is_none() => Ok(()),
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
}) {
};
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_approver()) {
Ok(r) => {
json!({"folder": folder, "loaded": r.loaded, "failed": r.failed.iter().map(|(f, e)| json!({"file": f, "error": e})).collect::<Vec<_>>()})
}
@@ -365,7 +440,7 @@ fn load_folder(folder: &str) -> Value {
}
#[cfg(target_arch = "wasm32")]
fn load_folder(folder: &str) -> Value {
fn load_folder(_: &Session, folder: &str) -> Value {
json!({"folder": folder, "error": "plug-in folders are not available on the web"})
}
@@ -378,16 +453,16 @@ fn reload(s: &mut Session, p: &Value) -> Result<Value> {
if folder.is_empty() {
return Err(bad(C, "no folder: pass `path` or set Preferences › Plug-ins & Scratch Disks › Additional Plug-ins Folder"));
}
let report = load_folder(&folder);
let report = load_folder(s, &folder);
if let Some(e) = report.get("error").and_then(Value::as_str) {
return Err(EngineError::Other(e.to_string()));
}
*FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, report.clone()));
*FOLDER.lock().unwrap_or_else(|e| e.into_inner()) = Some((folder, s.plugin_dir.clone(), report.clone()));
Ok(report)
}
fn list(_: &mut Session, _: &Value) -> Result<Value> {
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, r)| r.clone());
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| r.clone());
Ok(json!({"plugins": registry::list().iter().map(|p| describe(p)).collect::<Vec<_>>(), "folder": folder}))
}
@@ -402,6 +477,9 @@ fn info(_: &mut Session, p: &Value) -> Result<Value> {
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let id = str_param(p, "id").ok_or_else(|| bad("plugin.remove", "missing `id`"))?;
// Installed again, it asks again.
registry::revoke(id);
s.store_grant(id, None);
s.unstore_plugin(id);
if registry::remove(id) { Ok(json!({"removed": id})) } else { Err(err(vectorcraft_plugins::Error::NotFound(id.into()))) }
}
@@ -415,7 +493,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's format id, plugin.<id>, for document.export, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), size, source}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's format id, plugin.<id>, for document.export, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies), hash (the module's SHA-256)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null}",
always,
list
),
@@ -442,7 +520,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Install Plug-in",
[],
None,
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true: a plug-in with the same id is replaced), name?: file name (with dataBase64), allowHeavy?: bool (true once the user agreed to a heavy budget: a filter whose manifest asks for one, budget \"heavy\" in plugin.inspect, installs only with it)} validate and install a WebAssembly plug-in for this session → its plugin.list entry",
"{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true: a plug-in with the same id is replaced), name?: file name (with dataBase64), allowHeavy?: bool (true once the user agreed to a heavy budget: a filter whose manifest asks for one, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (the permissions the user granted: a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash, and replacing the plug-in with one that lists no new permission needs none; with a plug-in store attached, only the grants kept there count), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry",
always,
install
),
@@ -451,7 +529,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Inspect Plug-in",
[],
None,
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have",
"{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions the user hasn't granted its id: plugin.install then needs grant)",
always,
inspect
),
@@ -461,7 +539,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reload Plug-ins",
["Object", "Plug-ins"],
None,
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it (desktop; a bad module is reported and skipped) → {folder, loaded: [id], failed: [{file, error}]}",
"{path?: a folder (default: the Additional Plug-ins Folder preference)} install every *.wasm in it (desktop; a bad module is reported and skipped, and so are a heavy filter and a plug-in that lists permissions the user hasn't granted its id) → {folder, loaded: [id], failed: [{file, error}]}",
always,
reload
),
+81 -2
View File
@@ -14,11 +14,14 @@
//! * **Plug-ins**: the module of each plug-in `plugin.install` installs, as a `.wasm` file named
//! after its id (as Illustrator keeps plug-ins in its Plug-ins folder); `plugin.remove` deletes it.
//! Attaching the folder installs them again. The Additional Plug-ins Folder preference is not
//! copied: it is loaded from where it is.
//! 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 files are untrusted input like any other: sizes and counts are capped, a file that does not
//! parse is skipped with a log record, and every write is atomic.
use std::collections::BTreeMap;
use std::io::Read;
use std::path::{Path, PathBuf};
@@ -41,6 +44,10 @@ const PROFILE_EXT: &str = "icc";
pub const MAX_PLUGIN_STORE: u64 = 512 << 20;
/// The extension of a stored plug-in.
const PLUGIN_EXT: &str = "wasm";
/// The file in the plug-in store that holds the permissions the user granted.
const GRANTS_FILE: &str = "grants.json";
/// The largest grants file read.
const MAX_GRANTS_FILE: u64 = 1 << 20;
/// The file name (without extension) a stored item called `name` gets: its name made safe for any
/// file system, then a hash of the name, so that names that differ only in characters a file name
@@ -217,8 +224,10 @@ impl Session {
}
/// Keep the plug-ins this session installs in `dir`, and install the ones already there (a
/// module that doesn't load is skipped with a log record).
/// module that doesn't load, and one that lists permissions the grants there don't grant it,
/// is skipped with a log record).
pub fn attach_plugin_store(&mut self, dir: PathBuf) {
let grants = stored_grants(&dir);
let limits = vectorcraft_plugins::Limits::default();
let mut left = MAX_PLUGIN_STORE;
for path in list_files(&dir, PLUGIN_EXT) {
@@ -231,6 +240,18 @@ impl Session {
vectorcraft_plugins::Plugin::load(&bytes, limits.clone()).map_err(|e| e.to_string())
});
match loaded {
// Only this store's grants count: one given elsewhere in the process doesn't let a
// module stored here load.
Ok(plugin) if plugin.manifest().asks_permissions() => {
let m = plugin.manifest();
match grants.get(&m.id).filter(|g| g.covers(&m.permissions())) {
Some(g) => {
vectorcraft_plugins::registry::grant(g.clone());
vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string()));
}
None => log::warn!("skipping the stored plug-in {}: the user hasn't granted the permissions it lists", path.display()),
}
}
Ok(plugin) => {
vectorcraft_plugins::registry::install(plugin.with_source(path.display().to_string()));
}
@@ -240,6 +261,26 @@ impl Session {
self.plugin_dir = Some(dir);
}
/// Whether `plugin` installs without asking the user: it lists no permissions, or its id was
/// granted every one it lists, in the grants of the attached plug-in store when there is one,
/// else in this process's ([`vectorcraft_plugins::registry::approved`]).
pub(crate) fn plugin_approved(&self, plugin: &vectorcraft_plugins::Plugin) -> bool {
self.plugin_approver()(plugin)
}
/// [`Session::plugin_approved`] for many plug-ins: reads the store's grants once, when it is
/// made, and checks each plug-in against them.
pub(crate) fn plugin_approver(&self) -> impl Fn(&vectorcraft_plugins::Plugin) -> bool + use<> {
let grants = self.plugin_dir.as_deref().map(stored_grants);
move |plugin| {
let m = plugin.manifest();
match &grants {
Some(grants) if m.asks_permissions() => grants.get(&m.id).is_some_and(|g| g.covers(&m.permissions())),
_ => vectorcraft_plugins::registry::approved(plugin),
}
}
}
/// Write the module `bytes` of the plug-in `id` to the store.
pub(crate) fn store_plugin(&self, id: &str, bytes: &[u8]) {
if let Some(dir) = &self.plugin_dir {
@@ -247,6 +288,25 @@ 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.
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) {
let Some(dir) = &self.plugin_dir else { return };
let mut grants = stored_grants(dir);
let changed = match grant {
Some(g) => grants.insert(id.to_string(), g.clone()).as_ref() != Some(&g),
None => grants.remove(id).is_some(),
};
if !changed {
return;
}
if grants.is_empty() {
take(dir, GRANTS_FILE);
} else if let Ok(bytes) = serde_json::to_vec_pretty(&grants.into_values().collect::<Vec<_>>()) {
put(dir, GRANTS_FILE, &bytes);
}
}
/// Remove the plug-in `id` from the store.
pub(crate) fn unstore_plugin(&self, id: &str) {
if let Some(dir) = &self.plugin_dir {
@@ -255,6 +315,25 @@ impl Session {
}
}
/// The grants kept in the plug-in store `dir`, by plug-in id: none when there is no grants file,
/// and none, with a log record, when it is too large or doesn't parse. Grants for an invalid id are
/// left out.
fn stored_grants(dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
let path = dir.join(GRANTS_FILE);
if !path.is_file() {
return BTreeMap::new();
}
let grants = read_capped(&path, MAX_GRANTS_FILE)
.and_then(|bytes| serde_json::from_slice::<Vec<vectorcraft_plugins::permissions::Grant>>(&bytes).map_err(|e| e.to_string()));
match grants {
Ok(grants) => grants.into_iter().filter(|g| vectorcraft_plugins::manifest::valid_id(&g.id)).map(|g| (g.id.clone(), g)).collect(),
Err(e) => {
log::warn!("skipping the stored plug-in grants {}: {e}", path.display());
BTreeMap::new()
}
}
}
/// The presets of the files in `dir`: valid ones only, no name twice (any case), none called like a
/// built-in preset, at most [`MAX_STORE_FILES`].
fn load_presets(dir: &Path) -> Vec<PdfPreset> {
+224
View File
@@ -523,6 +523,230 @@ fn invalid_install_flags_are_refused() {
assert!(vectorcraft_plugins::registry::get(light).is_none());
}
/// A test filter `id` (named "Test `id`") whose manifest lists `permissions` (a JSON list) and that
/// returns `output`.
fn asking(id: &str, permissions: &str, output: &Value) -> Vec<u8> {
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"2.1","kind":"filter","permissions":{permissions}}}"#);
wat::parse_str(tpl::returning(&manifest, &output.to_string())).unwrap()
}
/// A plug-in whose manifest lists permissions installs only once they are all granted (`grant`),
/// which `plugin.inspect` tells beforehand (`needsApproval`) with the permissions and the module's
/// hash. The grant is recorded with that hash: replacing the plug-in with one that lists the same
/// permissions needs no new grant, and one that lists another needs one. Removing it forgets the
/// grant. A plug-in without `permissions` installs as before, with the ones its kind implies.
#[test]
fn a_plugin_that_lists_permissions_installs_once_they_are_granted() {
let mut s = session();
let id = "test.engine.permissions.install";
let empty = json!({"objects": []});
let data = |perms: &str| vectorcraft_format::base64_encode(&asking(id, perms, &empty));
let reads = data(r#"["doc.read"]"#);
let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": reads}));
assert_eq!((&inspected["needsApproval"], &inspected["permissions"]), (&json!(true), &json!(["doc.read"])));
let hash = vectorcraft_plugins::permissions::sha256_hex(&asking(id, r#"["doc.read"]"#, &empty));
assert_eq!(inspected["hash"], hash);
assert!(vectorcraft_plugins::registry::get(id).is_none(), "inspecting installs nothing");
// Refused without a grant that holds every permission it lists, naming them.
for (grant, says) in [
(Value::Null, "asks for the permissions doc.read"),
(json!([]), "asks for the permissions doc.read"),
(json!(["doc.write"]), "asks for the permissions doc.read"),
(json!(["doc.read", "net.fetch"]), "unknown permission `net.fetch`"),
(json!("doc.read"), "`grant` must be a list"),
(json!([1]), "`grant` must be a list"),
] {
let e = s.execute("plugin.install", &json!({"dataBase64": reads, "grant": grant})).unwrap_err().to_string();
assert!(e.contains(says), "grant {grant}: {e}");
assert!(vectorcraft_plugins::registry::get(id).is_none(), "installed with grant {grant}");
}
// `hash` pins the module the user was shown.
for wrong in [json!("0".repeat(64)), json!(1)] {
let e = s.execute("plugin.install", &json!({"dataBase64": reads, "grant": ["doc.read"], "hash": wrong})).unwrap_err().to_string();
assert!(e.contains("SHA-256 `hash`"), "hash {wrong}: {e}");
assert!(vectorcraft_plugins::registry::get(id).is_none(), "installed with hash {wrong}");
}
let installed = run(&mut s, "plugin.install", json!({"dataBase64": reads, "grant": ["doc.read"], "hash": hash}));
assert_eq!(installed["permissions"], json!(["doc.read"]));
let g = vectorcraft_plugins::registry::granted(id).unwrap();
assert_eq!((g.hash.as_str(), g.permissions.as_slice()), (hash.as_str(), &[vectorcraft_plugins::permissions::Permission::DocRead][..]));
// Replaced with another module that lists the same permissions: no new grant needed, and the
// grant now records the new module's hash.
let other = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "error": null}));
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(&other)}))["needsApproval"], false);
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&other)}));
assert_eq!(vectorcraft_plugins::registry::granted(id).unwrap().hash, vectorcraft_plugins::permissions::sha256_hex(&other));
// One that asks for more is refused until it is granted all of them.
let more = data(r#"["doc.read","doc.write"]"#);
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": more}))["needsApproval"], true);
let e = s.execute("plugin.install", &json!({"dataBase64": more})).unwrap_err().to_string();
assert!(e.contains("doc.read, doc.write") && e.contains("`grant`"), "{e}");
assert_eq!(vectorcraft_plugins::registry::get(id).unwrap().manifest().permissions().len(), 1, "the one installed stays");
run(&mut s, "plugin.install", json!({"dataBase64": more, "grant": ["doc.write", "doc.read", "state"]}));
assert_eq!(vectorcraft_plugins::registry::granted(id).unwrap().permissions.len(), 2, "only what it lists is recorded");
// Removed, it is asked again.
run(&mut s, "plugin.remove", json!({"id": id}));
assert!(vectorcraft_plugins::registry::granted(id).is_none());
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": reads}))["needsApproval"], true);
// A plug-in without `permissions` installs as before, with its kind's.
let plain = install(&mut s, DESATURATE);
assert_eq!(plain["permissions"], json!(["doc.read", "doc.write", "state"]));
assert_eq!(run(&mut s, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(DESATURATE)}))["needsApproval"], false);
}
/// The host enforces what a filter was granted: without `doc.write` an output that changes the
/// document is refused and nothing changes, without `doc.read` it is given no objects, and without
/// `state` it is given no data kept with the document and may not write any.
#[test]
fn a_filter_does_only_what_its_permissions_allow() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let filter = |s: &mut Session, pid: &str| s.execute("plugin.run", &json!({"id": pid, "ids": [id.0]}));
let grant = |s: &mut Session, wasm: &[u8], perms: Value| {
run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(wasm), "grant": perms}));
};
// Denied `doc.write`: renaming the object is refused, and the document and history stay.
let reader = "test.engine.permissions.reader";
grant(&mut s, &asking(reader, r#"["doc.read"]"#, &json!({"objects": [{"id": id.0, "name": "Changed"}]})), json!(["doc.read"]));
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
let e = filter(&mut s, reader).unwrap_err().to_string();
assert!(e.contains("wasn't granted `doc.write`"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
// Deleting it (leaving it out of the output) and adding objects are changes too.
for out in [json!({"objects": []}), json!({"objects": [{"id": id.0}, {"path": triangle()}]})] {
grant(&mut s, &asking(reader, r#"["doc.read"]"#, &out), json!(["doc.read"]));
assert!(filter(&mut s, reader).is_err(), "{out}");
assert_eq!(s.doc().unwrap().doc, before, "{out}");
}
// Returning the object unchanged changes nothing, so it may.
grant(&mut s, &asking(reader, r#"["doc.read"]"#, &json!({"objects": [{"id": id.0}]})), json!(["doc.read"]));
filter(&mut s, reader).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
// Granted `doc.write` alone: it is given no objects, so its triangle is added beside the
// rectangle rather than replacing it.
let writer = "test.engine.permissions.writer";
let manifest = format!(r#"{{"id":"{writer}","name":"W","kind":"filter","permissions":["doc.write"]}}"#);
let added = json!({"objects": [{"path": triangle(), "name": "Given nothing"}]});
let src = tpl::when_given(&manifest, tpl::Given::Input, r#"{"objects":[]}"#, &added.to_string());
grant(&mut s, &wat::parse_str(src).unwrap(), json!(["doc.write"]));
let made = filter(&mut s, writer).unwrap();
let new = NodeId(made["ids"][0].as_u64().unwrap());
assert_eq!(node(&s, new).name.as_deref(), Some("Given nothing"));
assert!(s.doc().unwrap().doc.node(id).is_some(), "the rectangle it wasn't given stays");
// Without `state`: kept data is not handed over, and writing some is refused.
run(
&mut s,
"plugin.install",
json!({"dataBase64": vectorcraft_format::base64_encode(&asking("test.engine.permissions.keeper", "null", &json!({"objects": [{"id": id.0}], "documentData": {"pen": 1}})))}),
);
filter(&mut s, "test.engine.permissions.keeper").unwrap();
let stateless = "test.engine.permissions.keeper";
let manifest = format!(r#"{{"id":"{stateless}","name":"K","kind":"filter","permissions":["doc.read","doc.write"]}}"#);
let src =
tpl::when_given(&manifest, tpl::Given::Params, r#""documentData":null"#, &json!({"objects": [{"id": id.0, "name": "No data"}]}).to_string());
grant(&mut s, &wat::parse_str(src).unwrap(), json!(["doc.read", "doc.write"]));
filter(&mut s, stateless).unwrap();
assert_eq!(node(&s, id).name.as_deref(), Some("No data"), "given no kept data");
let before = s.doc().unwrap().doc.clone();
grant(
&mut s,
&asking(stateless, r#"["doc.read","doc.write"]"#, &json!({"objects": [{"id": id.0}], "documentData": {"pen": 2}})),
json!(["doc.read", "doc.write"]),
);
let e = filter(&mut s, stateless).unwrap_err().to_string();
assert!(e.contains("wasn't granted `state`"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(s.doc().unwrap().doc.plugin_data(stateless), Some(&json!({"pen": 1})));
}
/// What the user granted is kept in the plug-in store with the module: the next session installs
/// the plug-in again without asking. A stored plug-in that lists permissions nobody granted it is
/// skipped, even when another store granted it, and so is one in the Additional Plug-ins Folder
/// until it is granted on its own.
#[test]
fn granted_permissions_are_kept_and_folders_skip_the_rest() {
let folder = crate::tests_links::Folder::new("plugin-store-grants");
let id = "test.engine.permissions.stored";
let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": ["doc.read"]}));
assert!(folder.0.join("grants.json").is_file());
vectorcraft_plugins::registry::remove(id);
vectorcraft_plugins::registry::revoke(id);
let mut next = session();
next.attach_plugin_store(folder.0.clone());
assert!(vectorcraft_plugins::registry::get(id).is_some(), "installed again from the store, as granted");
// Only a store's own grants count: the same module in another store without a grant is
// skipped, and a grant given elsewhere is not written to that store.
let other = crate::tests_links::Folder::new("plugin-store-grants-other");
std::fs::write(other.0.join("copy.wasm"), &wasm).unwrap();
vectorcraft_plugins::registry::remove(id);
let mut elsewhere = session();
elsewhere.attach_plugin_store(other.0.clone());
assert!(vectorcraft_plugins::registry::get(id).is_none(), "granted in another store only");
let e = elsewhere.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap_err().to_string();
assert!(e.contains("`grant`"), "a grant kept in another store doesn't count here: {e}");
let lone = "test.engine.permissions.lone";
let lone_wasm = asking(lone, r#"["doc.read"]"#, &json!({"objects": []}));
run(&mut elsewhere, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&lone_wasm), "grant": ["doc.read"]}));
let kept = std::fs::read_to_string(other.0.join("grants.json")).unwrap();
assert!(kept.contains(lone) && !kept.contains(id), "{kept}");
run(&mut elsewhere, "plugin.remove", json!({"id": lone}));
assert!(!other.0.join("grants.json").exists(), "the last grant removed takes the file with it");
// Without the grant it is skipped, and the file stays.
vectorcraft_plugins::registry::remove(id);
vectorcraft_plugins::registry::revoke(id);
std::fs::remove_file(folder.0.join("grants.json")).unwrap();
let mut third = session();
third.attach_plugin_store(folder.0.clone());
assert!(vectorcraft_plugins::registry::get(id).is_none(), "nobody granted it");
assert_eq!(std::fs::read_dir(&folder.0).unwrap().count(), 1, "the module stays in the store");
// The Additional Plug-ins Folder skips it with a note until it is granted.
let dir = crate::tests_links::Folder::new("plugin-folder-grants");
std::fs::write(dir.0.join("asks.wasm"), &wasm).unwrap();
let r = run(&mut third, "plugin.reload", json!({"path": dir.0.display().to_string()}));
assert_eq!(r["loaded"], json!([]));
let why = r["failed"][0]["error"].as_str().unwrap();
assert!(why.contains("needs approval") && why.contains("doc.read"), "{why}");
run(&mut third, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": ["doc.read"]}));
let r = run(&mut third, "plugin.reload", json!({"path": dir.0.display().to_string()}));
assert_eq!(r["loaded"], json!([id]));
run(&mut third, "plugin.remove", json!({"id": id}));
// With a store attached, only that store's grants load it from the folder: a grant given in a
// session without a store doesn't count.
let mut storeless = session();
run(&mut storeless, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": ["doc.read"]}));
vectorcraft_plugins::registry::remove(id);
assert!(vectorcraft_plugins::registry::granted(id).is_some(), "granted in the process");
let empty = crate::tests_links::Folder::new("plugin-store-grants-empty");
let mut scoped = session();
scoped.attach_plugin_store(empty.0.clone());
let r = run(&mut scoped, "plugin.reload", json!({"path": dir.0.display().to_string()}));
vectorcraft_plugins::registry::revoke(id);
assert_eq!(r["loaded"], json!([]), "a grant outside this store doesn't load it");
let why = r["failed"][0]["error"].as_str().unwrap();
assert!(why.contains("needs approval"), "{why}");
assert!(vectorcraft_plugins::registry::get(id).is_none(), "not installed");
// The preference's folder is loaded again for a session whose store holds other grants.
let pref_dir = crate::tests_links::Folder::new("plugin-folder-pref-grants");
std::fs::write(pref_dir.0.join("asks.wasm"), &wasm).unwrap();
let pref = json!({"key": "pluginsFolder", "value": pref_dir.0.display().to_string()});
run(&mut scoped, "prefs.set", pref.clone());
assert!(vectorcraft_plugins::registry::get(id).is_none(), "nothing granted in this store");
let granting = crate::tests_links::Folder::new("plugin-store-grants-pref");
let mut granted = session();
granted.attach_plugin_store(granting.0.clone());
run(&mut granted, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": ["doc.read"]}));
vectorcraft_plugins::registry::remove(id);
vectorcraft_plugins::registry::revoke(id);
run(&mut granted, "prefs.set", pref);
assert!(vectorcraft_plugins::registry::get(id).is_some(), "loaded under this store's grant");
run(&mut granted, "plugin.remove", json!({"id": id}));
}
/// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next
/// start without asking, with its budget.
#[test]