diff --git a/Cargo.lock b/Cargo.lock index b8995c19ea..d687b2dd30 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -123,10 +123,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", - "cipher", + "cipher 0.4.4", "cpufeatures 0.2.17", ] +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher 0.5.2", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "ahash" version = "0.8.12" @@ -140,6 +151,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "alloc-no-stdlib" version = "2.0.4" @@ -216,6 +236,17 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "apple-native-keyring-store" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a" +dependencies = [ + "keyring-core", + "log", + "security-framework", +] + [[package]] name = "arboard" version = "3.7.0" @@ -550,6 +581,24 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -662,6 +711,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "byteorder-lite" version = "0.1.0" @@ -724,6 +779,15 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher 0.5.2", +] + [[package]] name = "cc" version = "1.9.0" @@ -799,8 +863,18 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", - "inout", + "crypto-common 0.1.7", + "inout 0.1.4", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout 0.2.6", ] [[package]] @@ -821,6 +895,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "cmpv2" version = "0.2.0" @@ -839,7 +919,7 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", "spki", "x509-cert", @@ -915,6 +995,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "core-foundation" version = "0.9.4" @@ -980,6 +1066,12 @@ dependencies = [ "libm", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1363,7 +1455,7 @@ dependencies = [ "semver", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tar", "tempfile", "ureq", @@ -1495,6 +1587,24 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1513,7 +1623,7 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der_derive", "flagset", "pem-rfc7468", @@ -1556,8 +1666,21 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -2614,6 +2737,33 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "http" version = "1.5.0" @@ -2653,6 +2803,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -3027,6 +3186,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -3344,6 +3513,27 @@ dependencies = [ "serde", ] +[[package]] +name = "keyring" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627" +dependencies = [ + "apple-native-keyring-store", + "keyring-core", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", +] + +[[package]] +name = "keyring-core" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "281c851dbae0de36d405299dd463126df4826dc32665c1314e931696b8cdee77" +dependencies = [ + "log", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -3547,7 +3737,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", + "digest 0.10.7", ] [[package]] @@ -3762,12 +3952,75 @@ dependencies = [ "memchr", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -4889,6 +5142,29 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + [[package]] name = "regex-syntax" version = "0.8.11" @@ -5260,6 +5536,25 @@ dependencies = [ "tiny-skia 0.11.4", ] +[[package]] +name = "secret-service" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +dependencies = [ + "aes 0.9.4", + "cbc", + "futures-util", + "getrandom 0.4.3", + "hkdf", + "hybrid-array", + "num", + "once_cell", + "serde", + "sha2 0.11.1", + "zbus", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -5399,7 +5694,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -5410,7 +5705,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -5464,12 +5770,12 @@ checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b" dependencies = [ "aws-lc-rs", "base64 0.22.1", - "const-oid", + "const-oid 0.9.6", "der", - "digest", + "digest 0.10.7", "pem", "rand_core 0.10.1", - "sha2", + "sha2 0.10.9", "signature", "sigstore-types", "spki", @@ -5538,7 +5844,7 @@ dependencies = [ "chrono", "cmpv2", "cms", - "const-oid", + "const-oid 0.9.6", "der", "hex", "rand", @@ -5577,7 +5883,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cms", - "const-oid", + "const-oid 0.9.6", "hex", "pem", "rustls-pki-types", @@ -6827,12 +7133,15 @@ dependencies = [ "crc32fast", "encoding_rs", "flate2", + "getrandom 0.4.3", "hayro-ccitt", "heic-rs", + "hmac 0.12.1", "image", "jxl-color", "jxl-grid", "jxl-oxide", + "keyring", "kurbo 0.13.1", "log", "proptest", @@ -6842,6 +7151,7 @@ dependencies = [ "same-file", "serde", "serde_json", + "sha2 0.10.9", "skrifa 0.47.0", "thiserror 2.0.21", "tiff", @@ -7016,7 +7326,7 @@ dependencies = [ name = "vectorcraft-pdf" version = "0.24.1" dependencies = [ - "aes", + "aes 0.8.4", "chrono", "craft-image-codecs", "craft-pdf", @@ -7034,7 +7344,7 @@ dependencies = [ "objc2-core-graphics", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "siphasher", "skrifa 0.47.0", "smallvec", @@ -7059,7 +7369,7 @@ dependencies = [ "rustix 1.1.6", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", "vectorcraft-color", "vectorcraft-doc", @@ -7980,6 +8290,19 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-native-keyring-store" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8" +dependencies = [ + "byteorder", + "keyring-core", + "regex", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "windows-numerics" version = "0.3.1" @@ -8317,7 +8640,7 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", "sha1", "signature", @@ -8484,6 +8807,17 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus-secret-service-keyring-store" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" +dependencies = [ + "keyring-core", + "secret-service", + "zbus", +] + [[package]] name = "zbus_macros" version = "5.19.0" diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 492e2ea7bf..c638086870 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -50,9 +50,10 @@ pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) { } /// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones -/// installed from now on there. +/// installed from now on there. The key of the grants kept there is in the system's key store. pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) { if let Some(dir) = store_dir("Plug-ins") { + vectorcraft_engine::store::grant_keys::use_os_grant_keys(); session.attach_plugin_store(dir); } } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 075211dc1a..4a393d890f 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -84,6 +84,13 @@ same-file = "1.0.6" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] heic-rs = { version = "=0.1.4", default-features = false, features = ["std", "parallel"], optional = true } rayon = { version = "1.12", optional = true } +# The MAC that `grants.json` carries (grant_keys.rs) and the random key it is made with, which the +# user's key store keeps: Keychain on macOS, Credential Manager on Windows, the Secret Service on +# Linux. All MIT OR Apache-2.0. +hmac = "0.12.1" +sha2 = { version = "0.10", default-features = false } +getrandom = "0.4" +keyring = "4.2" [dev-dependencies] # JPEG XL files for the `.jxl` open and place tests. diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..338ecaf958 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1297,7 +1297,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (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 covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), 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 (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", + "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (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 covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count, and a grants.json without VectorCraft's MAC for that folder grants nothing; when the system key store can't be reached, the grant lasts for this session only; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), 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 (with a plug-in store, the install waits while another window or process changes the store and writes the module and its grant before that window or process changes it again; when the store's disabled.lock can't be locked, nothing is installed) (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 9c555d82f7..59ea6048d0 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -20,7 +20,9 @@ //! disabled, which `disabled.json` in the same folder lists (`plugin.setEnabled`). The Additional //! 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. +//! 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. //! * **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 @@ -50,6 +52,8 @@ use vectorcraft_plugins::storage::{self, Meter, Storage, StorageError}; use crate::Session; use crate::cmd::pdfcmds::{PRESET_FORMAT, PresetFile}; +pub mod grant_keys; + /// Files read from one store folder, at most (the rest are ignored). pub const MAX_STORE_FILES: usize = 1000; /// The largest PDF presets file read (a preset is a few kilobytes). @@ -721,7 +725,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`. A grants file that is too large, can't + /// 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 + /// 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 + /// 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; /// so is one whose new content would be larger than `MAX_GRANTS_FILE`. The file is read and /// written in `turn`. → whether the store now holds what was asked (`false` without a folder, @@ -788,6 +798,21 @@ impl Session { if let Some(between) = AFTER_GRANTS_READ.take() { between(); } + match (file.trust, &grant) { + // Nothing in the file can be checked, so nothing in it is rewritten: a grant holds for + // the session only, and one the file may still hold for `id` can't be removed. + (Trust::Unknown, Some(_)) => return false, + (Trust::Unknown, None) => return !file.names(id), + // The file grants nothing. A new grant replaces it with a signed file that holds that + // grant alone; removing one takes its entry out and leaves the rest unsigned. + (Trust::Unsigned, Some(_)) => { + log::warn!("replacing the stored plug-in grants {}: VectorCraft didn't write them for this folder", dir.join(GRANTS_FILE).display()); + file.grants.clear(); + file.other.clear(); + } + (Trust::Unsigned | Trust::Signed, _) => {} + } + let signed = file.trust == Trust::Signed || grant.is_some(); let others = file.other.len(); file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id)); let changed = match grant { @@ -802,16 +827,7 @@ impl Session { if entries.is_empty() { return take(dir, GRANTS_FILE); } - // 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 serde_json::to_vec_pretty(&entries).ok().filter(fits).or_else(|| serde_json::to_vec(&entries).ok().filter(fits)) { - Some(bytes) => put(dir, GRANTS_FILE, &bytes), - None => { - log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), too_large(MAX_GRANTS_FILE)); - false - } - } + put_grants(dir, entries, signed) } /// Whether the store holds, or may hold, an entry for the plug-in `id`, including one this @@ -1466,10 +1482,13 @@ impl Storage for PluginStorage { /// What the grants file of a plug-in store holds. #[derive(Default)] struct GrantsFile { - /// The grants this version can use, by plug-in id. + /// The grants this version can use, by plug-in id. They grant something only when the file is + /// [`Trust::Signed`]. grants: BTreeMap, /// The entries it can't use (a permission it doesn't know, an invalid id), as they were. other: Vec, + /// Whether VectorCraft wrote the grants for this folder. + trust: Trust, } impl GrantsFile { @@ -1479,6 +1498,103 @@ 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. + #[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. + Unsigned, + /// The key store can't be reached, so it is not known which. It grants nothing, and is left as + /// it is. + Unknown, +} + +/// 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. +#[derive(serde::Serialize, serde::Deserialize)] +struct SignedGrants { + version: u64, + 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. +#[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 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() +} + +/// Tests: the entries of the grants file `bytes`, signed or not. +#[cfg(test)] +pub(crate) fn grant_entries(bytes: &[u8]) -> Vec { + match serde_json::from_slice::(bytes) { + Ok(serde_json::Value::Array(entries)) => entries, + Ok(serde_json::Value::Object(mut file)) => match file.remove("grants") { + Some(serde_json::Value::Array(entries)) => entries, + _ => vec![], + }, + _ => 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. +fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust { + let (Some(tag), true) = (&signed.mac, 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, + Ok(_) => Trust::Unsigned, + Err(e) => { + log::warn!("can't check the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + Trust::Unknown + } + } +} + +/// 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. +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, + 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(mac) = mac else { return false }; + serde_json::to_value(SignedGrants { version: GRANTS_VERSION, grants: entries, mac: Some(mac) }) + } else { + serde_json::to_value(entries) + }; + // 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), + None => { + log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE)); + false + } + } +} + /// 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 @@ -1489,8 +1605,10 @@ struct GrantsError { } /// The grants file of the plug-in store `dir`: empty when there is none, an error when it is too -/// large, can't be read or doesn't hold a list. An entry that doesn't parse as a grant, or names an -/// invalid id, is kept in [`GrantsFile::other`] with a log record. +/// large, can't be read or doesn't hold a list. A list without a MAC (as an older version wrote it), +/// or with one the user's key didn't make for `dir`, is [`Trust::Unsigned`] ([`trust_of`]). An +/// entry that doesn't parse as a grant, or names an invalid id, is kept in [`GrantsFile::other`] +/// with a log record. fn read_grants(dir: &Path) -> Result { let path = dir.join(GRANTS_FILE); let bytes = match read_past_cap(&path, MAX_GRANTS_FILE) { @@ -1501,8 +1619,23 @@ fn read_grants(dir: &Path) -> Result { if bytes.len() as u64 > MAX_GRANTS_FILE { return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) }); } - let entries = serde_json::from_slice::>(&bytes).map_err(|e| GrantsError { unread: false, why: e.to_string() })?; - let mut file = GrantsFile::default(); + let not_a_list = |why: String| GrantsError { unread: false, why }; + let (entries, trust) = match serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))? { + serde_json::Value::Array(entries) => (entries, Trust::Unsigned), + serde_json::Value::Object(_) => { + let signed = serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))?; + let trust = trust_of(dir, &signed); + (signed.grants, trust) + } + _ => return Err(not_a_list("not a list of grants".into())), + }; + if trust == Trust::Unsigned { + log::warn!( + "the stored plug-in grants {} were not written by VectorCraft for this folder: the plug-ins that list permissions ask for them again", + path.display() + ); + } + let mut file = GrantsFile { trust, ..GrantsFile::default() }; let mut first_error = None; for entry in entries { let why = match serde_json::from_value::(entry.clone()) { @@ -1523,11 +1656,13 @@ fn read_grants(dir: &Path) -> Result { } /// The grants kept in the plug-in store `dir` that this version can use, by plug-in id: none when -/// there is no grants file, and none, with a log record, when it is too large, can't be read or -/// doesn't hold a list. +/// there is no grants file, when VectorCraft didn't write it for `dir` or that can't be checked +/// ([`Trust`]), and none, with a log record, when it is too large, can't be read or doesn't hold a +/// list. fn stored_grants(dir: &Path) -> BTreeMap { match read_grants(dir) { - Ok(file) => file.grants, + Ok(file) if file.trust == Trust::Signed => file.grants, + Ok(_) => BTreeMap::new(), Err(e) => { log::warn!("skipping the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); BTreeMap::new() diff --git a/crates/engine/src/store/grant_keys.rs b/crates/engine/src/store/grant_keys.rs new file mode 100644 index 0000000000..a77cce19a7 --- /dev/null +++ b/crates/engine/src/store/grant_keys.rs @@ -0,0 +1,317 @@ +//! The key that marks a plug-in store's `grants.json` as written by VectorCraft. The file carries an +//! HMAC-SHA-256 ([RFC 2104](https://www.rfc-editor.org/rfc/rfc2104)) of the grants it holds and of +//! the plug-in folder it is in, made with a random 32-byte key that the user's key store keeps +//! ([`GrantKeyStore`]), never a file. A grants file without the MAC of that key for its folder (one +//! an older version wrote, one another program wrote or changed, one copied from another folder or +//! machine) grants nothing. +//! +//! 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::sync::{Arc, LazyLock, Mutex}; + +/// The length of a key, in bytes, and of the MAC. +pub const KEY_LEN: usize = 32; + +/// A key for the MAC of grants files. Its bytes are never shown: `{:?}` prints `GrantKey(..)`. +#[derive(Clone, PartialEq, Eq)] +pub struct GrantKey([u8; KEY_LEN]); + +impl GrantKey { + /// The key with the bytes `bytes`. + pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self { + GrantKey(bytes) + } + + /// A new key from the system's random source. + #[cfg(not(target_arch = "wasm32"))] + pub fn random() -> Result { + let mut bytes = [0u8; KEY_LEN]; + getrandom::fill(&mut bytes).map_err(|e| KeyStoreError(format!("no random numbers ({e})")))?; + Ok(GrantKey(bytes)) + } + + /// The browser keeps no grants file. + #[cfg(target_arch = "wasm32")] + pub fn random() -> Result { + Err(KeyStoreError("there is no key store".into())) + } +} + +impl std::fmt::Debug for GrantKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("GrantKey(..)") + } +} + +/// Why a key store gave no key or didn't keep one. The message never holds key bytes. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{0}")] +pub struct KeyStoreError(pub String); + +/// Where the key of grants files is kept. +pub trait GrantKeyStore: Send + Sync { + /// The key kept, `None` when there is none; an error when the store can't be reached or read. + fn key(&self) -> Result, KeyStoreError>; + /// Keep `key` in place of any kept before. + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError>; + /// The key kept, after making and keeping a new one when there is none. The key returned is the + /// one read back from the store, so a key another process kept first wins. + fn create_key(&self) -> Result { + if let Some(key) = self.key()? { + return Ok(key); + } + self.set_key(&GrantKey::random()?)?; + self.key()?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into())) + } +} + +/// A key store in memory: the key lasts as long as the store. For tests and embedders. +#[derive(Default)] +pub struct MemoryGrantKeys { + key: Mutex>, +} + +impl MemoryGrantKeys { + /// A store that holds `key`. + pub fn with_key(key: GrantKey) -> Self { + MemoryGrantKeys { key: Mutex::new(Some(key)) } + } +} + +impl GrantKeyStore for MemoryGrantKeys { + fn key(&self) -> Result, KeyStoreError> { + Ok(self.key.lock().unwrap_or_else(|e| e.into_inner()).clone()) + } + + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { + *self.key.lock().unwrap_or_else(|e| e.into_inner()) = Some(key.clone()); + Ok(()) + } +} + +/// The key store of the process ([`set_grant_key_store`]). +static PROCESS_STORE: Mutex>> = Mutex::new(None); + +/// The one memory store of [`keep_grant_keys_in_memory`]. +static SHARED_MEMORY: LazyLock> = LazyLock::new(Arc::default); + +#[cfg(test)] +thread_local! { + /// Tests: the key store this thread uses in place of the process's. + pub(crate) static THREAD_STORE: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// Use `store` for the grants files of every plug-in store in the process from now on (`None`: no +/// key store, so grants hold for the session only). +pub fn set_grant_key_store(store: Option>) { + *PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()) = store; +} + +/// Keep the key in memory for the rest of the process, one key for every caller: grants files +/// written in the process count in it, and not in another process. For tests. +pub fn keep_grant_keys_in_memory() { + let shared: Arc = SHARED_MEMORY.clone(); + set_grant_key_store(Some(shared)); +} + +/// Keep the key in the system's key store: Keychain on macOS, Credential Manager on Windows, the +/// Secret Service on Linux and the BSDs, as the generic secret `hmac-sha256-v1` of the service +/// `org.storytold.vectorcraft.plugin-grants`. +#[cfg(not(target_arch = "wasm32"))] +pub fn use_os_grant_keys() { + set_grant_key_store(Some(Arc::new(OsGrantKeys::default()))); +} + +/// The key store in use: the thread's in tests, else the process's; in tests, the shared memory +/// store when the process set none. +fn current_store() -> Option> { + #[cfg(test)] + if let Some(store) = THREAD_STORE.with_borrow(Clone::clone) { + return Some(store); + } + let store = PROCESS_STORE.lock().unwrap_or_else(|e| e.into_inner()).clone(); + #[cfg(test)] + let store = store.or_else(|| Some(SHARED_MEMORY.clone() as Arc)); + store +} + +/// The key kept for grants files: `None` when there is none yet, an error when there is no key +/// store or it can't be reached. +pub(crate) fn current_key() -> Result, KeyStoreError> { + current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?.key() +} + +/// The key to sign a grants file with: the one kept, else a new one, kept first +/// ([`GrantKeyStore::create_key`]). +pub(crate) fn signing_key() -> Result { + let store = current_store().ok_or_else(|| KeyStoreError("there is no key store".into()))?; + match store.key()? { + Some(key) => Ok(key), + None => store.create_key(), + } +} + +/// 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`. +#[cfg(not(target_arch = "wasm32"))] +fn mac_of(key: &GrantKey, folder: &Path, 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(); + mac.update(DOMAIN); + mac.update(&(folder.len() as u64).to_be_bytes()); + mac.update(folder); + mac.update(grants); + Some(mac) +} + +/// The MAC of `grants` 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 { + use hmac::Mac; + Some(mac_of(key, folder, 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. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn verify(key: &GrantKey, folder: &Path, 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()) +} + +/// The browser keeps no grants file. +#[cfg(target_arch = "wasm32")] +pub(crate) fn sign(_: &GrantKey, _: &Path, _: &[u8]) -> Option { + None +} + +/// The browser keeps no grants file. +#[cfg(target_arch = "wasm32")] +pub(crate) fn verify(_: &GrantKey, _: &Path, _: &[u8], _: &str) -> bool { + false +} + +/// The bytes written as lower-case hexadecimal digits in `tag`, at most twice [`KEY_LEN`] of them; +/// `None` for anything else. +#[cfg(not(target_arch = "wasm32"))] +fn from_hex(tag: &str) -> Option> { + let digits = tag.as_bytes(); + let (pairs, rest) = digits.as_chunks::<2>(); + if !rest.is_empty() || pairs.len() > KEY_LEN { + return None; + } + let digit = |d: u8| match d { + b'0'..=b'9' => Some(d - b'0'), + b'a'..=b'f' => Some(d - b'a' + 10), + _ => None, + }; + pairs.iter().map(|&[high, low]| Some((digit(high)? << 4) | digit(low)?)).collect() +} + +/// The system's key store, through `keyring`. The key is read once and kept for the process. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct OsGrantKeys { + read: Mutex>, +} + +#[cfg(not(target_arch = "wasm32"))] +impl OsGrantKeys { + const SERVICE: &str = "org.storytold.vectorcraft.plugin-grants"; + const ACCOUNT: &str = "hmac-sha256-v1"; + + fn entry() -> Result { + keyring::Entry::new(Self::SERVICE, Self::ACCOUNT).map_err(store_error) + } + + /// The key the system's key store keeps, read from it. + fn stored(entry: &keyring::Entry) -> Result, KeyStoreError> { + match entry.get_secret() { + // A secret of another length is not a key this version made: there is none. + Ok(secret) => Ok(<[u8; KEY_LEN]>::try_from(secret.as_slice()).ok().map(GrantKey)), + Err(keyring::Error::NoEntry) => Ok(None), + Err(e) => Err(store_error(e)), + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl GrantKeyStore for OsGrantKeys { + fn key(&self) -> Result, KeyStoreError> { + let mut read = self.read.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(key) = read.as_ref() { + return Ok(Some(key.clone())); + } + Ok(Self::stored(&Self::entry()?)?.map(|key| read.insert(key).clone())) + } + + fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> { + let mut read = self.read.lock().unwrap_or_else(|e| e.into_inner()); + Self::entry()?.set_secret(&key.0).map_err(store_error)?; + *read = Some(key.clone()); + Ok(()) + } + + /// Reads the key store again, not the key read before, and makes the key only while holding + /// [`creation_lock`], so that processes of this user that make the first key at the same time + /// all keep the first one made. + fn create_key(&self) -> Result { + let mut read = self.read.lock().unwrap_or_else(|e| e.into_inner()); + let entry = Self::entry()?; + if let Some(key) = Self::stored(&entry)? { + return Ok(read.insert(key).clone()); + } + let _turn = creation_lock()?; + let key = match Self::stored(&entry)? { + Some(key) => key, + None => { + entry.set_secret(&GrantKey::random()?.0).map_err(store_error)?; + Self::stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into()))? + } + }; + *read = Some(key.clone()); + Ok(key) + } +} + +/// `vectorcraft-plugin-grant-key.lock` in a folder of this user's own, locked until the file is +/// dropped, waiting while another process holds it: the temporary folder on Windows and macOS, +/// `$XDG_RUNTIME_DIR` elsewhere. An error when there is no such folder or the file can't be +/// locked: no key is made then. +#[cfg(not(target_arch = "wasm32"))] +fn creation_lock() -> Result { + #[cfg(any(windows, target_os = "macos"))] + let dir = Some(std::env::temp_dir()); + #[cfg(not(any(windows, target_os = "macos")))] + let dir = std::env::var_os("XDG_RUNTIME_DIR").map(std::path::PathBuf::from).filter(|dir| dir.is_absolute()); + let dir = dir.ok_or_else(|| KeyStoreError("there is no folder for the key's lock ($XDG_RUNTIME_DIR is not set)".into()))?; + let file = std::fs::File::options() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(dir.join("vectorcraft-plugin-grant-key.lock")) + .map_err(|e| KeyStoreError(format!("can't open the key's lock ({e})")))?; + file.lock().map_err(|e| KeyStoreError(format!("can't lock the key's lock ({e})")))?; + Ok(file) +} + +/// What a key store error says, without the secret some of them hold. +#[cfg(not(target_arch = "wasm32"))] +fn store_error(e: keyring::Error) -> KeyStoreError { + KeyStoreError(match e { + keyring::Error::NoStorageAccess(e) => format!("the key store is locked or can't be reached ({e})"), + keyring::Error::PlatformFailure(e) => format!("the key store failed ({e})"), + keyring::Error::NoDefaultStore => "there is no key store".into(), + _ => "the key store can't read or keep the key".into(), + }) +} diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..13e66bda91 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2217,11 +2217,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { let other_wasm = asking(other, r#"["doc.read"]"#, &empty); let grants = folder.0.join("grants.json"); let ids = || -> Vec { - serde_json::from_slice::>(&std::fs::read(&grants).unwrap()) - .unwrap() - .iter() - .map(|e| e["id"].as_str().unwrap().to_string()) - .collect() + crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].as_str().unwrap().to_string()).collect() }; let mut s = session(); s.attach_plugin_store(folder.0.clone()); @@ -2241,7 +2237,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { // A grant the store already holds for an id whose stored module lists no permissions. let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); let other_entry = json!({"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]}); - std::fs::write(&grants, serde_json::to_vec(&json!([entry, other_entry])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([entry, other_entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); let mut third = session(); third.attach_plugin_store(folder.0.clone()); @@ -2251,7 +2247,7 @@ fn a_module_without_permissions_ends_the_grant_kept_in_the_store() { // So does an entry this version can't read, and a grant held only by the process. let future = json!({"id": id, "hash": "00", "permissions": ["doc.read", "ui.panel"]}); - std::fs::write(&grants, serde_json::to_vec(&json!([future, other_entry])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([future, other_entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); vectorcraft_plugins::registry::grant(GrantToken::after_engine_approval(Grant { id: id.into(), @@ -2311,8 +2307,8 @@ fn a_grant_that_cannot_be_removed_keeps_the_stored_module() { let file = s.stored_plugin_file(id).unwrap(); // An entry this version can't use is written back as it was read: `1e9` as `1000000000.0`, which // makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", replace.clone()); @@ -2359,8 +2355,8 @@ fn a_grant_left_behind_when_its_module_cannot_go_back_stops_counting() { run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); let file = s.stored_plugin_file(id).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); crate::store::PUT_BACK_FAILS.set(true); @@ -2392,7 +2388,7 @@ fn an_unusable_entry_that_cannot_be_removed_stops_plugin_remove() { let file = s.stored_plugin_file(id).unwrap(); let entry = json!({"id": id, "hash": "0".repeat(64), "permissions": ["no.such.permission"]}); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); @@ -2425,8 +2421,8 @@ fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() { s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.install", json!({"dataBase64": approved_data, "grant": ["doc.read"]})); let file = s.stored_plugin_file(id).unwrap(); - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); std::fs::remove_file(&file).unwrap(); @@ -2455,13 +2451,14 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let needs_approval = json!({"dataBase64": approved_data}); let grants = folder.0.join("grants.json"); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); + let list = json!([entry]).to_string(); + let recorded = |dir: &std::path::Path| crate::store::signed_grants_file(dir, &list); let mut s = session(); s.attach_plugin_store(folder.0.clone()); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)})); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); vectorcraft_plugins::registry::remove(id); let mut next = session(); @@ -2471,12 +2468,12 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let refused = next.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string(); assert!(refused.contains("doc.read"), "{refused}"); - std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap(); + std::fs::write(elsewhere.0.join("grants.json"), recorded(&elsewhere.0)).unwrap(); next.attach_plugin_store(elsewhere.0.clone()); assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); // A load that can rewrite the file forgets the grant, and the store has nothing ignored again. - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); next.attach_plugin_store(folder.0.clone()); assert!(!grants.exists(), "the load removes the grant"); @@ -2486,7 +2483,7 @@ fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() { let mut third = session(); third.attach_plugin_store(folder.0.clone()); std::fs::remove_dir(&grants).unwrap(); - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); assert_eq!(run(&mut third, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the file reads again, and the grant doesn't count"); // Attaching the same store again, with no stored module to try the removal for, keeps it out. @@ -2523,8 +2520,9 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { let needs_approval = json!({"dataBase64": approved_data}); let grants = folder.0.join("grants.json"); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); - std::fs::write(&grants, &recorded).unwrap(); + let list = json!([entry]).to_string(); + let recorded = |dir: &std::path::Path| crate::store::signed_grants_file(dir, &list); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); let mut first = session(); first.attach_plugin_store(folder.0.clone()); let inside = folder.0.join("inside"); @@ -2534,7 +2532,7 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); run(&mut first, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)})); let file = first.stored_plugin_file(id).unwrap(); @@ -2554,13 +2552,13 @@ fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() { later.attach_plugin_store(folder.0.clone()); assert_eq!(run(&mut later, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "a session attached later doesn't count it"); - std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap(); + std::fs::write(elsewhere.0.join("grants.json"), recorded(&elsewhere.0)).unwrap(); other.attach_plugin_store(elsewhere.0.clone()); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts"); other.attach_plugin_store(folder.0.clone()); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "back on the folder, it doesn't"); - std::fs::write(&grants, &recorded).unwrap(); + std::fs::write(&grants, recorded(&folder.0)).unwrap(); assert!(later.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written"); for s in [&mut first, &mut other, &mut later] { assert_eq!(run(s, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again"); @@ -2618,7 +2616,7 @@ fn sessions_attached_before_the_folder_exists_share_its_ignored_grants() { let mut other = session(); other.attach_plugin_store(alias); std::fs::create_dir(&dir).unwrap(); - std::fs::write(dir.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap(); + std::fs::write(dir.join("grants.json"), crate::store::signed_grants_file(&dir, &json!([entry]).to_string())).unwrap(); assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts"); first.ignore_stored_grant(id, first.grant_writes()); @@ -2659,11 +2657,10 @@ fn a_linked_plugin_folder_uses_the_ignored_grants_of_where_the_link_leads() { let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)}); let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]}); - let recorded = serde_json::to_vec(&json!([entry])).unwrap(); let (old, new, link) = (folder.0.join("old"), folder.0.join("new"), folder.0.join("Plug-ins")); for dir in [&old, &new] { std::fs::create_dir(dir).unwrap(); - std::fs::write(dir.join("grants.json"), &recorded).unwrap(); + std::fs::write(dir.join("grants.json"), crate::store::signed_grants_file(dir, &json!([entry]).to_string())).unwrap(); } std::os::unix::fs::symlink(&old, &link).unwrap(); let mut linked = session(); @@ -2730,8 +2727,8 @@ fn a_grant_that_cannot_be_removed_stops_plugin_remove() { let file = s.stored_plugin_file(id).unwrap(); let recorded = std::fs::read(&grants).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&recorded).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let data = crate::store::plugin_data_dir(&folder.0, id); std::fs::create_dir_all(&data).unwrap(); @@ -2789,8 +2786,8 @@ fn settings_that_cannot_be_moved_back_are_reported_and_moved_back_later() { run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]})); let recorded = std::fs::read(&grants).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&recorded).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&recorded).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); let data = crate::store::plugin_data_dir(&folder.0, id); let settings = br#"{"zoom":"aGVsbG8="}"#; @@ -3031,7 +3028,11 @@ fn a_stored_grant_covers_only_the_stored_module_it_recorded() { // A malformed hash is no wildcard, even for the module on disk. let upper = sha256_hex(&first).to_uppercase(); for hash in ["", "00", upper.as_str()] { - std::fs::write(&grants, serde_json::to_vec(&json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}])).unwrap()).unwrap(); + std::fs::write( + &grants, + crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": hash, "permissions": ["doc.read"]}]).to_string()), + ) + .unwrap(); assert!(!starts(), "hash {hash:?}"); } @@ -3091,11 +3092,11 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() { // The grants file is full: the new grant, which is longer, doesn't fit. let cap = 1 << 20; - let mut entries: Vec = serde_json::from_slice(&recorded).unwrap(); + let mut entries: Vec = crate::store::grant_entries(&recorded); entries.push(json!({"id": "", "pad": ""})); - let room = cap - serde_json::to_vec(&entries).unwrap().len(); + let room = cap - crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&entries).unwrap()).len(); *entries.last_mut().unwrap() = json!({"id": "", "pad": "x".repeat(room)}); - let full = serde_json::to_vec(&entries).unwrap(); + let full = crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&entries).unwrap()); assert_eq!(full.len(), cap); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", update.clone()); @@ -3335,7 +3336,7 @@ fn tell_when_waiting(waiting: std::sync::mpsc::Sender<&'static str>) { /// The ids `grants.json` in `dir` holds grants for, and the hash of each. fn stored_grant_hashes(dir: &std::path::Path) -> std::collections::BTreeMap { - let entries: Vec = serde_json::from_slice(&std::fs::read(dir.join("grants.json")).unwrap()).unwrap(); + let entries = crate::store::grant_entries(&std::fs::read(dir.join("grants.json")).unwrap()); entries.iter().map(|e| (e["id"].as_str().unwrap().to_string(), e["hash"].as_str().unwrap().to_string())).collect() } @@ -3637,8 +3638,8 @@ fn a_plain_update_put_back_that_fails_after_writing_keeps_a_disabled_plugin_off( assert!(!disabled.is_empty()); let file = s.stored_plugin_file(id).unwrap(); // `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read. - let entry = serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap().remove(0); - let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes(); + let entry = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).remove(0); + let full = crate::store::signed_grants_file(&folder.0, &format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(","))); std::fs::write(&grants, &full).unwrap(); crate::store::PUT_BACK_FAILS_AFTER_WRITE.set(true); @@ -4099,7 +4100,7 @@ fn a_grant_covers_only_the_module_it_was_given_to() { // A kept grant that records no hash, or an empty one, covers no module: the stored module isn't // installed at the next start and `plugin.inspect` asks for approval. for entry in [json!({"id": id, "permissions": ["settings", "cache"]}), json!({"id": id, "hash": "", "permissions": ["settings", "cache"]})] { - std::fs::write(folder.0.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap(); + std::fs::write(folder.0.join("grants.json"), crate::store::signed_grants_file(&folder.0, &json!([entry]).to_string())).unwrap(); vectorcraft_plugins::registry::remove(id); vectorcraft_plugins::registry::revoke(id); let mut again = session(); @@ -4130,9 +4131,9 @@ fn grants_this_version_cant_read_are_kept() { let invalid = json!({"id": "bad id/", "hash": "00", "permissions": ["doc.read"]}); let grant = json!({"id": kept, "hash": vectorcraft_plugins::permissions::sha256_hex(&kept_wasm), "permissions": ["doc.read"]}); let grants = folder.0.join("grants.json"); - std::fs::write(&grants, serde_json::to_vec(&json!([future, grant, invalid])).unwrap()).unwrap(); + std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([future, grant, invalid]).to_string())).unwrap(); std::fs::write(folder.0.join("kept.wasm"), &kept_wasm).unwrap(); - let entries = || serde_json::from_slice::>(&std::fs::read(&grants).unwrap()).unwrap(); + let entries = || crate::store::grant_entries(&std::fs::read(&grants).unwrap()); let mut s = session(); s.attach_plugin_store(folder.0.clone()); assert!(vectorcraft_plugins::registry::get(kept).is_some(), "the entries this version can't read don't drop the grant next to them"); @@ -4166,7 +4167,7 @@ fn grants_this_version_cant_read_are_kept() { // and left as it is when even compact would. let cap = 1 << 20; let many: Vec = (0..14_000).map(|i| json!({"id": format!("x.{i}"), "hash": "00", "permissions": ["ui.panel"]})).collect(); - let compact = serde_json::to_vec(&many).unwrap(); + let compact = crate::store::signed_grants_file(&folder.0, &serde_json::to_string(&many).unwrap()); assert!(compact.len() < cap && serde_json::to_vec_pretty(&many).unwrap().len() > cap); std::fs::write(&grants, &compact).unwrap(); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]})); @@ -4176,13 +4177,290 @@ fn grants_this_version_cant_read_are_kept() { let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm)})); assert_eq!(inspected["needsApproval"], json!(false), "the compact file is read back"); run(&mut s, "plugin.remove", json!({"id": added})); - let full = serde_json::to_vec(&json!([{"id": "x.full", "hash": "0".repeat(cap - 100), "permissions": ["ui.panel"]}])).unwrap(); + let full = crate::store::signed_grants_file( + &folder.0, + &json!([{"id": "x.full", "hash": "0".repeat(cap - 250), "permissions": ["ui.panel"]}]).to_string(), + ); + assert!(full.len() < cap); std::fs::write(&grants, &full).unwrap(); run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&added_wasm), "grant": ["doc.read"]})); assert_eq!(std::fs::read(&grants).unwrap(), full, "not written past the cap"); run(&mut s, "plugin.remove", json!({"id": added})); } +/// Tests: the key store `store` on this thread until the guard is dropped. +struct ThreadKeys; + +impl ThreadKeys { + fn using(store: impl crate::store::grant_keys::GrantKeyStore + 'static) -> Self { + crate::store::grant_keys::THREAD_STORE.set(Some(std::sync::Arc::new(store))); + ThreadKeys + } +} + +impl Drop for ThreadKeys { + fn drop(&mut self) { + crate::store::grant_keys::THREAD_STORE.set(None); + } +} + +/// A key store that is locked or can't be reached. +struct UnreachableKeys; + +impl crate::store::grant_keys::GrantKeyStore for UnreachableKeys { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + Err(crate::store::grant_keys::KeyStoreError("the key store is locked".into())) + } + + 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())) + } +} + +/// Whether the stored plug-in `id` loads from the plug-in store `dir` at a new start, and whether +/// `plugin.inspect` of `data` (its module) then asks for approval. +fn starts_from(dir: &std::path::Path, id: &str, data: &str) -> (bool, bool) { + vectorcraft_plugins::registry::remove(id); + vectorcraft_plugins::registry::revoke(id); + let mut next = session(); + next.attach_plugin_store(dir.to_path_buf()); + let asks = run(&mut next, "plugin.inspect", json!({"dataBase64": data}))["needsApproval"] == json!(true); + (vectorcraft_plugins::registry::get(id).is_some(), asks) +} + +/// The grants file as VectorCraft wrote it keeps its grants; once it is changed outside VectorCraft +/// it grants nothing, and its plug-ins ask again: a grant given more permissions, a grant added, the +/// MAC taken out or cut short, a MAC made with another key, the file cut short, and the file copied +/// into another plug-in folder. +#[test] +fn a_grants_file_changed_outside_vectorcraft_grants_nothing() { + use crate::store::grant_keys::{GrantKey, MemoryGrantKeys}; + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-signed"); + let copy = crate::tests_links::Folder::new("plugin-store-signed-copy"); + let id = "test.engine.permissions.signed"; + let added = "test.engine.permissions.signedadded"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let added_wasm = asking(added, r#"["doc.read"]"#, &json!({"objects": []})); + let (data, added_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&added_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"]})); + let added_file = folder.0.join(format!("{}.wasm", crate::store::file_stem(added))); + std::fs::write(&added_file, &added_wasm).unwrap(); + let written = std::fs::read(&grants).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file as written keeps its grant"); + + let file: Value = serde_json::from_slice(&written).unwrap(); + let with = |change: &dyn Fn(&mut Value)| { + let mut file = file.clone(); + change(&mut file); + serde_json::to_vec(&file).unwrap() + }; + let other_key = { + let _other = ThreadKeys::using(MemoryGrantKeys::with_key(GrantKey::from_bytes([7; 32]))); + crate::store::signed_grants_file(&folder.0, &file["grants"].to_string()) + }; + let tag = file["mac"].as_str().unwrap().to_string(); + let changed: [(&str, Vec); 6] = [ + ("a permission added", with(&|f| f["grants"][0]["permissions"] = json!(["doc.read", "doc.write"]))), + ( + "a grant added", + with(&|f| f["grants"].as_array_mut().unwrap().push(json!({"id": added, "hash": sha256_hex(&added_wasm), "permissions": ["doc.read"]}))), + ), + ("the MAC taken out", with(&|f| _ = f.as_object_mut().unwrap().remove("mac"))), + ("the MAC cut short", with(&|f| f["mac"] = json!(tag[..32]))), + ("a MAC made with another key", other_key), + ("the file cut short", written[..written.len() - 2].to_vec()), + ]; + for (what, bytes) in changed { + std::fs::write(&grants, &bytes).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "{what}"); + assert_eq!(starts_from(&folder.0, added, &added_data), (false, true), "{what}"); + assert_eq!(std::fs::read(&grants).unwrap(), bytes, "{what}: the file is left as it is"); + } + + std::fs::write(&grants, &written).unwrap(); + std::fs::write(copy.0.join("copied.wasm"), &wasm).unwrap(); + std::fs::write(copy.0.join("grants.json"), &written).unwrap(); + assert_eq!(starts_from(©.0, id, &data), (false, true), "copied into another folder"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file left as written keeps its grant"); + std::fs::remove_file(&added_file).unwrap(); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// A grants file in the form an older version wrote, a plain list, grants nothing. Approving a +/// plug-in again replaces it with a signed file that holds that grant alone; removing a plug-in takes +/// its entry out and leaves the rest unsigned. +#[test] +fn an_unsigned_grants_file_is_replaced_by_the_next_approval() { + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-unsigned"); + let id = "test.engine.permissions.unsigned"; + let other = "test.engine.permissions.unsignedother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let entry = |id: &str, wasm: &[u8]| json!({"id": id, "hash": sha256_hex(wasm), "permissions": ["doc.read"]}); + let unsigned = serde_json::to_vec(&json!([entry(id, &wasm), entry(other, &other_wasm)])).unwrap(); + std::fs::write(&grants, &unsigned).unwrap(); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "an unsigned list grants nothing"); + assert_eq!(std::fs::read(&grants).unwrap(), unsigned, "and is left as it is"); + + // `other` isn't installed, so the removal reports it as not found after removing its entry. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.execute("plugin.remove", &json!({"id": other})).is_err()); + assert_eq!(crate::store::grant_entries(&std::fs::read(&grants).unwrap()), vec![entry(id, &wasm)], "the removal takes its entry out"); + assert!(std::fs::read(&grants).unwrap().starts_with(b"["), "and leaves the rest unsigned"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true)); + + std::fs::write(&grants, &unsigned).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})); + assert_eq!(crate::store::grant_entries(&std::fs::read(&grants).unwrap()), vec![entry(id, &wasm)], "only the new grant is kept"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the approval counts at the next start"); + run(&mut s, "plugin.remove", json!({"id": id})); + assert!(!grants.exists()); +} + +/// With no key in the key store, a signed grants file grants nothing; the next approval makes a key +/// and signs a file that holds that grant alone. +#[test] +fn a_grants_file_without_its_key_is_replaced_by_the_next_approval() { + use crate::store::grant_keys::{GrantKey, GrantKeyStore, MemoryGrantKeys}; + use vectorcraft_plugins::permissions::sha256_hex; + let folder = crate::tests_links::Folder::new("plugin-store-no-key"); + let id = "test.engine.permissions.nokey"; + let other = "test.engine.permissions.nokeyother"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let list = json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}, {"id": other, "hash": "0".repeat(64), "permissions": ["doc.read"]}]); + let signed = { + let _old = ThreadKeys::using(MemoryGrantKeys::with_key(GrantKey::from_bytes([3; 32]))); + crate::store::signed_grants_file(&folder.0, &list.to_string()) + }; + 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())); + 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"); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true})); + assert!(keys.key().unwrap().is_some(), "the approval makes a key"); + let ids: Vec = crate::store::grant_entries(&std::fs::read(&grants).unwrap()).iter().map(|e| e["id"].clone()).collect(); + assert_eq!(ids, vec![json!(id)], "only the new grant is kept"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + run(&mut s, "plugin.remove", json!({"id": id})); +} + +/// When the key store can't be reached, no grants file grants anything and none is written: an +/// approval holds for the session only, the stored module isn't replaced, and a grant the file may +/// hold can't be removed. +#[test] +fn an_unreachable_key_store_keeps_approvals_in_the_session() { + let folder = crate::tests_links::Folder::new("plugin-store-unreachable-keys"); + let id = "test.engine.permissions.unreachable"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&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"]})); + let written = std::fs::read(&grants).unwrap(); + let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap()); + + let locked = ThreadKeys::using(UnreachableKeys); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the stored grant can't be checked"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + let changed = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "error": null})); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&changed), "grant": ["doc.read"], "replace": true})); + assert_eq!( + vectorcraft_plugins::registry::get(id).map(|p| p.hash().to_string()), + Some(vectorcraft_plugins::permissions::sha256_hex(&changed)), + "it runs in this session" + ); + assert_eq!(std::fs::read(&grants).unwrap(), written, "the grants file is left as it is"); + assert_eq!(std::fs::read(&module).unwrap(), wasm, "the store keeps the module its grant covers"); + let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string(); + assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}"); + assert_eq!(std::fs::read(&grants).unwrap(), written); + + drop(locked); + assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the grant counts once the key store can be reached"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.remove", json!({"id": id})); + 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. +#[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(); + 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_eq!(format!("{key:?}"), "GrantKey(..)"); +} + +/// A key store where another process keeps its key between this one's read and its write, and +/// that write does not replace it. +struct KeptFirstElsewhere { + reads: std::sync::Mutex, +} + +impl crate::store::grant_keys::GrantKeyStore for KeptFirstElsewhere { + fn key(&self) -> std::result::Result, crate::store::grant_keys::KeyStoreError> { + let mut reads = self.reads.lock().unwrap(); + *reads += 1; + // signing_key and create_key each read once before the write. + Ok((*reads > 2).then(|| crate::store::grant_keys::GrantKey::from_bytes([7; 32]))) + } + + fn set_key(&self, _: &crate::store::grant_keys::GrantKey) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> { + Ok(()) + } +} + +#[test] +fn a_new_grants_key_is_the_one_the_key_store_kept() { + use crate::store::grant_keys::{GrantKey, sign, verify}; + let _keys = ThreadKeys::using(KeptFirstElsewhere { reads: std::sync::Mutex::new(0) }); + 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())); +} + /// 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] diff --git a/crates/engine/tests/plugin_clear_cache.rs b/crates/engine/tests/plugin_clear_cache.rs index 7a323390c9..488c094c63 100644 --- a/crates/engine/tests/plugin_clear_cache.rs +++ b/crates/engine/tests/plugin_clear_cache.rs @@ -39,6 +39,7 @@ fn clearing_every_cache_empties_each_plugins_cache_and_keeps_its_settings() { let _ = std::fs::remove_dir_all(&folder); std::fs::create_dir_all(&folder).unwrap(); let ids = ["test.clearcache.a", "test.clearcache.b"]; + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.allow_plugin_grants_from_requests(); s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 20546835c1..59091858cb 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -914,6 +914,7 @@ proptest! { let store = Store(std::env::temp_dir().join(format!("vectorcraft-plugin-fuzz-storage-{}", std::process::id()))); let _ = std::fs::remove_dir_all(&store.0); let folder = store.0.clone(); + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.allow_plugin_grants_from_requests(); s.attach_plugin_store(folder.clone()); diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index a469e68f20..d9448e23a2 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -59,11 +59,13 @@ fn installed(id: &str) -> bool { vectorcraft_plugins::registry::get(id).is_some() } -/// A new launch: nothing installed, the plug-in folder `dir` attached. +/// A new launch: nothing installed, the plug-in folder `dir` attached, its grants' key kept in +/// memory. fn launch(dir: &std::path::Path) -> Session { for p in vectorcraft_plugins::registry::list() { vectorcraft_plugins::registry::remove(p.id()); } + vectorcraft_engine::store::grant_keys::keep_grant_keys_in_memory(); let mut s = Session::new(); s.attach_plugin_store(dir.to_path_buf()); s diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..812e3b9446 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13223,7 +13223,10 @@ naming the permissions needed. With `VECTORCRAFT_NO_PREFS` set there is no store flag lasts for that session only. In other sessions the approval, or a `grant` accepted under the flag, is kept with the module's 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. `plugin.remove` +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 +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 grant in the store. A stored module that is disabled, or not read in Safe Mode, keeps the grant for its id. When diff --git a/docs/plugins.md b/docs/plugins.md index 7e6dd26185..a2571e1ff3 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -261,8 +261,10 @@ capability model proposed for PhotoCraft plug-ins `grants.json`, and installs a module that lists permissions only under a grant recorded for this very module, also when it loads the Additional Plug-ins Folder. The approval does not protect against native code linked into VectorCraft or against another program running as the same user, which can change the files in the `Plug-ins` - folder. `grants.json` is not signed, so such a program can add a grant to it. `--allow-plugin-grants` is a choice - the person starting a headless session makes. + folder. `grants.json` carries a MAC made with a key kept in the system key store ([grants file + integrity](#grants-file-integrity)), so a program that only edits the file can't add a grant to it; one running as + the same user can still read the key or change VectorCraft. `--allow-plugin-grants` is a choice the person starting + a headless session makes. - **Replacing asks first.** When the file is another module than the plug-in installed with its id, or, with none installed, its id has settings and a cache in the `Plug-ins` folder, Install Plug-in… and File › Open show its id and SHA-256 and ask whether to install it in place of that plug-in, which gives it the settings and cache kept for @@ -300,8 +302,8 @@ capability model proposed for PhotoCraft plug-ins it held and `grants.json` keeps the grant. The new module runs until the session ends. When the grant can't be removed and the module already stored can't be read back or written back, the new module stays in the folder, and the grant stops counting. The grant also stops counting when the folder held no module for that id. A - `grants.json` larger than 1 MiB, or one that is not a JSON list, grants nothing: the new module stays in the folder, - and `plugin.remove` removes the plug-in. A `grants.json` that can't be opened or read counts as a grant that can't be + `grants.json` larger than 1 MiB, or one that is neither a grants object nor a JSON list, grants nothing: the new + module stays in the folder, and `plugin.remove` removes the plug-in. A `grants.json` that can't be opened or read counts as a grant that can't be removed. When VectorCraft loads the `Plug-ins` folder, it forgets any grant for an id whose stored module lists no permissions. When it can't remove that grant from `grants.json`, or can't read the file, the grant stops counting, including for the next load, which tries the removal again. A grant that stops counting in either of these cases @@ -315,8 +317,8 @@ capability model proposed for PhotoCraft plug-ins covers. An entry of `grants.json` that this version can't use (a permission it doesn't know, an invalid id) is skipped and stays in the file until its plug-in is granted again, replaced by a module that lists no permissions, or removed. When such an entry can't be removed from the file, `plugin.install` and `plugin.remove` treat it as a grant - that can't be removed. A `grants.json` that is not a JSON list is never overwritten, and the file is never written - larger than 1 MiB, the most that is read. When a `Plug-ins` folder is in use, only the grants kept in it count for + that can't be removed. A `grants.json` that is neither a grants object nor a JSON list is never overwritten, and + the file is never written larger than 1 MiB, the most that is read. When a `Plug-ins` folder is in use, only the grants kept in it count for `plugin.install`, `plugin.inspect`, `plugin.reload` and the Additional Plug-ins Folder. At startup, a stored plug-in is skipped when no grant covers its bytes and the permissions it lists. The Additional Plug-ins Folder and `plugin.reload` install only plug-ins that such a grant covers, and report the others. A module without a @@ -354,6 +356,39 @@ geometry, fill rule, reference box and the paints the effect is given: a plug-in changes. Failures are cached too. The swatches and patterns a painted result names are checked against the document each time it is drawn, and a paint linked to a global swatch is drawn in that swatch's current color at its own tint. +#### 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: + +- On macOS the key is in the user's Keychain. +- On Windows the key is a generic credential in Credential Manager. +- On Linux and the BSDs the key is in the Secret Service, for example GNOME Keyring. When its collection is locked, + the desktop may ask to unlock it. + +VectorCraft makes the key while it holds `vectorcraft-plugin-grant-key.lock` in the temporary folder on Windows and +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 +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. + +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 +for the id is not replaced, and `plugin.remove` of a plug-in that the file names returns an error, as for a grant that +can't be removed. With `VECTORCRAFT_NO_PREFS` set there is no plug-in store, and the web build keeps no grants file. The +MAC does not protect against another program running as the same user, which can read the key from the key store or +change VectorCraft itself. + ## ABI v1 A plug-in is a core WebAssembly module (MVP + these post-MVP features: mutable globals, sign extension, saturating diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..c8eff38c84 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2653,13 +2653,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Plug-in grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged. - **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `` dialog cannot set protected field ``"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged. -- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user, the unsigned `grants.json`). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. +- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **A refused plug-in install writes nothing (G17):** `plugin.install` checks the plug-in installed under the module's id and its grant again while it records the grant and installs the module (`registry::install_checked`), and only then writes the module and its grant to the `Plug-ins` folder, attaches its settings and cache and turns a disabled plug-in on. When another session installed a plug-in with the id that would need `replace: true`, or changed the grant the checks relied on, the install is refused and the folder, `grants.json`, the disabled list and the installed plug-in stay as they were. Without a plug-in store, the approval comes from the grant the install checks again. A `plugin.remove`, or a load of the folder or of a plug-ins folder, in another session waits until the install has written the folder. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Windows and processes take turns on the Plug-ins folder:** each one locks `disabled.lock` in the `Plug-ins` folder while it reads and changes the stored modules, `grants.json`, `disabled.json` and the plug-ins' settings and caches, so two installs of one id keep each module with its own grant, and grants or settings written by two processes are all kept. When the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval waits before OK (G17):** the approval dialog's OK stays disabled until its question has been on screen in the focused window for half a second, VectorCraft's own value; a click, Enter, Space, or a press begun before then installs nothing, and the dialog stays open. The wait starts over for every new question, even one that reads the same, and when the window gets the focus back, so a question swapped in just before a click is not approved by it. Cancel works at once. Regressions: `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **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. - **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.