feat(modules): sandboxed WebAssembly module host with permissions and host crypto

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 16:08:33 +01:00
1 parent 523f3b28fa
commit 5627ca7f84
8 files changed
+1937 -3

No files matched your search

+201
View File
@@ -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<Vec<u8>> {
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<Key> {
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<u32, Key>,
next: u32,
}
impl Keyring {
fn insert(&mut self, key: Key) -> Result<u32> {
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<u32> {
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<u32> {
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<Vec<u8>> {
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<Zeroizing<Vec<u8>>> {
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<Vec<u8>> {
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<u32> {
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());
}
}
+400
View File
@@ -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<Mutex<Graph>>,
keys: Keyring,
pending: Vec<u8>,
response: Option<Vec<u8>>,
limits: StoreLimits,
log: Vec<String>,
}
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> {
Module::new(engine, wasm).map_err(|e| Error::Invalid(format!("invalid WebAssembly: {e}")))
}
pub struct Running {
store: Store<HostState>,
memory: Memory,
alloc: TypedFunc<i32, i32>,
handle: TypedFunc<(i32, i32), ()>,
}
fn memory_of(caller: &Caller<'_, HostState>) -> Result<Memory, wasmi::Error> {
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<Vec<u8>, 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<Mutex<Graph>>,
) -> Result<Self> {
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::<HostState>::new(engine);
linker
.func_wrap(
"synapse",
"call",
|mut caller: Caller<'_, HostState>, ptr: i32, len: i32| -> Result<i32, wasmi::Error> {
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::<i32, i32>(&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<Value> {
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<String> {
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<u32> {
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<Vec<u8>> {
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<Value> {
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:?}"))),
}
}
+41
View File
@@ -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<T, E = Error> = std::result::Result<T, E>;
+224
View File
@@ -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<Self> {
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<String>,
}
#[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<Permission>,
#[serde(default)]
pub views: Vec<ViewDecl>,
/// Names of the `{{name args}}` block macros the module renders.
#[serde(default)]
pub macros: Vec<String>,
/// When set, the app sends a `tick` request this often (seconds, >= 5) while it runs.
#[serde(default)]
pub tick_seconds: Option<u32>,
}
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<Self> {
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<Self> {
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<u32> {
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<Option<&'a [u8]>> {
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<u8> {
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());
}
}
+266
View File
@@ -0,0 +1,266 @@
//! Installed modules of a graph: `<graph>/modules/<id>.wasm` plus `<graph>/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<Permission>,
}
/// 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<Running>,
}
pub struct Registry {
dir: PathBuf,
graph: Arc<Mutex<Graph>>,
engine: Engine,
/// Serialises installs and the state file.
state: Mutex<BTreeMap<String, Entry>>,
/// One lock per module so a slow module does not block the others.
loaded: Mutex<HashMap<String, Arc<Mutex<Option<Loaded>>>>>,
}
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<Mutex<Graph>>) -> 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<String, Entry>) -> 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<String, Entry>> {
self.state.lock().unwrap_or_else(|p| p.into_inner())
}
fn slot(&self, id: &str) -> Arc<Mutex<Option<Loaded>>> {
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<Manifest> {
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<ModuleInfo> {
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<ModuleInfo> {
let state = self.lock_state().clone();
let mut out: Vec<ModuleInfo> = 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<Value> {
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
}
}