fix(modules): meter host calls, cap tables, storage quotas, separate key wrapping from sealing, no lock-order deadlock, unique macro names

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 16:34:25 +01:00
1 parent 0faff9ae96
commit fcdfeb216a
6 files changed
+417 -18

No files matched your search

+10
View File
@@ -66,6 +66,16 @@ impl Graph {
Ok(rows) Ok(rows)
} }
/// Number of live entries of `module` and their total size (keys plus values, bytes).
pub fn module_data_usage(&self, module: &str) -> Result<(u64, u64)> {
Ok(self.row(
"SELECT count(*), coalesce(sum(length(CAST(key AS BLOB)) + length(CAST(value AS BLOB))), 0)
FROM module_data WHERE module=?1 AND value IS NOT NULL",
params![module],
|r| Ok((r.get::<_, i64>(0)? as u64, r.get::<_, i64>(1)? as u64)),
)?)
}
/// Sets (`Some`) or deletes (`None`) an entry, logged as [`Op::PutModuleData`]. Deleting an /// Sets (`Some`) or deletes (`None`) an entry, logged as [`Op::PutModuleData`]. Deleting an
/// unset key is a no-op. /// unset key is a no-op.
pub fn set_module_data(&self, module: &str, key: &str, value: Option<&str>) -> Result<()> { pub fn set_module_data(&self, module: &str, key: &str, value: Option<&str>) -> Result<()> {
+31 -3
View File
@@ -12,12 +12,20 @@ use zeroize::Zeroizing;
pub const KEY_LEN: usize = 32; pub const KEY_LEN: usize = 32;
pub const NONCE_LEN: usize = 24; pub const NONCE_LEN: usize = 24;
/// Upper bounds for Argon2id parameters a module may ask for (memory in KiB). /// 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_MEMORY_KIB: u32 = 128 * 1024;
pub const MAX_KDF_ITERATIONS: u32 = 10; pub const MAX_KDF_ITERATIONS: u32 = 10;
pub const MAX_KDF_LANES: u32 = 4; pub const MAX_KDF_LANES: u32 = 4;
/// Largest plaintext or ciphertext handled in one call. /// Largest plaintext or ciphertext handled in one call.
pub const MAX_CRYPTO_INPUT: usize = 1 << 20; pub const MAX_CRYPTO_INPUT: usize = 1 << 20;
const MAX_KEYS: usize = 64; const MAX_KEYS: usize = 64;
/// Associated data prefix reserved for key wrapping, so data sealed with [`Keyring::seal`]
/// can never be unwrapped as a key (importing a key the module knows) and a wrapped key can
/// never be opened as data (exporting it).
const WRAP_AAD: &[u8] = b"synapse.wrap\0";
fn wrap_aad(aad: &[u8]) -> Vec<u8> {
[WRAP_AAD, aad].concat()
}
type Key = Zeroizing<[u8; KEY_LEN]>; type Key = Zeroizing<[u8; KEY_LEN]>;
@@ -89,6 +97,13 @@ impl Keyring {
/// Encrypts with a fresh random nonce; returns `nonce || ciphertext`. /// Encrypts with a fresh random nonce; returns `nonce || ciphertext`.
pub fn seal(&self, key: u32, plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>> { pub fn seal(&self, key: u32, plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
if aad.starts_with(WRAP_AAD) {
return Err(Error::Invalid("reserved associated data".into()));
}
self.seal_raw(key, plaintext, aad)
}
fn seal_raw(&self, key: u32, plaintext: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
if plaintext.len() > MAX_CRYPTO_INPUT { if plaintext.len() > MAX_CRYPTO_INPUT {
return Err(Error::Invalid("plaintext too large".into())); return Err(Error::Invalid("plaintext too large".into()));
} }
@@ -111,6 +126,13 @@ impl Keyring {
/// Decrypts `nonce || ciphertext`; fails when the key, data or associated data is wrong. /// 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>>> { pub fn open(&self, key: u32, data: &[u8], aad: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
if aad.starts_with(WRAP_AAD) {
return Err(Error::Invalid("reserved associated data".into()));
}
self.open_raw(key, data, aad)
}
fn open_raw(&self, key: u32, data: &[u8], aad: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
if data.len() < NONCE_LEN || data.len() > MAX_CRYPTO_INPUT + NONCE_LEN + 16 { if data.len() < NONCE_LEN || data.len() > MAX_CRYPTO_INPUT + NONCE_LEN + 16 {
return Err(Error::Decrypt); return Err(Error::Decrypt);
} }
@@ -129,12 +151,12 @@ impl Keyring {
/// Encrypts key `target` with key `kek` (key wrapping). /// Encrypts key `target` with key `kek` (key wrapping).
pub fn wrap(&self, kek: u32, target: u32, aad: &[u8]) -> Result<Vec<u8>> { pub fn wrap(&self, kek: u32, target: u32, aad: &[u8]) -> Result<Vec<u8>> {
let t = self.get(target)?.clone(); let t = self.get(target)?.clone();
self.seal(kek, t.as_ref(), aad) self.seal_raw(kek, t.as_ref(), &wrap_aad(aad))
} }
/// Decrypts a wrapped key and returns a handle to it. /// Decrypts a wrapped key and returns a handle to it.
pub fn unwrap_key(&mut self, kek: u32, data: &[u8], aad: &[u8]) -> Result<u32> { pub fn unwrap_key(&mut self, kek: u32, data: &[u8], aad: &[u8]) -> Result<u32> {
let plain = self.open(kek, data, aad)?; let plain = self.open_raw(kek, data, &wrap_aad(aad))?;
let bytes: [u8; KEY_LEN] = plain.as_slice().try_into().map_err(|_| Error::Decrypt)?; let bytes: [u8; KEY_LEN] = plain.as_slice().try_into().map_err(|_| Error::Decrypt)?;
self.insert(Zeroizing::new(bytes)) self.insert(Zeroizing::new(bytes))
} }
@@ -185,6 +207,12 @@ mod tests {
// Fresh nonce each time. // Fresh nonce each time.
assert_ne!(ct, k.seal(dek, b"hunter2", b"entry/1").unwrap()); assert_ne!(ct, k.seal(dek, b"hunter2", b"entry/1").unwrap());
// Wrapped keys and sealed data cannot be confused.
assert!(k.open(same, &wrapped, b"vault").is_err());
let sealed_key = k.seal(kek, &[7u8; KEY_LEN], b"vault").unwrap();
assert!(k.unwrap_key(same, &sealed_key, b"vault").is_err());
assert!(k.seal(kek, b"x", b"synapse.wrap\0vault").is_err());
k.forget(dek2); k.forget(dek2);
assert!(k.open(dek2, &ct, b"entry/1").is_err()); assert!(k.open(dek2, &ct, b"entry/1").is_err());
} }
+83 -7
View File
@@ -32,6 +32,20 @@ pub const FUEL_PER_REQUEST: u64 = 1_000_000_000;
pub const MAX_MEMORY: usize = 64 << 20; pub const MAX_MEMORY: usize = 64 << 20;
/// Largest request, response or host-call payload. /// Largest request, response or host-call payload.
pub const MAX_MESSAGE: usize = 4 << 20; pub const MAX_MESSAGE: usize = 4 << 20;
/// Host calls are not free: each costs this much fuel plus [`FUEL_PER_BYTE`] per byte in and
/// out, so a loop of host calls runs out of fuel like any other loop.
pub const FUEL_PER_HOST_CALL: u64 = 200_000;
pub const FUEL_PER_BYTE: u64 = 20;
/// Hard caps per request, whatever the fuel: host calls, bytes written to storage and key
/// derivations (Argon2 is memory-hard and slow on purpose).
pub const MAX_HOST_CALLS: u32 = 5_000;
pub const MAX_WRITE_BYTES: usize = 16 << 20;
pub const MAX_DERIVES: u32 = 3;
/// Storage quota per module (all its live entries).
pub const MAX_STORAGE_BYTES: u64 = 64 << 20;
pub const MAX_STORAGE_ENTRIES: u64 = 50_000;
/// Table elements per instance (tables live outside linear memory).
pub const MAX_TABLE_ELEMENTS: usize = 10_000;
pub(crate) struct HostState { pub(crate) struct HostState {
manifest: Manifest, manifest: Manifest,
@@ -41,6 +55,10 @@ pub(crate) struct HostState {
response: Option<Vec<u8>>, response: Option<Vec<u8>>,
limits: StoreLimits, limits: StoreLimits,
log: Vec<String>, log: Vec<String>,
/// Usage in the current request (reset by [`Running::request`]).
calls: u32,
written: usize,
derives: u32,
} }
pub(crate) fn engine() -> Engine { pub(crate) fn engine() -> Engine {
@@ -68,6 +86,16 @@ fn memory_of(caller: &Caller<'_, HostState>) -> Result<Memory, wasmi::Error> {
.ok_or_else(|| wasmi::Error::new("module exports no memory")) .ok_or_else(|| wasmi::Error::new("module exports no memory"))
} }
/// Takes the cost of a host call (and its payload) out of the request's fuel.
fn charge(caller: &mut Caller<'_, HostState>, bytes: usize) -> Result<(), wasmi::Error> {
let cost = FUEL_PER_HOST_CALL + FUEL_PER_BYTE * bytes as u64;
let fuel = caller.get_fuel()?;
if fuel < cost {
return Err(wasmi::Error::new("out of fuel"));
}
caller.set_fuel(fuel - cost)
}
fn read_bytes(caller: &Caller<'_, HostState>, ptr: i32, len: i32) -> Result<Vec<u8>, wasmi::Error> { 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"))?; let len = usize::try_from(len).map_err(|_| wasmi::Error::new("negative length"))?;
if len > MAX_MESSAGE { if len > MAX_MESSAGE {
@@ -98,8 +126,13 @@ impl Running {
.instances(1) .instances(1)
.memories(1) .memories(1)
.tables(4) .tables(4)
.table_elements(MAX_TABLE_ELEMENTS)
.trap_on_grow_failure(true)
.build(), .build(),
log: Vec::new(), log: Vec::new(),
calls: 0,
written: 0,
derives: 0,
}; };
let mut store = Store::new(engine, state); let mut store = Store::new(engine, state);
store.limiter(|s| &mut s.limits); store.limiter(|s| &mut s.limits);
@@ -113,6 +146,12 @@ impl Running {
len: i32| len: i32|
-> Result<i32, wasmi::Error> { -> Result<i32, wasmi::Error> {
let req = read_bytes(&caller, ptr, len)?; let req = read_bytes(&caller, ptr, len)?;
let state = caller.data_mut();
state.calls += 1;
if state.calls > MAX_HOST_CALLS {
return Err(wasmi::Error::new("too many host calls in one request"));
}
charge(&mut caller, req.len())?;
let reply = match dispatch(caller.data_mut(), &req) { let reply = match dispatch(caller.data_mut(), &req) {
Ok(v) => json!({ "ok": v }), Ok(v) => json!({ "ok": v }),
Err(e) => json!({ "error": e.to_string() }), Err(e) => json!({ "error": e.to_string() }),
@@ -122,6 +161,7 @@ impl Running {
if bytes.len() > MAX_MESSAGE { if bytes.len() > MAX_MESSAGE {
return Err(wasmi::Error::new("host reply too large")); return Err(wasmi::Error::new("host reply too large"));
} }
charge(&mut caller, bytes.len())?;
let n = bytes.len() as i32; let n = bytes.len() as i32;
caller.data_mut().pending = bytes; caller.data_mut().pending = bytes;
Ok(n) Ok(n)
@@ -187,7 +227,12 @@ impl Running {
self.store self.store
.set_fuel(FUEL_PER_REQUEST) .set_fuel(FUEL_PER_REQUEST)
.map_err(|e| Error::Host(e.to_string()))?; .map_err(|e| Error::Host(e.to_string()))?;
self.store.data_mut().response = None; let state = self.store.data_mut();
state.response = None;
state.pending.clear();
state.calls = 0;
state.written = 0;
state.derives = 0;
let ptr = self let ptr = self
.alloc .alloc
.call(&mut self.store, bytes.len() as i32) .call(&mut self.store, bytes.len() as i32)
@@ -301,21 +346,52 @@ fn dispatch(state: &mut HostState, req: &[u8]) -> Result<Value> {
Some(Value::String(s)) => Some(s.as_str()), Some(Value::String(s)) => Some(s.as_str()),
Some(_) => return Err(Error::Invalid("value must be a string or null".into())), Some(_) => return Err(Error::Invalid("value must be a string or null".into())),
}; };
graph(state).set_module_data(&id, key, value)?; let size = key.len() + value.map_or(0, str::len);
if state.written + size > MAX_WRITE_BYTES {
return Err(Error::Invalid(
"too much data written in one request".into(),
));
}
state.written += size;
let g = graph(state);
if let Some(v) = value {
let (count, bytes) = g.module_data_usage(&id)?;
let old = g.module_data(&id, key)?;
let new_count = count + u64::from(old.is_none());
let new_bytes = bytes - old.map_or(0, |o| (key.len() + o.len()) as u64)
+ (key.len() + v.len()) as u64;
if new_count > MAX_STORAGE_ENTRIES || new_bytes > MAX_STORAGE_BYTES {
return Err(Error::Invalid("the module's storage quota is full".into()));
}
}
g.set_module_data(&id, key, value)?;
Ok(Value::Null) Ok(Value::Null)
} }
"kv.list" => { "kv.list" => {
need(state, Permission::Storage)?; need(state, Permission::Storage)?;
let prefix = args.get("prefix").and_then(Value::as_str).unwrap_or(""); let prefix = args.get("prefix").and_then(Value::as_str).unwrap_or("");
let rows = graph(state).module_data_list(&id, prefix)?; let rows = graph(state).module_data_list(&id, prefix)?;
Ok(Value::Array( let mut total = 0;
rows.into_iter() let mut out = Vec::with_capacity(rows.len());
.map(|(k, v)| json!({ "key": k, "value": v })) for (k, v) in rows {
.collect(), total += k.len() + v.len() + 32;
)) if total > MAX_MESSAGE - 1024 {
return Err(Error::Invalid(
"too much data to list at once; use a narrower prefix".into(),
));
}
out.push(json!({ "key": k, "value": v }));
}
Ok(Value::Array(out))
} }
"crypto.derive" => { "crypto.derive" => {
need(state, Permission::Crypto)?; need(state, Permission::Crypto)?;
state.derives += 1;
if state.derives > MAX_DERIVES {
return Err(Error::Invalid(
"too many key derivations in one request".into(),
));
}
let h = state.keys.derive( let h = state.keys.derive(
arg_str(&args, "password")?, arg_str(&args, "password")?,
&arg_b64(&args, "salt")?, &arg_b64(&args, "salt")?,
+5 -1
View File
@@ -11,7 +11,11 @@ mod host;
pub mod manifest; pub mod manifest;
mod registry; mod registry;
pub use host::{FUEL_PER_REQUEST, MAX_MEMORY, MAX_MESSAGE, Running}; pub use host::{
FUEL_PER_BYTE, FUEL_PER_HOST_CALL, FUEL_PER_REQUEST, MAX_DERIVES, MAX_HOST_CALLS, MAX_MEMORY,
MAX_MESSAGE, MAX_STORAGE_BYTES, MAX_STORAGE_ENTRIES, MAX_TABLE_ELEMENTS, MAX_WRITE_BYTES,
Running,
};
pub use manifest::{API_VERSION, MANIFEST_SECTION, Manifest, Permission, ViewDecl}; pub use manifest::{API_VERSION, MANIFEST_SECTION, Manifest, Permission, ViewDecl};
pub use registry::{ModuleInfo, Registry}; pub use registry::{ModuleInfo, Registry};
+48 -5
View File
@@ -108,6 +108,23 @@ impl Registry {
))); )));
} }
let mut state = self.lock_state(); let mut state = self.lock_state();
// A block macro belongs to one module: another installed module claiming the same
// name would silently receive (and could spoof) its blocks.
for other in self.list_locked(&state) {
if other.manifest.id == manifest.id {
continue;
}
if let Some(m) = manifest
.macros
.iter()
.find(|m| other.manifest.macros.contains(m))
{
return Err(Error::Invalid(format!(
"the macro {{{{{m}}}}} is already used by the module {}",
other.manifest.name
)));
}
}
std::fs::create_dir_all(&self.dir)?; std::fs::create_dir_all(&self.dir)?;
let path = self.wasm_path(&manifest.id); let path = self.wasm_path(&manifest.id);
let tmp = path.with_extension("wasm.tmp"); let tmp = path.with_extension("wasm.tmp");
@@ -122,6 +139,9 @@ impl Registry {
}, },
); );
self.save(&state)?; self.save(&state)?;
// Never wait for a module slot while holding the state lock: `call` takes them in
// the opposite order.
drop(state);
// Drop a running older version. // Drop a running older version.
*self *self
.slot(&manifest.id) .slot(&manifest.id)
@@ -137,12 +157,23 @@ impl Registry {
/// Installed modules, by name. A module whose file is missing or broken is skipped. /// Installed modules, by name. A module whose file is missing or broken is skipped.
pub fn list(&self) -> Vec<ModuleInfo> { pub fn list(&self) -> Vec<ModuleInfo> {
let state = self.lock_state().clone(); let state = self.lock_state().clone();
self.list_locked(&state)
}
/// Whether the graph already holds data for module `id` (synced from another device or
/// left by an earlier install): a module installed under that id can read it.
pub fn has_data(&self, id: &str) -> Result<bool> {
let g = self.graph.lock().unwrap_or_else(|p| p.into_inner());
Ok(g.module_data_usage(id)?.0 > 0)
}
fn list_locked(&self, state: &BTreeMap<String, Entry>) -> Vec<ModuleInfo> {
let mut out: Vec<ModuleInfo> = state let mut out: Vec<ModuleInfo> = state
.into_iter() .iter()
.filter_map(|(id, e)| { .filter_map(|(id, e)| {
let bytes = std::fs::read(self.wasm_path(&id)).ok()?; let bytes = std::fs::read(self.wasm_path(id)).ok()?;
let manifest = Manifest::from_wasm(&bytes).ok()?; let manifest = Manifest::from_wasm(&bytes).ok()?;
(manifest.id == id).then_some(ModuleInfo { (&manifest.id == id).then_some(ModuleInfo {
manifest, manifest,
enabled: e.enabled, enabled: e.enabled,
size: bytes.len() as u64, size: bytes.len() as u64,
@@ -160,6 +191,7 @@ impl Registry {
.ok_or_else(|| Error::NotFound(id.to_string()))?; .ok_or_else(|| Error::NotFound(id.to_string()))?;
e.enabled = enabled; e.enabled = enabled;
self.save(&state)?; self.save(&state)?;
drop(state);
if !enabled { if !enabled {
self.stop(id); self.stop(id);
} }
@@ -174,6 +206,7 @@ impl Registry {
return Err(Error::NotFound(id.to_string())); return Err(Error::NotFound(id.to_string()));
} }
self.save(&state)?; self.save(&state)?;
drop(state);
self.stop(id); self.stop(id);
let _ = std::fs::remove_file(self.wasm_path(id)); let _ = std::fs::remove_file(self.wasm_path(id));
if delete_data { if delete_data {
@@ -187,12 +220,14 @@ impl Registry {
/// Drops the running instance (its in-memory state, such as unlocked keys, is lost). /// Drops the running instance (its in-memory state, such as unlocked keys, is lost).
pub fn stop(&self, id: &str) { pub fn stop(&self, id: &str) {
if let Some(slot) = self // Release the map before waiting for a busy module, so other modules keep working.
let slot = self
.loaded .loaded
.lock() .lock()
.unwrap_or_else(|p| p.into_inner()) .unwrap_or_else(|p| p.into_inner())
.get(id) .get(id)
{ .cloned();
if let Some(slot) = slot {
*slot.lock().unwrap_or_else(|p| p.into_inner()) = None; *slot.lock().unwrap_or_else(|p| p.into_inner()) = None;
} }
} }
@@ -224,6 +259,14 @@ impl Registry {
} }
let slot = self.slot(id); let slot = self.slot(id);
let mut guard = slot.lock().unwrap_or_else(|p| p.into_inner()); let mut guard = slot.lock().unwrap_or_else(|p| p.into_inner());
// Disabled or removed while we waited for the slot: do not start it again.
let entry = match self.lock_state().get(id) {
Some(e) if e.enabled => e.clone(),
_ => {
*guard = None;
return Err(Error::Invalid(format!("module {id} is disabled")));
}
};
if guard.is_none() { if guard.is_none() {
let bytes = std::fs::read(self.wasm_path(id))?; let bytes = std::fs::read(self.wasm_path(id))?;
let manifest = Manifest::from_wasm(&bytes)?; let manifest = Manifest::from_wasm(&bytes)?;
+240 -2
View File
@@ -141,7 +141,7 @@ fn secrets_vault_end_to_end() {
{ {
let g = graph.lock().unwrap(); let g = graph.lock().unwrap();
let rows = g.module_data_list(SECRETS, "").unwrap(); let rows = g.module_data_list(SECRETS, "").unwrap();
assert_eq!(rows.len(), 2, "{rows:?}"); assert_eq!(rows.len(), 3, "pointer, header, entry: {rows:?}");
for (_, v) in &rows { for (_, v) in &rows {
assert!(!v.contains("hunter2") && !v.contains("GitHub") && !v.contains("dario")); assert!(!v.contains("hunter2") && !v.contains("GitHub") && !v.contains("dario"));
} }
@@ -222,7 +222,7 @@ fn secrets_vault_end_to_end() {
.module_data_list(SECRETS, "") .module_data_list(SECRETS, "")
.unwrap() .unwrap()
.len(), .len(),
2 3
); );
reg.install(&wasm, &m.permissions).unwrap(); reg.install(&wasm, &m.permissions).unwrap();
reg.uninstall(SECRETS, true).unwrap(); reg.uninstall(SECRETS, true).unwrap();
@@ -471,3 +471,241 @@ fn a_swapped_file_cannot_gain_permissions() {
Err(Error::Denied(_)) Err(Error::Denied(_))
)); ));
} }
fn ops_of(g: &Arc<Mutex<Graph>>) -> Vec<(String, synapse_core::Op)> {
g.lock()
.unwrap()
.ops_since(0, 100_000)
.unwrap()
.into_iter()
.filter(|r| matches!(r.op, synapse_core::Op::PutModuleData { .. }))
.map(|r| (r.hlc, r.op))
.collect()
}
fn sync(from: &Arc<Mutex<Graph>>, to: &Arc<Mutex<Graph>>) {
let ops = ops_of(from);
let g = to.lock().unwrap();
for (hlc, op) in &ops {
g.apply_remote(hlc, op).unwrap();
}
}
fn keys(g: &Arc<Mutex<Graph>>) -> Vec<String> {
g.lock()
.unwrap()
.module_data_list(SECRETS, "")
.unwrap()
.into_iter()
.map(|(k, _)| k)
.collect()
}
#[test]
fn two_vaults_set_up_before_syncing_merge_on_unlock() {
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();
for (reg, name) in [(&a, "From A"), (&b, "From B")] {
event(
reg,
"setup",
json!({ "password": "correct horse", "confirm": "correct horse" }),
"",
);
event(reg, "new", json!({}), "");
event(reg, "save", json!({ "name": name, "password": "pw" }), "");
}
sync(&a_graph, &b_graph);
sync(&b_graph, &a_graph);
// B's data key may have lost the pointer: writing with it is refused until unlocked again.
for reg in [&a, &b] {
reg.stop(SECRETS);
let r = event(reg, "unlock", json!({ "password": "correct horse" }), "");
let t = ui_text(&r);
assert!(t.contains("From A") && t.contains("From B"), "{t}");
}
// One header is left on each replica after syncing again.
sync(&a_graph, &b_graph);
sync(&b_graph, &a_graph);
for g in [&a_graph, &b_graph] {
let headers = keys(g)
.into_iter()
.filter(|k| k.starts_with("vault/"))
.count();
assert_eq!(headers, 1, "{:?}", keys(g));
}
}
#[test]
fn a_device_whose_key_was_replaced_must_unlock_again_before_writing() {
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" }),
"",
);
sync(&a_graph, &b_graph);
event(&b, "unlock", json!({ "password": "correct horse" }), "");
// A changes the password: the data key rotates.
event(&a, "change_password", json!({}), "");
event(
&a,
"save_password",
json!({ "current": "correct horse", "new": "battery staple", "confirm": "battery staple" }),
"",
);
sync(&a_graph, &b_graph);
// B still holds the old key; saving with it is refused and B locks.
event(&b, "new", json!({}), "");
let r = event(&b, "save", json!({ "name": "Late", "password": "x" }), "");
assert!(ui_text(&r).contains("changed on another device"), "{r}");
assert!(!keys(&b_graph).iter().any(|k| k.starts_with("entry/")));
let r = event(&b, "unlock", json!({ "password": "correct horse" }), "");
assert!(ui_text(&r).contains("Wrong password"));
let r = event(&b, "unlock", json!({ "password": "battery staple" }), "");
assert!(!ui_text(&r).contains("Wrong password"));
}
#[test]
fn changing_the_password_rotates_the_data_key() {
let (_dir, graph, reg) = setup();
let wasm = secrets_wasm();
reg.install(&wasm, &reg.inspect(&wasm).unwrap().permissions)
.unwrap();
event(
&reg,
"setup",
json!({ "password": "correct horse", "confirm": "correct horse" }),
"",
);
event(&reg, "new", json!({}), "");
event(
&reg,
"save",
json!({ "name": "Bank", "password": "s3cret" }),
"",
);
let before = keys(&graph);
let entry_before = graph
.lock()
.unwrap()
.module_data_list(SECRETS, "entry/")
.unwrap();
event(&reg, "change_password", json!({}), "");
event(
&reg,
"save_password",
json!({ "current": "correct horse", "new": "battery staple", "confirm": "battery staple" }),
"",
);
let after = keys(&graph);
let old_header = before.iter().find(|k| k.starts_with("vault/")).unwrap();
assert!(!after.contains(old_header), "old header deleted: {after:?}");
let entry_after = graph
.lock()
.unwrap()
.module_data_list(SECRETS, "entry/")
.unwrap();
assert_ne!(entry_before[0].1, entry_after[0].1, "entry re-sealed");
reg.stop(SECRETS);
let r = event(&reg, "unlock", json!({ "password": "battery staple" }), "");
assert!(ui_text(&r).contains("Bank"));
}
#[test]
fn synced_headers_with_weak_kdf_parameters_are_ignored() {
let (_dir, graph, reg) = setup();
let wasm = secrets_wasm();
reg.install(&wasm, &reg.inspect(&wasm).unwrap().permissions)
.unwrap();
let weak = json!({ "v": 1, "key_id": "aa", "kdf": { "memory_kib": 8, "iterations": 1, "lanes": 1 }, "salt": "c2FsdHNhbHRzYWx0", "key": "AAAA" });
graph
.lock()
.unwrap()
.set_module_data(SECRETS, "vault/aa", Some(&weak.to_string()))
.unwrap();
let r = reg
.call(SECRETS, &json!({ "op": "render", "view": "vault" }))
.unwrap();
assert!(ui_text(&r).contains("Create vault"), "{r}");
}
/// Calls `kv.set` in a loop with the request stored at offset 0 (a data segment).
fn flood_module() -> String {
let req = r#"{"fn":"kv.set","key":"k","value":"0123456789012345678901234567890123456789"}"#;
format!(
r#"
(module
(import "synapse" "call" (func $call (param i32 i32) (result i32)))
(memory (export "memory") 2)
(data (i32.const 0) "{}")
(func (export "syn_alloc") (param i32) (result i32) i32.const 4096)
(func (export "syn_handle") (param i32 i32)
(loop $l
i32.const 0
i32.const {}
call $call
drop
br $l)))
"#,
req.replace('"', "\\\""),
req.len()
)
}
#[test]
fn host_calls_are_metered() {
let (_dir, graph, reg) = setup();
let wasm = wat_module(&flood_module(), manifest("test.flood", &["storage"]));
reg.install(&wasm, &[Permission::Storage]).unwrap();
let t = std::time::Instant::now();
assert!(matches!(
reg.call("test.flood", &json!({})),
Err(Error::Module(_))
));
assert!(t.elapsed() < std::time::Duration::from_secs(20));
let writes = ops_of(&graph).len();
assert!(
writes <= synapse_modules::MAX_HOST_CALLS as usize,
"{writes}"
);
}
#[test]
fn tables_are_capped() {
let (_dir, _graph, reg) = setup();
let wat = r#"
(module
(table 50000000 funcref)
(memory (export "memory") 1)
(func (export "syn_alloc") (param i32) (result i32) i32.const 1024)
(func (export "syn_handle") (param i32 i32)))
"#;
let wasm = wat_module(wat, manifest("test.table", &[]));
reg.install(&wasm, &[]).unwrap();
assert!(reg.call("test.table", &json!({})).is_err());
}
#[test]
fn a_macro_name_belongs_to_one_module() {
let (_dir, _graph, reg) = setup();
let mut m = manifest("test.one", &[]);
m["macros"] = json!(["secret"]);
reg.install(&wat_module(ECHO, m), &[]).unwrap();
let mut m = manifest("test.two", &[]);
m["macros"] = json!(["secret"]);
assert!(matches!(
reg.install(&wat_module(ECHO, m), &[]),
Err(Error::Invalid(_))
));
}