diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 09c0b63204..d13af0a6ce 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -732,7 +732,11 @@ impl Session { /// signed file left empty is removed after raising the generation ([`take_signed_grants`]). A file /// VectorCraft didn't write for this folder ([`Trust::Unsigned`]) grants nothing: a grant /// replaces it with a file that holds that grant alone, and removing one raises the generation - /// ([`raise_generation`]), then takes out the entry for `id` and leaves the rest unsigned. When the key store can't be reached ([`Trust::Unknown`], or + /// ([`raise_generation`]), then takes out the entry for `id` and leaves the rest unsigned. Removing + /// a grant when there is no file, or when the file grants nothing (unsigned, too large or not a + /// list) and has no entry to take out, also raises the generation when the key store holds a key + /// ([`retire_signed_copies`]), so that a signed copy put back doesn't grant it again; when the + /// generation can't be raised, nothing is recorded. When the key store can't be reached ([`Trust::Unknown`], or /// a key can't be made or kept), the file is left as it is and nothing is recorded, and an entry /// for `id` stays. A grants file that is too large, can't /// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded; @@ -794,6 +798,11 @@ impl Session { Ok(file) => file, Err(e) => { log::warn!("not updating the stored plug-in grants {}: {}", dir.join(GRANTS_FILE).display(), e.why); + // A file that is too large or doesn't hold a list grants nothing and is left as it + // is, but a signed copy made before it must not grant `id` again once it is put back. + if grant.is_none() && !e.unread { + retire_signed_copies(dir, None); + } return false; } }; @@ -816,6 +825,7 @@ impl Session { (Trust::Unsigned | Trust::Signed, _) => {} } let signed = file.trust == Trust::Signed || grant.is_some(); + let removing = grant.is_none(); let others = file.other.len(); file.other.retain(|entry| entry.get("id").and_then(serde_json::Value::as_str) != Some(id)); let changed = match grant { @@ -823,7 +833,12 @@ impl Session { None => file.grants.remove(id).is_some(), } || file.other.len() != others; if !changed { - return true; + // Without a file, or with one that grants nothing, the last signed file may still be + // around as a copy at the kept generation: a removal raises the generation so that the + // copy doesn't grant `id` again once it is put back. A signed file that doesn't name `id` + // is the latest, so every copy that does is at an earlier generation already. The new + // generation is past the one the file carries, so the file left in place grants nothing. + return !removing || (file.present && file.trust == Trust::Signed) || retire_signed_copies(dir, file.generation); } let mut entries: Vec = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect(); entries.extend(file.other); @@ -831,8 +846,8 @@ impl Session { return if entries.is_empty() { take_signed_grants(dir) } else { put_grants(dir, entries, true) }; } // An unsigned file loses an entry: the generation is raised first, so that no signed copy - // made before brings the entry back. - if raise_generation(dir).is_none() { + // made before brings the entry back, nor the file itself when it can't be rewritten. + if raise_generation(dir, file.generation).is_none() { return false; } if entries.is_empty() { take(dir, GRANTS_FILE) } else { put_grants(dir, entries, false) } @@ -1497,6 +1512,11 @@ struct GrantsFile { other: Vec, /// Whether VectorCraft wrote the grants for this folder. trust: Trust, + /// Whether there is a grants file: `false` when there is none, and the file is then empty and + /// [`Trust::Signed`]. + present: bool, + /// The generation the file carries, as this version writes it ([`SignedGrants::generation`]). + generation: Option, } impl GrantsFile { @@ -1640,7 +1660,7 @@ fn keep_generation(dir: &Path, folder: &Path, generation: u64) -> bool { /// either, the file grants nothing. The file holds no grant but the one being removed. Nothing is /// removed when the generation can't be raised. Call it in the store's turn ([`StoreTurn`]). fn take_signed_grants(dir: &Path) -> bool { - let Some(generation) = raise_generation(dir) else { return false }; + let Some(generation) = raise_generation(dir, None) else { return false }; if take(dir, GRANTS_FILE) { return true; } @@ -1650,11 +1670,14 @@ fn take_signed_grants(dir: &Path) -> bool { /// Keep the next generation for the grants file of the plug-in store `dir`, so that no signed copy /// of the file made before grants anything → the generation kept before; `None`, with a log record, -/// when the key store can't read or keep it. -fn raise_generation(dir: &Path) -> Option { +/// when the key store can't read or keep it. `carried` is the generation the file in `dir` carries +/// when it grants nothing ([`GrantsFile::generation`]): the new generation is past it too, so that a +/// signed write whose generation wasn't kept doesn't start to grant when the file stays. +fn raise_generation(dir: &Path, carried: Option) -> Option { let folder = plugin_store_key(dir); let raised = grant_keys::current_generation(&folder).and_then(|generation| { - let next = generation.checked_add(1).ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?; + let next = generation.max(carried.unwrap_or(0)).checked_add(1); + let next = next.ok_or_else(|| grant_keys::KeyStoreError("the generation can't be raised".into()))?; grant_keys::set_current_generation(&folder, next).map(|()| generation) }); match raised { @@ -1666,6 +1689,22 @@ fn raise_generation(dir: &Path) -> Option { } } +/// Make sure no signed copy of an earlier grants file of the plug-in store `dir` grants anything → +/// whether none can: the generation is raised ([`raise_generation`]) when the key store holds a key, +/// and left as it is when it holds none, since no file is then signed. `carried` is as for +/// [`raise_generation`]. `false`, with a log record, when the key store can't read or keep it. Call +/// it in the store's turn ([`StoreTurn`]). +fn retire_signed_copies(dir: &Path, carried: Option) -> bool { + match grant_keys::current_key() { + Ok(None) => true, + Ok(Some(_)) => raise_generation(dir, carried).is_some(), + Err(e) => { + log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display()); + false + } + } +} + /// Why the grants file of a plug-in store gave no grants. struct GrantsError { /// Opening or reading the file failed, so what it holds is unknown. When `false`, the file is @@ -1691,12 +1730,12 @@ fn read_grants(dir: &Path) -> Result { return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) }); } let not_a_list = |why: String| GrantsError { unread: false, why }; - let (entries, trust) = match serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))? { - serde_json::Value::Array(entries) => (entries, Trust::Unsigned), + let (entries, trust, generation) = match serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))? { + serde_json::Value::Array(entries) => (entries, Trust::Unsigned, None), serde_json::Value::Object(_) => { let signed = serde_json::from_slice::(&bytes).map_err(|e| not_a_list(e.to_string()))?; let trust = trust_of(dir, &signed); - (signed.grants, trust) + (signed.grants, trust, signed.generation) } _ => return Err(not_a_list("not a list of grants".into())), }; @@ -1706,7 +1745,7 @@ fn read_grants(dir: &Path) -> Result { path.display() ); } - let mut file = GrantsFile { trust, ..GrantsFile::default() }; + let mut file = GrantsFile { trust, present: true, generation, ..GrantsFile::default() }; let mut first_error = None; for entry in entries { let why = match serde_json::from_value::(entry.clone()) { diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 2061465570..d6c0218072 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4561,6 +4561,64 @@ fn an_earlier_grants_file_put_back_grants_nothing() { assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked from the edited file doesn't come back"); } +/// A grant revoked while the grants file is gone, or while another file that grants nothing (one +/// without a MAC, or one that doesn't hold a list) is in its place, doesn't come back with the last +/// signed file put back: the revoke raises the generation. A revoke that a signed file without an +/// entry for the plug-in already covers, or one while the key store holds no key, leaves the +/// generation as it is. +#[test] +fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-revoke-without-file"); + let id = "test.engine.permissions.revokedgone"; + let other = "test.engine.permissions.revokedgoneother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(other, None), "nothing to revoke in an empty folder"); + assert_eq!(kept(&folder.0), None, "without a key nothing is signed, so no generation is kept"); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + assert_eq!(kept(&folder.0), Some(1)); + assert!(s.store_grant(other, None)); + assert_eq!(kept(&folder.0), Some(1), "the signed file names no grant for it, so nothing is raised"); + assert_eq!(starts_from(&folder.0, id, &data), (true, false)); + + // The file is gone when the grant is revoked. + std::fs::remove_file(&grants).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(id, None)); + assert_eq!(kept(&folder.0), Some(2)); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked while the file was gone doesn't come back"); + + // A file without a MAC that names no grant for it is in place. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + std::fs::write(&grants, b"[]").unwrap(); + assert!(s.store_grant(id, None)); + assert_eq!(std::fs::read(&grants).unwrap(), b"[]", "the unsigned file is left as it is"); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over an unsigned file doesn't come back"); + + // A file that doesn't hold a list is in place: the revoke isn't recorded, and still raises the + // generation. + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + let signed = std::fs::read(&grants).unwrap(); + std::fs::write(&grants, br#""not a list""#).unwrap(); + assert!(!s.store_grant(id, None)); + std::fs::write(&grants, &signed).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the grant revoked over a file without a list doesn't come back"); +} + /// Every signed write of the grants file is at the next generation, which the key store then keeps, /// and the file stays signed; removing the last grant raises the generation too. #[test] @@ -4652,6 +4710,29 @@ fn a_key_without_a_generation_reads_generation_zero() { run(&mut s, "plugin.remove", json!({"id": id})); } +/// A grant revoked while the file signed at generation 0 is gone doesn't come back with that file +/// put back: with a key kept, the revoke raises the generation from 0. +#[test] +fn a_grant_revoked_while_a_generation_zero_file_is_gone_doesnt_come_back() { + use vectorcraft_plugins::permissions::sha256_hex; + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([6; 32]))); + let _keys = ThreadKeys::using(SharedKeys::new(&keys)); + let folder = crate::tests_links::Folder::new("plugin-store-generation-zero-revoke"); + let id = "test.engine.permissions.generationzerorevoke"; + let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []})); + let data = vectorcraft_format::base64_encode(&wasm); + let grants = folder.0.join("grants.json"); + let file = crate::store::signed_grants_file(&folder.0, &json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]).to_string()); + assert_eq!(generation_of(&file), Some(0)); + std::fs::write(folder.0.join(format!("{}.wasm", crate::store::file_stem(id))), &wasm).unwrap(); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant(id, None)); + assert_eq!(kept_generation(&keys, &folder.0), Some(1)); + std::fs::write(&grants, &file).unwrap(); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file at generation 0 grants nothing"); +} + /// When the key store can't keep the generation of a write, the file written is one generation ahead /// of the kept one and grants nothing, so its plug-ins ask again; so does a file one generation /// behind the kept one, as a write that kept its generation and then failed to write the file would @@ -4689,6 +4770,39 @@ fn a_grants_file_whose_generation_was_not_kept_grants_nothing() { assert_eq!(starts_from(&folder.0, id, &data), (false, true), "a file one generation behind grants nothing"); } +/// A revoke over a signed file whose generation wasn't kept raises the generation past the file's, +/// so the file left in place still grants nothing. +#[test] +fn a_revoke_over_a_file_ahead_of_its_generation_leaves_it_granting_nothing() { + let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default()); + let shared = SharedKeys::new(&keys); + let fail = shared.generation_writes_fail.clone(); + let _keys = ThreadKeys::using(shared); + let kept = |dir: &std::path::Path| kept_generation(&keys, dir); + let folder = crate::tests_links::Folder::new("plugin-store-revoke-ahead"); + let id = "test.engine.permissions.revokeahead"; + let other = "test.engine.permissions.revokeaheadother"; + let data = vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []}))); + let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []}))); + let grants = folder.0.join("grants.json"); + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]})); + fail.store(true, std::sync::atomic::Ordering::SeqCst); + _ = s.execute("plugin.install", &json!({"dataBase64": other_data, "grant": ["doc.read"]})); + fail.store(false, std::sync::atomic::Ordering::SeqCst); + let ahead = std::fs::read(&grants).unwrap(); + assert_eq!((generation_of(&ahead), kept(&folder.0)), (Some(2), Some(1))); + + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + assert!(s.store_grant("test.engine.permissions.revokeaheadnone", None)); + assert_eq!(std::fs::read(&grants).unwrap(), ahead, "the file is left as it is"); + assert_eq!(kept(&folder.0), Some(3), "the generation is past the file's"); + assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the file still grants nothing"); + assert_eq!(starts_from(&folder.0, other, &other_data), (false, true)); +} + /// The user agreed once: a heavy filter kept in the plug-in store is installed again at the next /// start without asking, with its budget. #[test] diff --git a/docs/plugins.md b/docs/plugins.md index 972590bb2a..1af038597e 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -391,7 +391,12 @@ file was removed, a write whose generation the key store didn't keep, and a file store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when the key store has none. When a grant is forgotten without an approval (`plugin.remove`, installing a module that lists no permissions under that id, or a folder load that forgets the grant), VectorCraft keeps the next generation, then -takes that entry out of such a file and leaves the rest unsigned, so no earlier signed copy brings the entry back. +takes that entry out of such a file and leaves the rest unsigned, so no earlier signed copy brings the entry back. It +also keeps the next generation when a grant is forgotten while there is no `grants.json`, or while the file in its place +grants nothing (no valid MAC, too large, or neither a grants object nor a JSON list) and has no entry to take out, +whenever the key store holds a key. Each time it keeps the next generation for a file that grants nothing and +stays in place, the new generation is also past the one that file carries. When the key store can't keep that +generation, VectorCraft logs a warning. When the key store can't be reached (it is locked, or a headless Linux session has no Secret Service), no `grants.json` grants anything and VectorCraft writes none: an approval lasts for the session only, the module stored