diff --git a/Cargo.lock b/Cargo.lock index a68d9a0..90680a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" +dependencies = [ + "crypto-common 0.2.2", + "inout", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -84,6 +94,18 @@ dependencies = [ "rustversion", ] +[[package]] +name = "argon2" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures", + "password-hash", +] + [[package]] name = "arrayvec" version = "0.7.8" @@ -208,6 +230,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "1.3.2" @@ -229,6 +257,15 @@ dependencies = [ "crunchy", ] +[[package]] +name = "blake2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "blake3" version = "1.8.7" @@ -251,6 +288,15 @@ 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 = "bon" version = "3.10.2" @@ -350,10 +396,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", + "cipher", "cpufeatures", "rand_core 0.10.1", ] +[[package]] +name = "chacha20poly1305" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", +] + [[package]] name = "chrono" version = "0.4.45" @@ -378,6 +437,17 @@ dependencies = [ "phf", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer 0.12.1", + "crypto-common 0.2.2", + "inout", +] + [[package]] name = "clru" version = "0.6.3" @@ -387,6 +457,12 @@ dependencies = [ "hashbrown 0.16.1", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "combine" version = "4.6.9" @@ -503,6 +579,26 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "getrandom 0.4.3", + "hybrid-array", + "rand_core 0.10.1", +] + +[[package]] +name = "ctutils" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe3e9d21d39e6f39ff46e03d5b621424f88ee23d8a1672c6bfc9ccc7f2da4f6a" +dependencies = [ + "cmov", +] + [[package]] name = "darling" version = "0.24.1" @@ -643,8 +739,19 @@ 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", +] + +[[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", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -1760,6 +1867,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[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" @@ -1975,6 +2091,15 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inout" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f" +dependencies = [ + "hybrid-array", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -2116,6 +2241,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + [[package]] name = "levenshtein_automata" version = "0.2.1" @@ -2215,7 +2346,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", + "digest 0.10.7", ] [[package]] @@ -2417,12 +2548,33 @@ dependencies = [ "windows-link", ] +[[package]] +name = "password-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b" +dependencies = [ + "getrandom 0.4.3", + "phc", +] + [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phc" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892" +dependencies = [ + "base64ct", + "ctutils", + "getrandom 0.4.3", +] + [[package]] name = "phf" version = "0.12.1" @@ -2453,6 +2605,16 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "poly1305" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c" +dependencies = [ + "cpufeatures", + "universal-hash", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -3198,12 +3360,28 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + [[package]] name = "stable_deref_trait" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "string-interner" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23de088478b31c349c9ba67816fa55d9355232d63c3afea8bf513e31f0f1d2c0" +dependencies = [ + "hashbrown 0.15.5", + "serde", +] + [[package]] name = "strsim" version = "0.11.1" @@ -3335,6 +3513,24 @@ dependencies = [ "uuid", ] +[[package]] +name = "synapse-modules" +version = "0.1.0" +dependencies = [ + "argon2", + "base64 0.22.1", + "chacha20poly1305", + "getrandom 0.4.3", + "serde", + "serde_json", + "synapse-core", + "tempfile", + "thiserror", + "wasmi", + "wat", + "zeroize", +] + [[package]] name = "synapse-search" version = "0.1.0" @@ -3857,6 +4053,22 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "universal-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" +dependencies = [ + "crypto-common 0.2.2", + "ctutils", +] + [[package]] name = "untrusted" version = "0.9.0" @@ -4033,6 +4245,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser 0.262.0", +] + [[package]] name = "wasm-streams" version = "0.4.2" @@ -4059,6 +4281,89 @@ dependencies = [ "web-sys", ] +[[package]] +name = "wasmi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78693fcdd618e0fc34af59c6b8efa9ac5d58c68df940beff4bedddb6acfe7c27" +dependencies = [ + "spin", + "wasmi_collections", + "wasmi_core", + "wasmi_ir", + "wasmparser 0.228.0", +] + +[[package]] +name = "wasmi_collections" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a8be2aa467cf2d29e96ff759472c36eeb44a3c81c67fc9cb76c9a24c519c557" +dependencies = [ + "string-interner", +] + +[[package]] +name = "wasmi_core" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69372d5fda3ea3d1e0aa6603c7888110e0187e88ea17cd8fc2e2df0a0e1f37fa" +dependencies = [ + "libm", +] + +[[package]] +name = "wasmi_ir" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f17b774caa13c618c7244f1ee51fe23c5e7b8538a471fa46d9949779758aed6" +dependencies = [ + "wasmi_core", +] + +[[package]] +name = "wasmparser" +version = "0.228.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4abf1132c1fdf747d56bbc1bb52152400c70f336870f968b85e89ea422198ae3" +dependencies = [ + "bitflags 2.13.2", + "indexmap", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags 2.13.2", + "indexmap", + "semver", +] + +[[package]] +name = "wast" +version = "262.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30612a0c29249b5f185888a107e8a519d920226b7d07f9d351fd094e9f75eb23" +dependencies = [ + "bumpalo", + "leb128fmt", + "memchr", + "unicode-width", + "wasm-encoder", +] + +[[package]] +name = "wat" +version = "1.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e228027f2b07bbaf946980ebbe2437fca73be6f54c40c2a8d4f42f277075f8d1" +dependencies = [ + "wast", +] + [[package]] name = "web-sys" version = "0.3.106" diff --git a/crates/synapse-modules/Cargo.toml b/crates/synapse-modules/Cargo.toml new file mode 100644 index 0000000..0cf0449 --- /dev/null +++ b/crates/synapse-modules/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "synapse-modules" +version = "0.1.0" +edition.workspace = true +license.workspace = true +description = "Sandboxed WebAssembly modules for Synapse: manifest, permissions, host API, registry" + +[dependencies] +argon2 = "0.6" +base64 = "0.22" +chacha20poly1305 = "0.11" +getrandom = "0.4" +serde.workspace = true +serde_json.workspace = true +synapse-core.workspace = true +thiserror.workspace = true +# Portable loop dispatch: the default tail-call dispatch overflows the stack in debug builds +# and depends on the optimiser per target (Android, Windows); hot paths (crypto) are native. +wasmi = { version = "2", default-features = false, features = ["std", "stable", "validate", "portable-dispatch"] } +zeroize = "1" + +[dev-dependencies] +tempfile = "3" +wat = "1" diff --git a/crates/synapse-modules/src/crypto.rs b/crates/synapse-modules/src/crypto.rs new file mode 100644 index 0000000..1304a5a --- /dev/null +++ b/crates/synapse-modules/src/crypto.rs @@ -0,0 +1,201 @@ +//! Host-side cryptography for modules (`crypto` permission): Argon2id key derivation and +//! XChaCha20-Poly1305 authenticated encryption. Keys never enter the module: it gets opaque +//! handles into a per-instance [`Keyring`], whose keys are zeroed when dropped. + +use crate::{Error, Result}; +use argon2::{Algorithm, Argon2, Params, Version}; +use chacha20poly1305::XChaCha20Poly1305; +use chacha20poly1305::aead::{Aead, KeyInit, Payload}; +use std::collections::HashMap; +use zeroize::Zeroizing; + +pub const KEY_LEN: usize = 32; +pub const NONCE_LEN: usize = 24; +/// Upper bounds for Argon2id parameters a module may ask for (memory in KiB). +pub const MAX_KDF_MEMORY_KIB: u32 = 256 * 1024; +pub const MAX_KDF_ITERATIONS: u32 = 10; +pub const MAX_KDF_LANES: u32 = 4; +/// Largest plaintext or ciphertext handled in one call. +pub const MAX_CRYPTO_INPUT: usize = 1 << 20; +const MAX_KEYS: usize = 64; + +type Key = Zeroizing<[u8; KEY_LEN]>; + +pub fn random_bytes(n: usize) -> Result> { + let mut v = vec![0u8; n]; + getrandom::fill(&mut v).map_err(|e| Error::Host(format!("no randomness: {e}")))?; + Ok(v) +} + +fn random_key() -> Result { + let mut k = Zeroizing::new([0u8; KEY_LEN]); + getrandom::fill(k.as_mut()).map_err(|e| Error::Host(format!("no randomness: {e}")))?; + Ok(k) +} + +/// Keys of one module instance, addressed by small integer handles. +#[derive(Default)] +pub struct Keyring { + keys: HashMap, + next: u32, +} + +impl Keyring { + fn insert(&mut self, key: Key) -> Result { + if self.keys.len() >= MAX_KEYS { + return Err(Error::Invalid("too many keys; forget unused ones".into())); + } + self.next = self.next.wrapping_add(1).max(1); + self.keys.insert(self.next, key); + Ok(self.next) + } + + fn get(&self, handle: u32) -> Result<&Key> { + self.keys + .get(&handle) + .ok_or_else(|| Error::Invalid(format!("unknown key handle {handle}"))) + } + + /// Derives a key from a password with Argon2id. + pub fn derive( + &mut self, + password: &str, + salt: &[u8], + memory_kib: u32, + iterations: u32, + lanes: u32, + ) -> Result { + if memory_kib > MAX_KDF_MEMORY_KIB + || iterations > MAX_KDF_ITERATIONS + || lanes > MAX_KDF_LANES + || !(8..=64).contains(&salt.len()) + { + return Err(Error::Invalid("Argon2 parameters out of range".into())); + } + let params = Params::new(memory_kib, iterations, lanes, Some(KEY_LEN)) + .map_err(|e| Error::Invalid(format!("Argon2 parameters: {e}")))?; + let mut key = Zeroizing::new([0u8; KEY_LEN]); + Argon2::new(Algorithm::Argon2id, Version::V0x13, params) + .hash_password_into(password.as_bytes(), salt, key.as_mut()) + .map_err(|e| Error::Host(format!("Argon2: {e}")))?; + self.insert(key) + } + + /// A new random key. + pub fn generate(&mut self) -> Result { + let k = random_key()?; + self.insert(k) + } + + /// Encrypts with a fresh random nonce; returns `nonce || ciphertext`. + pub fn seal(&self, key: u32, plaintext: &[u8], aad: &[u8]) -> Result> { + if plaintext.len() > MAX_CRYPTO_INPUT { + return Err(Error::Invalid("plaintext too large".into())); + } + let cipher = XChaCha20Poly1305::new_from_slice(self.get(key)?.as_ref()) + .map_err(|_| Error::Host("bad key length".into()))?; + let nonce = random_bytes(NONCE_LEN)?; + let ct = cipher + .encrypt( + nonce.as_slice().try_into().expect("nonce length"), + Payload { + msg: plaintext, + aad, + }, + ) + .map_err(|_| Error::Host("encryption failed".into()))?; + let mut out = nonce; + out.extend(ct); + Ok(out) + } + + /// Decrypts `nonce || ciphertext`; fails when the key, data or associated data is wrong. + pub fn open(&self, key: u32, data: &[u8], aad: &[u8]) -> Result>> { + if data.len() < NONCE_LEN || data.len() > MAX_CRYPTO_INPUT + NONCE_LEN + 16 { + return Err(Error::Decrypt); + } + let cipher = XChaCha20Poly1305::new_from_slice(self.get(key)?.as_ref()) + .map_err(|_| Error::Host("bad key length".into()))?; + let (nonce, ct) = data.split_at(NONCE_LEN); + cipher + .decrypt( + nonce.try_into().expect("nonce length"), + Payload { msg: ct, aad }, + ) + .map(Zeroizing::new) + .map_err(|_| Error::Decrypt) + } + + /// Encrypts key `target` with key `kek` (key wrapping). + pub fn wrap(&self, kek: u32, target: u32, aad: &[u8]) -> Result> { + let t = self.get(target)?.clone(); + self.seal(kek, t.as_ref(), aad) + } + + /// Decrypts a wrapped key and returns a handle to it. + pub fn unwrap_key(&mut self, kek: u32, data: &[u8], aad: &[u8]) -> Result { + let plain = self.open(kek, data, aad)?; + let bytes: [u8; KEY_LEN] = plain.as_slice().try_into().map_err(|_| Error::Decrypt)?; + self.insert(Zeroizing::new(bytes)) + } + + pub fn forget(&mut self, handle: u32) { + self.keys.remove(&handle); + } + + pub fn clear(&mut self) { + self.keys.clear(); + } + + pub fn len(&self) -> usize { + self.keys.len() + } + + pub fn is_empty(&self) -> bool { + self.keys.is_empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn seal_open_and_wrap_round_trip() { + let mut k = Keyring::default(); + let kek = k + .derive("correct horse", b"saltsaltsalt", 1024, 1, 1) + .unwrap(); + let same = k + .derive("correct horse", b"saltsaltsalt", 1024, 1, 1) + .unwrap(); + let other = k.derive("wrong", b"saltsaltsalt", 1024, 1, 1).unwrap(); + let dek = k.generate().unwrap(); + let wrapped = k.wrap(kek, dek, b"vault").unwrap(); + let dek2 = k.unwrap_key(same, &wrapped, b"vault").unwrap(); + assert!(k.unwrap_key(other, &wrapped, b"vault").is_err()); + assert!(k.unwrap_key(same, &wrapped, b"other aad").is_err()); + + let ct = k.seal(dek, b"hunter2", b"entry/1").unwrap(); + assert_eq!(&**k.open(dek2, &ct, b"entry/1").unwrap(), b"hunter2"); + assert!(k.open(dek2, &ct, b"entry/2").is_err()); + let mut tampered = ct.clone(); + *tampered.last_mut().unwrap() ^= 1; + assert!(k.open(dek2, &tampered, b"entry/1").is_err()); + // Fresh nonce each time. + assert_ne!(ct, k.seal(dek, b"hunter2", b"entry/1").unwrap()); + + k.forget(dek2); + assert!(k.open(dek2, &ct, b"entry/1").is_err()); + } + + #[test] + fn refuses_extreme_kdf_parameters() { + let mut k = Keyring::default(); + assert!( + k.derive("p", b"saltsaltsalt", MAX_KDF_MEMORY_KIB + 1, 1, 1) + .is_err() + ); + assert!(k.derive("p", b"short", 1024, 1, 1).is_err()); + } +} diff --git a/crates/synapse-modules/src/host.rs b/crates/synapse-modules/src/host.rs new file mode 100644 index 0000000..bd46126 --- /dev/null +++ b/crates/synapse-modules/src/host.rs @@ -0,0 +1,400 @@ +//! A running module: a wasmi instance plus the host functions it may call. +//! +//! ABI (module API v1), all strings UTF-8 JSON: +//! - The module exports `memory`, `syn_alloc(len: i32) -> i32` (a buffer the host may fill) and +//! `syn_handle(ptr: i32, len: i32)` (handle one request from the app). +//! - Inside `syn_handle` the module answers by calling the host import +//! `synapse.respond(ptr, len)` once. +//! - To use the host it calls `synapse.call(ptr, len) -> i32` with `{"fn": name, ...args}`; the +//! host keeps the JSON reply (`{"ok": value}` or `{"error": message}`) and returns its length, +//! then the module copies it into its own memory with `synapse.take(ptr)`. +//! +//! Every request runs with a fuel budget and the instance's memory is capped, so a broken or +//! hostile module cannot hang or exhaust the app. A trap discards the instance (its state, +//! such as unlocked keys, is lost); the next request starts a fresh one. + +use crate::crypto::{Keyring, random_bytes}; +use crate::manifest::{Manifest, Permission}; +use crate::{Error, Result}; +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as B64; +use serde_json::{Value, json}; +use std::sync::{Arc, Mutex}; +use synapse_core::{Graph, Placement}; +use wasmi::{ + Caller, Config, Engine, Instance as WasmInstance, Linker, Memory, Module, Store, StoreLimits, + StoreLimitsBuilder, TypedFunc, +}; + +/// Fuel for one request (roughly one unit per instruction). +pub const FUEL_PER_REQUEST: u64 = 1_000_000_000; +/// Linear memory cap per instance. +pub const MAX_MEMORY: usize = 64 << 20; +/// Largest request, response or host-call payload. +pub const MAX_MESSAGE: usize = 4 << 20; + +pub(crate) struct HostState { + manifest: Manifest, + graph: Arc>, + keys: Keyring, + pending: Vec, + response: Option>, + limits: StoreLimits, + log: Vec, +} + +pub(crate) fn engine() -> Engine { + let mut config = Config::default(); + config.consume_fuel(true); + Engine::new(&config) +} + +/// Compiles a module (validation only; nothing runs). +pub(crate) fn compile(engine: &Engine, wasm: &[u8]) -> Result { + Module::new(engine, wasm).map_err(|e| Error::Invalid(format!("invalid WebAssembly: {e}"))) +} + +pub struct Running { + store: Store, + memory: Memory, + alloc: TypedFunc, + handle: TypedFunc<(i32, i32), ()>, +} + +fn memory_of(caller: &Caller<'_, HostState>) -> Result { + caller + .get_export("memory") + .and_then(|e| e.into_memory()) + .ok_or_else(|| wasmi::Error::new("module exports no memory")) +} + +fn read_bytes(caller: &Caller<'_, HostState>, ptr: i32, len: i32) -> Result, wasmi::Error> { + let len = usize::try_from(len).map_err(|_| wasmi::Error::new("negative length"))?; + if len > MAX_MESSAGE { + return Err(wasmi::Error::new("message too large")); + } + let mut buf = vec![0u8; len]; + memory_of(caller)? + .read(caller, ptr as u32 as usize, &mut buf) + .map_err(|_| wasmi::Error::new("out of bounds read"))?; + Ok(buf) +} + +impl Running { + pub(crate) fn start( + engine: &Engine, + module: &Module, + manifest: Manifest, + graph: Arc>, + ) -> Result { + let state = HostState { + manifest, + graph, + keys: Keyring::default(), + pending: Vec::new(), + response: None, + limits: StoreLimitsBuilder::new() + .memory_size(MAX_MEMORY) + .instances(1) + .memories(1) + .tables(4) + .build(), + log: Vec::new(), + }; + let mut store = Store::new(engine, state); + store.limiter(|s| &mut s.limits); + let mut linker = Linker::::new(engine); + linker + .func_wrap( + "synapse", + "call", + |mut caller: Caller<'_, HostState>, ptr: i32, len: i32| -> Result { + let req = read_bytes(&caller, ptr, len)?; + let reply = match dispatch(caller.data_mut(), &req) { + Ok(v) => json!({ "ok": v }), + Err(e) => json!({ "error": e.to_string() }), + }; + let bytes = serde_json::to_vec(&reply).map_err(|e| wasmi::Error::new(e.to_string()))?; + if bytes.len() > MAX_MESSAGE { + return Err(wasmi::Error::new("host reply too large")); + } + let n = bytes.len() as i32; + caller.data_mut().pending = bytes; + Ok(n) + }, + ) + .and_then(|l| { + l.func_wrap( + "synapse", + "take", + |mut caller: Caller<'_, HostState>, ptr: i32| -> Result<(), wasmi::Error> { + let bytes = std::mem::take(&mut caller.data_mut().pending); + memory_of(&caller)? + .write(&mut caller, ptr as u32 as usize, &bytes) + .map_err(|_| wasmi::Error::new("out of bounds write")) + }, + ) + }) + .and_then(|l| { + l.func_wrap( + "synapse", + "respond", + |mut caller: Caller<'_, HostState>, ptr: i32, len: i32| -> Result<(), wasmi::Error> { + let bytes = read_bytes(&caller, ptr, len)?; + caller.data_mut().response = Some(bytes); + Ok(()) + }, + ) + }) + .map_err(|e| Error::Host(e.to_string()))?; + store + .set_fuel(FUEL_PER_REQUEST) + .map_err(|e| Error::Host(e.to_string()))?; + let instance: WasmInstance = linker + .instantiate_and_start(&mut store, module) + .map_err(|e| Error::Module(format!("cannot start: {e}")))?; + let memory = instance + .get_memory(&store, "memory") + .ok_or_else(|| Error::Module("exports no memory".into()))?; + let alloc = instance + .get_typed_func::(&store, "syn_alloc") + .map_err(|e| Error::Module(format!("syn_alloc: {e}")))?; + let handle = instance + .get_typed_func::<(i32, i32), ()>(&store, "syn_handle") + .map_err(|e| Error::Module(format!("syn_handle: {e}")))?; + Ok(Self { + store, + memory, + alloc, + handle, + }) + } + + /// Sends one request and returns the module's JSON response, with effects the module may + /// not cause (by permission) removed. An error means the instance must be discarded. + pub fn request(&mut self, request: &Value) -> Result { + let bytes = serde_json::to_vec(request)?; + if bytes.len() > MAX_MESSAGE { + return Err(Error::Invalid("request too large".into())); + } + self.store + .set_fuel(FUEL_PER_REQUEST) + .map_err(|e| Error::Host(e.to_string()))?; + self.store.data_mut().response = None; + let ptr = self + .alloc + .call(&mut self.store, bytes.len() as i32) + .map_err(|e| Error::Module(format!("syn_alloc failed: {e}")))?; + self.memory + .write(&mut self.store, ptr as u32 as usize, &bytes) + .map_err(|_| Error::Module("syn_alloc returned a bad pointer".into()))?; + self.handle + .call(&mut self.store, (ptr, bytes.len() as i32)) + .map_err(|e| Error::Module(format!("crashed: {e}")))?; + let out = self + .store + .data_mut() + .response + .take() + .ok_or_else(|| Error::Module("gave no response".into()))?; + let mut v: Value = serde_json::from_slice(&out) + .map_err(|e| Error::Module(format!("bad response JSON: {e}")))?; + filter_effects(&self.store.data().manifest, &mut v); + Ok(v) + } + + /// Log lines written by the module since the last call (for diagnostics). + pub fn take_log(&mut self) -> Vec { + std::mem::take(&mut self.store.data_mut().log) + } + + pub fn keys_held(&self) -> usize { + self.store.data().keys.len() + } +} + +/// Removes `copy` effects from modules without the clipboard permission. +fn filter_effects(manifest: &Manifest, v: &mut Value) { + if manifest.permissions.contains(&Permission::Clipboard) { + return; + } + if let Some(effects) = v.get_mut("effects").and_then(Value::as_array_mut) { + effects.retain(|e| e.get("copy").is_none()); + } +} + +fn need(state: &HostState, p: Permission) -> Result<()> { + if state.manifest.permissions.contains(&p) { + Ok(()) + } else { + Err(Error::Denied(p.as_str().into())) + } +} + +fn arg_str<'a>(args: &'a Value, name: &str) -> Result<&'a str> { + args.get(name) + .and_then(Value::as_str) + .ok_or_else(|| Error::Invalid(format!("missing string argument {name:?}"))) +} + +fn arg_u32(args: &Value, name: &str) -> Result { + args.get(name) + .and_then(Value::as_u64) + .and_then(|n| u32::try_from(n).ok()) + .ok_or_else(|| Error::Invalid(format!("missing integer argument {name:?}"))) +} + +fn arg_b64(args: &Value, name: &str) -> Result> { + B64.decode(arg_str(args, name)?) + .map_err(|_| Error::Invalid(format!("{name:?} is not base64"))) +} + +fn graph(state: &HostState) -> std::sync::MutexGuard<'_, Graph> { + state.graph.lock().unwrap_or_else(|p| p.into_inner()) +} + +/// Runs one host function for the module. +fn dispatch(state: &mut HostState, req: &[u8]) -> Result { + let args: Value = + serde_json::from_slice(req).map_err(|e| Error::Invalid(format!("bad call: {e}")))?; + let name = arg_str(&args, "fn")?.to_string(); + let id = state.manifest.id.clone(); + match name.as_str() { + "log" => { + let msg = arg_str(&args, "msg")?; + if state.log.len() < 200 { + state.log.push(msg.chars().take(500).collect()); + } + Ok(Value::Null) + } + "now" => Ok(json!( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) + )), + "random" => { + let n = arg_u32(&args, "len")? as usize; + if n > 4096 { + return Err(Error::Invalid("at most 4096 random bytes".into())); + } + Ok(json!(B64.encode(random_bytes(n)?))) + } + "kv.get" => { + need(state, Permission::Storage)?; + Ok(json!( + graph(state).module_data(&id, arg_str(&args, "key")?)? + )) + } + "kv.set" => { + need(state, Permission::Storage)?; + let key = arg_str(&args, "key")?; + let value = match args.get("value") { + None | Some(Value::Null) => None, + Some(Value::String(s)) => Some(s.as_str()), + Some(_) => return Err(Error::Invalid("value must be a string or null".into())), + }; + graph(state).set_module_data(&id, key, value)?; + Ok(Value::Null) + } + "kv.list" => { + need(state, Permission::Storage)?; + let prefix = args.get("prefix").and_then(Value::as_str).unwrap_or(""); + let rows = graph(state).module_data_list(&id, prefix)?; + Ok(Value::Array( + rows.into_iter() + .map(|(k, v)| json!({ "key": k, "value": v })) + .collect(), + )) + } + "crypto.derive" => { + need(state, Permission::Crypto)?; + let h = state.keys.derive( + arg_str(&args, "password")?, + &arg_b64(&args, "salt")?, + arg_u32(&args, "memory_kib")?, + arg_u32(&args, "iterations")?, + arg_u32(&args, "lanes")?, + )?; + Ok(json!(h)) + } + "crypto.generate" => { + need(state, Permission::Crypto)?; + Ok(json!(state.keys.generate()?)) + } + "crypto.seal" => { + need(state, Permission::Crypto)?; + let ct = state.keys.seal( + arg_u32(&args, "key")?, + arg_str(&args, "plaintext")?.as_bytes(), + arg_str(&args, "aad")?.as_bytes(), + )?; + Ok(json!(B64.encode(ct))) + } + "crypto.open" => { + need(state, Permission::Crypto)?; + let plain = state.keys.open( + arg_u32(&args, "key")?, + &arg_b64(&args, "data")?, + arg_str(&args, "aad")?.as_bytes(), + )?; + let text = std::str::from_utf8(&plain).map_err(|_| Error::Decrypt)?; + Ok(json!(text)) + } + "crypto.wrap" => { + need(state, Permission::Crypto)?; + let w = state.keys.wrap( + arg_u32(&args, "key")?, + arg_u32(&args, "target")?, + arg_str(&args, "aad")?.as_bytes(), + )?; + Ok(json!(B64.encode(w))) + } + "crypto.unwrap" => { + need(state, Permission::Crypto)?; + let h = state.keys.unwrap_key( + arg_u32(&args, "key")?, + &arg_b64(&args, "data")?, + arg_str(&args, "aad")?.as_bytes(), + )?; + Ok(json!(h)) + } + "crypto.forget" => { + need(state, Permission::Crypto)?; + state.keys.forget(arg_u32(&args, "key")?); + Ok(Value::Null) + } + "crypto.forget_all" => { + need(state, Permission::Crypto)?; + state.keys.clear(); + Ok(Value::Null) + } + "pages.get" => { + need(state, Permission::PagesRead)?; + let g = graph(state); + let Some(page) = g.page_by_title(arg_str(&args, "title")?)? else { + return Ok(Value::Null); + }; + let mut md = String::new(); + for (depth, b) in g.page_tree(page.id)? { + for (i, line) in b.content.lines().enumerate() { + md.push_str(&" ".repeat(depth)); + md.push_str(if i == 0 { "- " } else { " " }); + md.push_str(line); + md.push('\n'); + } + } + Ok(json!({ "title": page.title, "markdown": md })) + } + "pages.append" => { + need(state, Permission::PagesWrite)?; + let title = arg_str(&args, "title")?; + let text = arg_str(&args, "text")?; + let g = graph(state); + let page = g.ensure_page(title, None)?; + let b = g.insert_block(page.id, Placement::LastChildOf(None), text)?; + Ok(json!({ "page": page.title, "block": b.id.to_string() })) + } + other => Err(Error::Invalid(format!("unknown host function {other:?}"))), + } +} diff --git a/crates/synapse-modules/src/lib.rs b/crates/synapse-modules/src/lib.rs new file mode 100644 index 0000000..465afdb --- /dev/null +++ b/crates/synapse-modules/src/lib.rs @@ -0,0 +1,41 @@ +//! Sandboxed WebAssembly modules that extend Synapse. +//! +//! A module is a single `.wasm` file with its [`Manifest`] embedded in a custom section. It +//! runs in a wasmi interpreter (no JIT, so it works on every platform the app targets) with a +//! fuel budget and a memory cap, and reaches the app only through host functions gated by the +//! permissions the user granted at install time. Its UI is data: views and block macros are +//! JSON trees the app renders. See `docs/modules.md`. + +pub mod crypto; +mod host; +pub mod manifest; +mod registry; + +pub use host::{FUEL_PER_REQUEST, MAX_MEMORY, MAX_MESSAGE, Running}; +pub use manifest::{API_VERSION, MANIFEST_SECTION, Manifest, Permission, ViewDecl}; +pub use registry::{ModuleInfo, Registry}; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid: {0}")] + Invalid(String), + #[error("permission denied: {0}")] + Denied(String), + #[error("not found: {0}")] + NotFound(String), + #[error("decryption failed (wrong key or tampered data)")] + Decrypt, + /// The module misbehaved (trap, out of fuel, bad response); its instance is discarded. + #[error("module error: {0}")] + Module(String), + #[error("host error: {0}")] + Host(String), + #[error(transparent)] + Core(#[from] synapse_core::Error), + #[error(transparent)] + Io(#[from] std::io::Error), + #[error(transparent)] + Json(#[from] serde_json::Error), +} + +pub type Result = std::result::Result; diff --git a/crates/synapse-modules/src/manifest.rs b/crates/synapse-modules/src/manifest.rs new file mode 100644 index 0000000..6f43641 --- /dev/null +++ b/crates/synapse-modules/src/manifest.rs @@ -0,0 +1,224 @@ +//! Module manifest: identity, permissions and contributions, embedded in the `.wasm` file as a +//! custom section named [`MANIFEST_SECTION`] holding JSON. + +use crate::{Error, Result}; +use serde::{Deserialize, Serialize}; + +/// Name of the custom section that holds the manifest JSON. +pub const MANIFEST_SECTION: &str = "synapse.manifest"; +/// Module API version this host speaks. +pub const API_VERSION: u32 = 1; + +/// What a module may do. Host functions behind a permission fail for modules without it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum Permission { + /// Its own key-value store, synced with the graph. + #[serde(rename = "storage")] + Storage, + /// Key derivation (Argon2id) and authenticated encryption (XChaCha20-Poly1305) done by + /// the host; keys stay in the host. + #[serde(rename = "crypto")] + Crypto, + /// Put text on the clipboard (cleared after a delay). + #[serde(rename = "clipboard")] + Clipboard, + /// Read pages. + #[serde(rename = "pages:read")] + PagesRead, + /// Create pages and add blocks to them. + #[serde(rename = "pages:write")] + PagesWrite, +} + +impl Permission { + pub fn as_str(self) -> &'static str { + match self { + Permission::Storage => "storage", + Permission::Crypto => "crypto", + Permission::Clipboard => "clipboard", + Permission::PagesRead => "pages:read", + Permission::PagesWrite => "pages:write", + } + } + + pub fn parse(s: &str) -> Option { + serde_json::from_value(serde_json::Value::String(s.to_string())).ok() + } +} + +/// A view the module adds to the sidebar, rendered from the UI tree it returns. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ViewDecl { + pub id: String, + pub title: String, + #[serde(default)] + pub icon: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Manifest { + pub api: u32, + pub id: String, + pub name: String, + pub version: String, + #[serde(default)] + pub description: String, + #[serde(default)] + pub author: String, + #[serde(default)] + pub permissions: Vec, + #[serde(default)] + pub views: Vec, + /// Names of the `{{name args}}` block macros the module renders. + #[serde(default)] + pub macros: Vec, + /// When set, the app sends a `tick` request this often (seconds, >= 5) while it runs. + #[serde(default)] + pub tick_seconds: Option, +} + +fn simple_name(s: &str) -> bool { + !s.is_empty() + && s.len() <= 32 + && s.bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_') +} + +impl Manifest { + pub fn parse(json: &[u8]) -> Result { + let mut m: Manifest = serde_json::from_slice(json) + .map_err(|e| Error::Invalid(format!("bad manifest: {e}")))?; + if m.api != API_VERSION { + return Err(Error::Invalid(format!( + "module API {} is not supported (this app speaks {API_VERSION})", + m.api + ))); + } + if !synapse_core::is_valid_module_id(&m.id) { + return Err(Error::Invalid(format!("invalid module id {:?}", m.id))); + } + if m.name.trim().is_empty() || m.name.chars().count() > 64 { + return Err(Error::Invalid("module name must be 1-64 characters".into())); + } + if m.version.trim().is_empty() || m.version.len() > 32 { + return Err(Error::Invalid("invalid module version".into())); + } + if m.views.len() > 8 || m.macros.len() > 16 { + return Err(Error::Invalid("too many views or macros".into())); + } + for v in &m.views { + if !simple_name(&v.id) || v.title.trim().is_empty() || v.title.chars().count() > 64 { + return Err(Error::Invalid(format!("invalid view {:?}", v.id))); + } + if v.icon.as_ref().is_some_and(|i| i.chars().count() > 16) { + return Err(Error::Invalid(format!("invalid icon of view {:?}", v.id))); + } + } + if let Some(m) = m.macros.iter().find(|n| !simple_name(n)) { + return Err(Error::Invalid(format!("invalid macro name {m:?}"))); + } + if m.tick_seconds.is_some_and(|t| t < 5) { + return Err(Error::Invalid("tick_seconds must be at least 5".into())); + } + m.description + .truncate(m.description.floor_char_boundary(1000)); + m.author.truncate(m.author.floor_char_boundary(100)); + m.permissions.sort(); + m.permissions.dedup(); + Ok(m) + } + + /// Reads the manifest from the custom section of a WebAssembly binary, without compiling it. + pub fn from_wasm(wasm: &[u8]) -> Result { + let section = custom_section(wasm, MANIFEST_SECTION)? + .ok_or_else(|| Error::Invalid(format!("no {MANIFEST_SECTION} section")))?; + Self::parse(section) + } +} + +fn leb_u32(b: &[u8], pos: &mut usize) -> Result { + let mut out: u32 = 0; + for shift in (0..35).step_by(7) { + let byte = *b + .get(*pos) + .ok_or_else(|| Error::Invalid("truncated module".into()))?; + *pos += 1; + out |= u32::from(byte & 0x7f) << shift; + if byte & 0x80 == 0 { + return Ok(out); + } + } + Err(Error::Invalid("bad LEB128 in module".into())) +} + +/// The payload of the first custom section called `name`, if any. +fn custom_section<'a>(wasm: &'a [u8], name: &str) -> Result> { + if wasm.len() < 8 || &wasm[..4] != b"\0asm" { + return Err(Error::Invalid("not a WebAssembly module".into())); + } + let mut pos = 8; + while pos < wasm.len() { + let id = wasm[pos]; + pos += 1; + let size = leb_u32(wasm, &mut pos)? as usize; + let end = pos + .checked_add(size) + .filter(|&e| e <= wasm.len()) + .ok_or_else(|| Error::Invalid("truncated module".into()))?; + if id == 0 { + let mut p = pos; + let len = leb_u32(wasm, &mut p)? as usize; + let name_end = p + .checked_add(len) + .filter(|&e| e <= end) + .ok_or_else(|| Error::Invalid("bad custom section".into()))?; + if &wasm[p..name_end] == name.as_bytes() { + return Ok(Some(&wasm[name_end..end])); + } + } + pos = end; + } + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn wasm_with(section: &str, payload: &[u8]) -> Vec { + let mut w = b"\0asm\x01\0\0\0".to_vec(); + let mut body = vec![section.len() as u8]; + body.extend_from_slice(section.as_bytes()); + body.extend_from_slice(payload); + w.push(0); + w.push(body.len() as u8); // small payloads only + w.extend(body); + w + } + + #[test] + fn reads_the_manifest_section() { + let json = br#"{"api":1,"id":"x.y","name":"X","version":"1","permissions":["crypto","storage","crypto"]}"#; + let m = Manifest::from_wasm(&wasm_with(MANIFEST_SECTION, json)).unwrap(); + assert_eq!(m.id, "x.y"); + assert_eq!(m.permissions, vec![Permission::Storage, Permission::Crypto]); + } + + #[test] + fn refuses_bad_manifests() { + for json in [ + r#"{"api":2,"id":"x","name":"X","version":"1"}"#, + r#"{"api":1,"id":"X Y","name":"X","version":"1"}"#, + r#"{"api":1,"id":"x","name":"X","version":"1","permissions":["network"]}"#, + r#"{"api":1,"id":"x","name":"X","version":"1","macros":["Bad Name"]}"#, + r#"{"api":1,"id":"x","name":"X","version":"1","tick_seconds":1}"#, + ] { + assert!( + Manifest::from_wasm(&wasm_with(MANIFEST_SECTION, json.as_bytes())).is_err(), + "{json}" + ); + } + assert!(Manifest::from_wasm(&wasm_with("other", b"{}")).is_err()); + assert!(Manifest::from_wasm(b"nope").is_err()); + } +} diff --git a/crates/synapse-modules/src/registry.rs b/crates/synapse-modules/src/registry.rs new file mode 100644 index 0000000..4155bc8 --- /dev/null +++ b/crates/synapse-modules/src/registry.rs @@ -0,0 +1,266 @@ +//! Installed modules of a graph: `/modules/.wasm` plus `/modules/modules.json` +//! (enabled flag and granted permissions). Installation is local to each device; module data +//! (`module_data`) syncs with the graph. + +use crate::host::{self, Running}; +use crate::manifest::{Manifest, Permission}; +use crate::{Error, Result}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::{BTreeMap, HashMap}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use synapse_core::Graph; +use wasmi::{Engine, Module}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Entry { + enabled: bool, + granted: Vec, +} + +/// An installed module as the app sees it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ModuleInfo { + pub manifest: Manifest, + pub enabled: bool, + /// Size of the `.wasm` file in bytes. + pub size: u64, +} + +struct Loaded { + manifest: Manifest, + module: Module, + running: Option, +} + +pub struct Registry { + dir: PathBuf, + graph: Arc>, + engine: Engine, + /// Serialises installs and the state file. + state: Mutex>, + /// One lock per module so a slow module does not block the others. + loaded: Mutex>>>>, +} + +fn state_path(dir: &Path) -> PathBuf { + dir.join("modules.json") +} + +impl Registry { + /// Opens the registry of the graph directory `graph_dir` (creating `modules/` lazily). + pub fn open(graph_dir: &Path, graph: Arc>) -> Self { + let dir = graph_dir.join("modules"); + let state = std::fs::read(state_path(&dir)) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default(); + Self { + dir, + graph, + engine: host::engine(), + state: Mutex::new(state), + loaded: Mutex::new(HashMap::new()), + } + } + + fn wasm_path(&self, id: &str) -> PathBuf { + self.dir.join(format!("{id}.wasm")) + } + + fn save(&self, state: &BTreeMap) -> Result<()> { + std::fs::create_dir_all(&self.dir)?; + let tmp = self.dir.join("modules.json.tmp"); + std::fs::write(&tmp, serde_json::to_vec_pretty(state)?)?; + std::fs::rename(tmp, state_path(&self.dir))?; + Ok(()) + } + + fn lock_state(&self) -> std::sync::MutexGuard<'_, BTreeMap> { + self.state.lock().unwrap_or_else(|p| p.into_inner()) + } + + fn slot(&self, id: &str) -> Arc>> { + self.loaded + .lock() + .unwrap_or_else(|p| p.into_inner()) + .entry(id.to_string()) + .or_default() + .clone() + } + + /// Validates a module file without installing it: manifest and WebAssembly. + pub fn inspect(&self, wasm: &[u8]) -> Result { + let manifest = Manifest::from_wasm(wasm)?; + host::compile(&self.engine, wasm)?; + Ok(manifest) + } + + /// Installs or updates a module. `granted` must contain every permission the manifest + /// asks for (the user saw and accepted them). An update keeps the enabled flag. + pub fn install(&self, wasm: &[u8], granted: &[Permission]) -> Result { + let manifest = self.inspect(wasm)?; + if let Some(p) = manifest.permissions.iter().find(|p| !granted.contains(p)) { + return Err(Error::Denied(format!( + "permission {} was not granted", + p.as_str() + ))); + } + let mut state = self.lock_state(); + std::fs::create_dir_all(&self.dir)?; + let path = self.wasm_path(&manifest.id); + let tmp = path.with_extension("wasm.tmp"); + std::fs::write(&tmp, wasm)?; + std::fs::rename(&tmp, &path)?; + let enabled = state.get(&manifest.id).is_none_or(|e| e.enabled); + state.insert( + manifest.id.clone(), + Entry { + enabled, + granted: manifest.permissions.clone(), + }, + ); + self.save(&state)?; + // Drop a running older version. + *self + .slot(&manifest.id) + .lock() + .unwrap_or_else(|p| p.into_inner()) = None; + Ok(ModuleInfo { + manifest, + enabled, + size: wasm.len() as u64, + }) + } + + /// Installed modules, by name. A module whose file is missing or broken is skipped. + pub fn list(&self) -> Vec { + let state = self.lock_state().clone(); + let mut out: Vec = state + .into_iter() + .filter_map(|(id, e)| { + let bytes = std::fs::read(self.wasm_path(&id)).ok()?; + let manifest = Manifest::from_wasm(&bytes).ok()?; + (manifest.id == id).then_some(ModuleInfo { + manifest, + enabled: e.enabled, + size: bytes.len() as u64, + }) + }) + .collect(); + out.sort_by_key(|m| m.manifest.name.to_lowercase()); + out + } + + pub fn set_enabled(&self, id: &str, enabled: bool) -> Result<()> { + let mut state = self.lock_state(); + let e = state + .get_mut(id) + .ok_or_else(|| Error::NotFound(id.to_string()))?; + e.enabled = enabled; + self.save(&state)?; + if !enabled { + self.stop(id); + } + Ok(()) + } + + /// Removes the module file. Its synced data is deleted too only when `delete_data` (that + /// deletion syncs to every device). + pub fn uninstall(&self, id: &str, delete_data: bool) -> Result<()> { + let mut state = self.lock_state(); + if state.remove(id).is_none() { + return Err(Error::NotFound(id.to_string())); + } + self.save(&state)?; + self.stop(id); + let _ = std::fs::remove_file(self.wasm_path(id)); + if delete_data { + self.graph + .lock() + .unwrap_or_else(|p| p.into_inner()) + .clear_module_data(id)?; + } + Ok(()) + } + + /// Drops the running instance (its in-memory state, such as unlocked keys, is lost). + pub fn stop(&self, id: &str) { + if let Some(slot) = self + .loaded + .lock() + .unwrap_or_else(|p| p.into_inner()) + .get(id) + { + *slot.lock().unwrap_or_else(|p| p.into_inner()) = None; + } + } + + /// Drops every running instance. + pub fn stop_all(&self) { + let slots: Vec<_> = self + .loaded + .lock() + .unwrap_or_else(|p| p.into_inner()) + .values() + .cloned() + .collect(); + for s in slots { + *s.lock().unwrap_or_else(|p| p.into_inner()) = None; + } + } + + /// Sends a request to an enabled module, starting it if needed. If the module traps, its + /// instance is discarded and the error returned. + pub fn call(&self, id: &str, request: &Value) -> Result { + let entry = self + .lock_state() + .get(id) + .cloned() + .ok_or_else(|| Error::NotFound(id.to_string()))?; + if !entry.enabled { + return Err(Error::Invalid(format!("module {id} is disabled"))); + } + let slot = self.slot(id); + let mut guard = slot.lock().unwrap_or_else(|p| p.into_inner()); + if guard.is_none() { + let bytes = std::fs::read(self.wasm_path(id))?; + let manifest = Manifest::from_wasm(&bytes)?; + if manifest.id != id { + return Err(Error::Invalid("module file does not match its id".into())); + } + // Permissions are the ones granted at install time (a file swapped behind our back + // cannot gain more). + if manifest + .permissions + .iter() + .any(|p| !entry.granted.contains(p)) + { + return Err(Error::Denied( + "module asks for permissions not granted".into(), + )); + } + let module = host::compile(&self.engine, &bytes)?; + *guard = Some(Loaded { + manifest, + module, + running: None, + }); + } + let loaded = guard.as_mut().expect("loaded"); + if loaded.running.is_none() { + loaded.running = Some(Running::start( + &self.engine, + &loaded.module, + loaded.manifest.clone(), + self.graph.clone(), + )?); + } + let result = loaded.running.as_mut().expect("running").request(request); + if matches!(result, Err(Error::Module(_))) { + loaded.running = None; + } + result + } +} diff --git a/crates/synapse-modules/tests/modules.rs b/crates/synapse-modules/tests/modules.rs new file mode 100644 index 0000000..f5a6fc0 --- /dev/null +++ b/crates/synapse-modules/tests/modules.rs @@ -0,0 +1,473 @@ +use serde_json::{Value, json}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use synapse_core::Graph; +use synapse_modules::{Error, MANIFEST_SECTION, Permission, Registry}; + +const SECRETS: &str = "synapse.secrets"; + +fn secrets_wasm() -> Vec { + let p = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../app/assets/modules/synapse.secrets.wasm"); + std::fs::read(&p) + .unwrap_or_else(|e| panic!("{}: {e} (run scripts/build-modules.sh)", p.display())) +} + +fn setup() -> (tempfile::TempDir, Arc>, Registry) { + let dir = tempfile::tempdir().unwrap(); + let graph = Arc::new(Mutex::new(Graph::open(dir.path()).unwrap())); + let reg = Registry::open(dir.path(), graph.clone()); + (dir, graph, reg) +} + +fn all_perms() -> Vec { + vec![ + Permission::Storage, + Permission::Crypto, + Permission::Clipboard, + Permission::PagesRead, + Permission::PagesWrite, + ] +} + +/// A module from WAT, with a manifest section appended. +fn wat_module(wat: &str, manifest: Value) -> Vec { + let mut wasm = wat::parse_str(wat).unwrap(); + let json = serde_json::to_vec(&manifest).unwrap(); + let mut body = Vec::new(); + leb(&mut body, MANIFEST_SECTION.len()); + body.extend_from_slice(MANIFEST_SECTION.as_bytes()); + body.extend_from_slice(&json); + wasm.push(0); + leb(&mut wasm, body.len()); + wasm.extend(body); + wasm +} + +fn leb(out: &mut Vec, mut n: usize) { + loop { + let b = (n & 0x7f) as u8; + n >>= 7; + if n == 0 { + out.push(b); + return; + } + out.push(b | 0x80); + } +} + +fn texts(v: &Value, out: &mut String) { + match v { + Value::String(s) => { + out.push_str(s); + out.push('\n'); + } + Value::Array(a) => a.iter().for_each(|x| texts(x, out)), + Value::Object(o) => o.values().for_each(|x| texts(x, out)), + _ => {} + } +} + +fn ui_text(resp: &Value) -> String { + let mut s = String::new(); + texts(&resp["ui"], &mut s); + s +} + +fn event(reg: &Registry, action: &str, values: Value, arg: &str) -> Value { + let r = reg + .call( + SECRETS, + &json!({ "op": "event", "view": "vault", "action": action, "values": values, "arg": arg }), + ) + .unwrap(); + assert!(r.get("error").is_none(), "{action}: {r}"); + r +} + +#[test] +fn secrets_vault_end_to_end() { + let (_dir, graph, reg) = setup(); + let wasm = secrets_wasm(); + let m = reg.inspect(&wasm).unwrap(); + assert_eq!(m.id, SECRETS); + assert_eq!( + m.permissions, + vec![ + Permission::Storage, + Permission::Crypto, + Permission::Clipboard + ] + ); + // Installing needs every requested permission granted. + assert!(matches!( + reg.install(&wasm, &[Permission::Storage]), + Err(Error::Denied(_)) + )); + reg.install(&wasm, &m.permissions).unwrap(); + assert_eq!(reg.list().len(), 1); + + let r = reg + .call(SECRETS, &json!({ "op": "render", "view": "vault" })) + .unwrap(); + assert!(ui_text(&r).contains("Create vault"), "{r}"); + + let r = event( + ®, + "setup", + json!({ "password": "short", "confirm": "short" }), + "", + ); + assert!(ui_text(&r).contains("at least 8")); + let r = event( + ®, + "setup", + json!({ "password": "correct horse", "confirm": "correct horse" }), + "", + ); + assert!(ui_text(&r).contains("No secrets yet"), "{r}"); + + event(®, "new", json!({}), ""); + let r = event( + ®, + "save", + json!({ "name": "GitHub", "username": "dario", "password": "hunter2-XYZ", "url": "https://github.com", "notes": "" }), + "", + ); + assert!(ui_text(&r).contains("GitHub")); + assert!(!ui_text(&r).contains("hunter2-XYZ"), "masked by default"); + + // Stored data is ciphertext only. + { + let g = graph.lock().unwrap(); + let rows = g.module_data_list(SECRETS, "").unwrap(); + assert_eq!(rows.len(), 2, "{rows:?}"); + for (_, v) in &rows { + assert!(!v.contains("hunter2") && !v.contains("GitHub") && !v.contains("dario")); + } + } + + // Macro: masked, copy gives a clipboard effect. + let r = reg + .call( + SECRETS, + &json!({ "op": "macro", "name": "secret", "args": "github" }), + ) + .unwrap(); + assert_eq!(r["inline"]["text"], "GitHub"); + assert_ne!(r["inline"]["masked"], "hunter2-XYZ"); + let r = reg + .call( + SECRETS, + &json!({ "op": "macro_action", "name": "secret", "args": "GitHub", "action": "copy" }), + ) + .unwrap(); + assert_eq!(r["effects"][0]["copy"]["text"], "hunter2-XYZ"); + let r = reg + .call( + SECRETS, + &json!({ "op": "macro_action", "name": "secret", "args": "GitHub", "action": "reveal" }), + ) + .unwrap(); + assert_eq!(r["inline"]["masked"], "hunter2-XYZ"); + let r = reg + .call( + SECRETS, + &json!({ "op": "macro", "name": "secret", "args": "Nope" }), + ) + .unwrap(); + assert!(r["inline"]["error"].is_string()); + + // Lock: the macro no longer reveals anything. + event(®, "lock", json!({}), ""); + let r = reg + .call( + SECRETS, + &json!({ "op": "macro_action", "name": "secret", "args": "GitHub", "action": "copy" }), + ) + .unwrap(); + assert_eq!(r["effects"][0]["open_view"], "vault"); + assert!(!r.to_string().contains("hunter2")); + + let r = event(®, "unlock", json!({ "password": "wrong horse" }), ""); + assert!(ui_text(&r).contains("Wrong password")); + let r = event(®, "unlock", json!({ "password": "correct horse" }), ""); + assert!(ui_text(&r).contains("GitHub")); + + // Change the password: the old one stops working, entries survive. + event(®, "change_password", json!({}), ""); + event( + ®, + "save_password", + json!({ "current": "correct horse", "new": "battery staple", "confirm": "battery staple" }), + "", + ); + // A restart (or crash) drops the instance: locked again. + reg.stop(SECRETS); + let r = event(®, "unlock", json!({ "password": "correct horse" }), ""); + assert!(ui_text(&r).contains("Wrong password")); + let r = event(®, "unlock", json!({ "password": "battery staple" }), ""); + assert!(ui_text(&r).contains("GitHub")); + + // Suspend locks. + let r = reg.call(SECRETS, &json!({ "op": "suspend" })).unwrap(); + assert_eq!(r["changed"], true); + + // Uninstall keeps synced data unless asked. + reg.uninstall(SECRETS, false).unwrap(); + assert_eq!( + graph + .lock() + .unwrap() + .module_data_list(SECRETS, "") + .unwrap() + .len(), + 2 + ); + reg.install(&wasm, &m.permissions).unwrap(); + reg.uninstall(SECRETS, true).unwrap(); + assert!( + graph + .lock() + .unwrap() + .module_data_list(SECRETS, "") + .unwrap() + .is_empty() + ); +} + +#[test] +fn vault_data_syncs_as_ciphertext_and_unlocks_on_another_replica() { + let (_a_dir, a_graph, a) = setup(); + let (_b_dir, b_graph, b) = setup(); + let wasm = secrets_wasm(); + let perms = a.inspect(&wasm).unwrap().permissions; + a.install(&wasm, &perms).unwrap(); + b.install(&wasm, &perms).unwrap(); + event( + &a, + "setup", + json!({ "password": "correct horse", "confirm": "correct horse" }), + "", + ); + event(&a, "new", json!({}), ""); + event( + &a, + "save", + json!({ "name": "Bank", "password": "s3cret!" }), + "", + ); + let ops = a_graph.lock().unwrap().ops_since(0, 10_000).unwrap(); + { + let g = b_graph.lock().unwrap(); + for op in &ops { + if matches!(op.op, synapse_core::Op::PutModuleData { .. }) { + assert!(!serde_json::to_string(&op.op).unwrap().contains("s3cret")); + g.apply_remote(&op.hlc, &op.op).unwrap(); + } + } + } + let r = b + .call( + SECRETS, + &json!({ "op": "event", "action": "unlock", "values": { "password": "correct horse" } }), + ) + .unwrap(); + assert!(ui_text(&r).contains("Bank"), "{r}"); + let r = b + .call( + SECRETS, + &json!({ "op": "macro_action", "name": "secret", "args": "bank", "action": "copy" }), + ) + .unwrap(); + assert_eq!(r["effects"][0]["copy"]["text"], "s3cret!"); +} + +const ECHO: &str = r#" +(module + (import "synapse" "call" (func $call (param i32 i32) (result i32))) + (import "synapse" "take" (func $take (param i32))) + (import "synapse" "respond" (func $respond (param i32 i32))) + (memory (export "memory") 2) + (global $next (mut i32) (i32.const 1024)) + (func (export "syn_alloc") (param $n i32) (result i32) + (local $p i32) + global.get $next + local.set $p + global.get $next + local.get $n + i32.add + global.set $next + local.get $p) + ;; Forwards the request to the host as a host call and returns the host's reply. + (func (export "syn_handle") (param $p i32) (param $n i32) + (local $len i32) + local.get $p + local.get $n + call $call + local.set $len + i32.const 32768 + call $take + i32.const 32768 + local.get $len + call $respond)) +"#; + +fn manifest(id: &str, perms: &[&str]) -> Value { + json!({ "api": 1, "id": id, "name": id, "version": "1", "permissions": perms }) +} + +#[test] +fn host_functions_need_their_permission() { + let (_dir, graph, reg) = setup(); + let wasm = wat_module(ECHO, manifest("test.echo", &[])); + reg.install(&wasm, &[]).unwrap(); + let r = reg + .call( + "test.echo", + &json!({ "fn": "kv.set", "key": "k", "value": "v" }), + ) + .unwrap(); + assert!( + r["error"].as_str().unwrap().contains("permission denied"), + "{r}" + ); + let r = reg + .call("test.echo", &json!({ "fn": "crypto.generate" })) + .unwrap(); + assert!(r["error"].is_string()); + let r = reg + .call("test.echo", &json!({ "fn": "pages.get", "title": "x" })) + .unwrap(); + assert!(r["error"].is_string()); + let r = reg.call("test.echo", &json!({ "fn": "now" })).unwrap(); + assert!(r["ok"].as_u64().unwrap() > 0); + + let wasm = wat_module( + ECHO, + manifest("test.store", &["storage", "pages:write", "pages:read"]), + ); + reg.install(&wasm, &all_perms()).unwrap(); + let r = reg + .call( + "test.store", + &json!({ "fn": "kv.set", "key": "k", "value": "v" }), + ) + .unwrap(); + assert!(r.get("error").is_none(), "{r}"); + let r = reg + .call( + "test.store", + &json!({ "fn": "pages.append", "title": "Inbox", "text": "from a module" }), + ) + .unwrap(); + assert_eq!(r["ok"]["page"], "Inbox"); + let r = reg + .call( + "test.store", + &json!({ "fn": "pages.get", "title": "inbox" }), + ) + .unwrap(); + assert_eq!(r["ok"]["markdown"], "- from a module\n"); + let g = graph.lock().unwrap(); + // Each module only sees its own namespace. + assert_eq!( + g.module_data("test.store", "k").unwrap().as_deref(), + Some("v") + ); + assert_eq!(g.module_data("test.echo", "k").unwrap(), None); +} + +#[test] +fn copy_effects_need_the_clipboard_permission() { + let (_dir, _graph, reg) = setup(); + // Echo answers with the host reply; make the module answer an arbitrary JSON instead by + // sending a request the host rejects... simpler: a module that responds with its request. + let wat = r#" +(module + (import "synapse" "respond" (func $respond (param i32 i32))) + (memory (export "memory") 2) + (func (export "syn_alloc") (param i32) (result i32) i32.const 1024) + (func (export "syn_handle") (param $p i32) (param $n i32) + local.get $p + local.get $n + call $respond)) +"#; + let wasm = wat_module(wat, manifest("test.mirror", &[])); + reg.install(&wasm, &[]).unwrap(); + let req = json!({ "effects": [{ "copy": { "text": "x" } }, { "toast": "hi" }] }); + let r = reg.call("test.mirror", &req).unwrap(); + assert_eq!(r["effects"], json!([{ "toast": "hi" }])); +} + +#[test] +fn a_runaway_module_is_stopped_and_restarted() { + let (_dir, _graph, reg) = setup(); + let wat = r#" +(module + (memory (export "memory") 1) + (func (export "syn_alloc") (param i32) (result i32) i32.const 1024) + (func (export "syn_handle") (param i32 i32) + (loop $l br $l))) +"#; + let wasm = wat_module(wat, manifest("test.loop", &[])); + reg.install(&wasm, &[]).unwrap(); + assert!(matches!( + reg.call("test.loop", &json!({})), + Err(Error::Module(_)) + )); + // Still callable (a fresh instance), still stopped by the fuel limit. + assert!(matches!( + reg.call("test.loop", &json!({})), + Err(Error::Module(_)) + )); +} + +#[test] +fn memory_is_capped() { + let (_dir, _graph, reg) = setup(); + let wat = r#" +(module + (memory (export "memory") 1) + (func (export "syn_alloc") (param i32) (result i32) i32.const 1024) + (func (export "syn_handle") (param i32 i32) + ;; 2000 pages = 125 MiB, over the cap: memory.grow returns -1, then trap. + i32.const 2000 + memory.grow + i32.const -1 + i32.eq + if unreachable end)) +"#; + let wasm = wat_module(wat, manifest("test.mem", &[])); + reg.install(&wasm, &[]).unwrap(); + assert!(matches!( + reg.call("test.mem", &json!({})), + Err(Error::Module(_)) + )); +} + +#[test] +fn disabled_and_unknown_modules_refuse_calls() { + let (dir, graph, reg) = setup(); + let wasm = wat_module(ECHO, manifest("test.echo", &[])); + reg.install(&wasm, &[]).unwrap(); + reg.set_enabled("test.echo", false).unwrap(); + assert!(reg.call("test.echo", &json!({ "fn": "now" })).is_err()); + assert!(reg.call("nope", &json!({})).is_err()); + // State survives reopening. + let reg2 = Registry::open(dir.path(), graph); + assert!(!reg2.list()[0].enabled); +} + +#[test] +fn a_swapped_file_cannot_gain_permissions() { + let (dir, _graph, reg) = setup(); + reg.install(&wat_module(ECHO, manifest("test.echo", &[])), &[]) + .unwrap(); + let evil = wat_module(ECHO, manifest("test.echo", &["storage"])); + std::fs::write(dir.path().join("modules/test.echo.wasm"), evil).unwrap(); + assert!(matches!( + reg.call("test.echo", &json!({ "fn": "now" })), + Err(Error::Denied(_)) + )); +}