Plug-ins: grant generations come from the key store only

A revoke raised the kept generation past the one the grants file
carried. The file can be edited, so a file carrying the largest
generation made every revoke fail, and one just below it left the kept
generation at the limit, so later grants could not be kept. The
generation is now read from the key store only.

A raise went to the generation after the kept one, which is the
generation a signed write whose keep failed had used, so a copy of that
write put back after a revoke granted again. A raise now goes two past
the kept generation, and each signed write raises first and is written
at the generation after the raised one. Every signed write is at a
generation no file was signed at before. When the file can't be
written, the earlier generation is put back. When the generation can't
be raised without passing the largest 64-bit value, the change is
refused with a log record.
This commit is contained in:
dotCooCoo committed 2026-11-21 12:33:41 -08:00
1 parent 24c2d57b20
commit d73ffbc271
3 files changed
+258 -101

No files matched your search

+84 -64
View File
@@ -726,17 +726,18 @@ impl Session {
/// Record in the store what the user granted plug-in `id` (`None`: nothing), leaving the store's
/// other grants as they are; with none left, remove the file. Entries this version can't use
/// are written back as they were, except one for `id`. The file is written at the folder's next
/// generation with the MAC of its grants for this folder ([`grant_keys`]), making the key when
/// the key store holds none, and the key store then keeps that generation ([`put_grants`]); a
/// 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. 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
/// are written back as they were, except one for `id`. The generation is raised, and the file is
/// written at the generation after the raised one with the MAC of its grants for this folder
/// ([`grant_keys`]), making the key when the key store holds none; the key store then keeps that
/// generation ([`put_grants`]). A 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. 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. The generation is never read from the file; when it 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;
@@ -801,7 +802,7 @@ impl Session {
// 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);
retire_signed_copies(dir);
}
return false;
}
@@ -837,8 +838,9 @@ impl Session {
// 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);
// generation is past every one a file was signed at, so the file left in place grants
// nothing either.
return !removing || (file.present && file.trust == Trust::Signed) || retire_signed_copies(dir);
}
let mut entries: Vec<serde_json::Value> = file.grants.into_values().filter_map(|g| serde_json::to_value(g).ok()).collect();
entries.extend(file.other);
@@ -847,7 +849,7 @@ impl Session {
}
// An unsigned file loses an entry: the generation is raised first, so that no signed copy
// made before brings the entry back, nor the file itself when it can't be rewritten.
if raise_generation(dir, file.generation).is_none() {
if raise_generation(dir).is_none() {
return false;
}
if entries.is_empty() { take(dir, GRANTS_FILE) } else { put_grants(dir, entries, false) }
@@ -1515,8 +1517,6 @@ struct GrantsFile {
/// 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<u64>,
}
impl GrantsFile {
@@ -1607,39 +1607,59 @@ fn trust_of(dir: &Path, signed: &SignedGrants) -> Trust {
/// Write `entries` as the grants file of the plug-in store `dir`, pretty-printed, or compact when
/// that is larger than [`MAX_GRANTS_FILE`] → whether it went there; the file is not written when the
/// key or the generation can't be had or it is too large either way. When `signed`, the file is at
/// the next generation for `dir` with its MAC, and that generation is kept after the file is written;
/// when it can't be kept, the file is at a generation the key store doesn't hold, so it grants
/// nothing, and the write reports a failure. Call it in the store's turn ([`StoreTurn`]).
/// key or the generation can't be had or it is too large either way. When `signed`, the generation
/// is raised first ([`raise_generation`]), the file is written at the generation after the raised one
/// with its MAC, and the key store keeps that generation once the file is written. Every signed write
/// is then at a generation no file was signed at before, a write whose generation wasn't kept
/// included, since that one is at most one past the generation the key store kept. When the file
/// isn't written, the generation kept before is put back. When the file's generation can't be kept,
/// the file is at a generation the key store doesn't hold, so it grants nothing, and the write
/// reports a failure. Call it in the store's turn ([`StoreTurn`]).
fn put_grants(dir: &Path, entries: Vec<serde_json::Value>, signed: bool) -> bool {
let path = dir.join(GRANTS_FILE);
let folder = plugin_store_key(dir);
let (file, next) = if signed {
let signing = grant_keys::signing_key().and_then(|key| Ok((key, grant_keys::current_generation(&folder)?)));
let (key, generation) = match signing {
Ok(signing) => signing,
Err(e) => {
log::warn!("not updating the stored plug-in grants {}: {e}", path.display());
return false;
if !signed {
return match grants_bytes(serde_json::to_value(entries).ok()) {
Some(bytes) => put(dir, GRANTS_FILE, &bytes),
None => {
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
false
}
};
let Some(next) = generation.checked_add(1) else { return false };
let mac = serde_json::to_vec(&entries).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants));
let Some(mac) = mac else { return false };
(serde_json::to_value(SignedGrants { version: GRANTS_VERSION, generation: Some(next), grants: entries, mac: Some(mac) }), Some(next))
} else {
(serde_json::to_value(entries), None)
};
// The file is read back only up to its cap: written compactly when pretty-printed is larger,
// and not at all when that is too.
let fits = |bytes: &Vec<u8>| bytes.len() as u64 <= MAX_GRANTS_FILE;
match file.ok().and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits))) {
Some(bytes) => put(dir, GRANTS_FILE, &bytes) && next.is_none_or(|next| keep_generation(dir, &folder, next)),
None => {
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
false
}
}
let key = match grant_keys::signing_key() {
Ok(key) => key,
Err(e) => {
log::warn!("not updating the stored plug-in grants {}: {e}", path.display());
return false;
}
};
let Some((before, raised)) = raise_generation(dir) else { return false };
let Some(next) = raised.checked_add(1) else {
log::warn!("not updating the stored plug-in grants {}: the generation can't be raised", path.display());
keep_generation(dir, &folder, before);
return false;
};
let mac = serde_json::to_vec(&entries).ok().and_then(|grants| grant_keys::sign(&key, &folder, next, &grants));
let file = mac
.and_then(|mac| serde_json::to_value(SignedGrants { version: GRANTS_VERSION, generation: Some(next), grants: entries, mac: Some(mac) }).ok());
let Some(bytes) = grants_bytes(file) else {
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
keep_generation(dir, &folder, before);
return false;
};
if !put(dir, GRANTS_FILE, &bytes) {
keep_generation(dir, &folder, before);
return false;
}
keep_generation(dir, &folder, next)
}
/// `file` written as the bytes of a grants file: pretty-printed, or compact when that is larger than
/// [`MAX_GRANTS_FILE`]; `None` when that is too, since the file is read back only up to its cap.
fn grants_bytes(file: Option<serde_json::Value>) -> Option<Vec<u8>> {
let fits = |bytes: &Vec<u8>| bytes.len() as u64 <= MAX_GRANTS_FILE;
file.and_then(|file| serde_json::to_vec_pretty(&file).ok().filter(fits).or_else(|| serde_json::to_vec(&file).ok().filter(fits)))
}
/// Keep `generation` for the grants file of the plug-in store `dir` (whose folder is `folder`) →
@@ -1660,28 +1680,29 @@ 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, None) else { return false };
let Some((before, _)) = raise_generation(dir) else { return false };
if take(dir, GRANTS_FILE) {
return true;
}
keep_generation(dir, &plugin_store_key(dir), generation);
keep_generation(dir, &plugin_store_key(dir), before);
false
}
/// 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. `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<u64>) -> Option<u64> {
/// Keep a generation two past the one kept 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 and the one
/// kept now; `None`, with a log record, when the key store can't read or keep it or the generation
/// is too large to raise. A signed write whose generation wasn't kept is at the generation after the
/// kept one ([`put_grants`]), so the new generation is past it too. The generation comes from the key
/// store alone, never from a file, which anyone can edit.
fn raise_generation(dir: &Path) -> Option<(u64, u64)> {
let folder = plugin_store_key(dir);
let raised = grant_keys::current_generation(&folder).and_then(|generation| {
let next = generation.max(carried.unwrap_or(0)).checked_add(1);
let next = generation.checked_add(2);
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)
grant_keys::set_current_generation(&folder, next).map(|()| (generation, next))
});
match raised {
Ok(generation) => Some(generation),
Ok(generations) => Some(generations),
Err(e) => {
log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
None
@@ -1691,13 +1712,12 @@ fn raise_generation(dir: &Path, carried: Option<u64>) -> Option<u64> {
/// 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<u64>) -> bool {
/// and left as it is when it holds none, since no file is then signed. `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) -> bool {
match grant_keys::current_key() {
Ok(None) => true,
Ok(Some(_)) => raise_generation(dir, carried).is_some(),
Ok(Some(_)) => raise_generation(dir).is_some(),
Err(e) => {
log::warn!("not changing the stored plug-in grants {}: {e}", dir.join(GRANTS_FILE).display());
false
@@ -1730,12 +1750,12 @@ fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
return Err(GrantsError { unread: false, why: too_large(MAX_GRANTS_FILE) });
}
let not_a_list = |why: String| GrantsError { unread: false, why };
let (entries, trust, generation) = match serde_json::from_slice::<serde_json::Value>(&bytes).map_err(|e| not_a_list(e.to_string()))? {
serde_json::Value::Array(entries) => (entries, Trust::Unsigned, None),
let (entries, trust) = match serde_json::from_slice::<serde_json::Value>(&bytes).map_err(|e| not_a_list(e.to_string()))? {
serde_json::Value::Array(entries) => (entries, Trust::Unsigned),
serde_json::Value::Object(_) => {
let signed = serde_json::from_slice::<SignedGrants>(&bytes).map_err(|e| not_a_list(e.to_string()))?;
let trust = trust_of(dir, &signed);
(signed.grants, trust, signed.generation)
(signed.grants, trust)
}
_ => return Err(not_a_list("not a list of grants".into())),
};
@@ -1745,7 +1765,7 @@ fn read_grants(dir: &Path) -> Result<GrantsFile, GrantsError> {
path.display()
);
}
let mut file = GrantsFile { trust, present: true, generation, ..GrantsFile::default() };
let mut file = GrantsFile { trust, present: true, ..GrantsFile::default() };
let mut first_error = None;
for entry in entries {
let why = match serde_json::from_value::<vectorcraft_plugins::permissions::Grant>(entry.clone()) {
+162 -27
View File
@@ -4225,16 +4225,16 @@ impl crate::store::grant_keys::GrantKeyStore for UnreachableKeys {
}
}
/// A memory key store the test keeps a handle on; it fails to keep a generation while
/// `generation_writes_fail` is set.
/// A memory key store the test keeps a handle on. While `file_generations_fail` is set, it fails to
/// keep the generation that the grants file in the folder is at, and keeps every other one.
struct SharedKeys {
keys: std::sync::Arc<crate::store::grant_keys::MemoryGrantKeys>,
generation_writes_fail: std::sync::Arc<std::sync::atomic::AtomicBool>,
file_generations_fail: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
impl SharedKeys {
fn new(keys: &std::sync::Arc<crate::store::grant_keys::MemoryGrantKeys>) -> Self {
SharedKeys { keys: keys.clone(), generation_writes_fail: std::sync::Arc::default() }
SharedKeys { keys: keys.clone(), file_generations_fail: std::sync::Arc::default() }
}
}
@@ -4252,7 +4252,9 @@ impl crate::store::grant_keys::GrantKeyStore for SharedKeys {
}
fn set_generation(&self, folder: &std::path::Path, generation: u64) -> std::result::Result<(), crate::store::grant_keys::KeyStoreError> {
if self.generation_writes_fail.load(std::sync::atomic::Ordering::SeqCst) {
if self.file_generations_fail.load(std::sync::atomic::Ordering::SeqCst)
&& std::fs::read(folder.join("grants.json")).ok().and_then(|bytes| generation_of(&bytes)) == Some(generation)
{
return Err(crate::store::grant_keys::KeyStoreError("the key store can't keep it".into()));
}
crate::store::grant_keys::GrantKeyStore::set_generation(self.keys.as_ref(), folder, generation)
@@ -4582,9 +4584,9 @@ fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() {
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_eq!(kept(&folder.0), Some(3));
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!(kept(&folder.0), Some(3), "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.
@@ -4592,7 +4594,7 @@ fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() {
let mut s = session();
s.attach_plugin_store(folder.0.clone());
assert!(s.store_grant(id, None));
assert_eq!(kept(&folder.0), Some(2));
assert_eq!(kept(&folder.0), Some(5));
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");
@@ -4619,8 +4621,9 @@ fn a_grant_revoked_without_a_signed_file_doesnt_come_back_with_one() {
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.
/// Every signed write of the grants file raises the generation by two and is at the generation after
/// that, which the key store then keeps, and the file stays signed; removing the last grant raises
/// the generation too.
#[test]
fn a_signed_grants_write_raises_the_generation_and_stays_signed() {
let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
@@ -4635,20 +4638,20 @@ fn a_signed_grants_write_raises_the_generation_and_stays_signed() {
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(1), Some(1)));
assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(3), Some(3)));
assert_eq!(starts_from(&folder.0, id, &data), (true, false));
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]}));
assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(2), Some(2)));
assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(6), Some(6)));
run(&mut s, "plugin.remove", json!({"id": other}));
assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(3), Some(3)));
assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(9), Some(9)));
assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file stays signed");
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.remove", json!({"id": id}));
assert!(!grants.exists());
assert_eq!(kept(&folder.0), Some(4), "removing the file raises the generation");
assert_eq!(kept(&folder.0), Some(11), "removing the file raises the generation");
}
/// Each plug-in folder has a generation of its own.
@@ -4668,7 +4671,7 @@ fn two_plugin_folders_keep_their_own_generations() {
let mut b = session();
b.attach_plugin_store(second.0.clone());
run(&mut b, "plugin.install", json!({"dataBase64": data[2], "grant": ["doc.read"]}));
assert_eq!((kept(&first.0), kept(&second.0)), (Some(2), Some(1)));
assert_eq!((kept(&first.0), kept(&second.0)), (Some(6), Some(3)));
assert_eq!(starts_from(&first.0, ids[0], &data[0]), (true, false));
assert_eq!(starts_from(&second.0, ids[2], &data[2]), (true, false));
let (mut a, mut b) = (session(), session());
@@ -4680,7 +4683,7 @@ fn two_plugin_folders_keep_their_own_generations() {
}
/// A key store that holds a key and no generation for the folder, as one does the first time this
/// version runs, reads generation 0: a file signed at 0 keeps its grants, and the next write is at 1.
/// version runs, reads generation 0: a file signed at 0 keeps its grants, and the next write is at 3.
#[test]
fn a_key_without_a_generation_reads_generation_zero() {
use vectorcraft_plugins::permissions::sha256_hex;
@@ -4702,7 +4705,7 @@ fn a_key_without_a_generation_reads_generation_zero() {
s.attach_plugin_store(folder.0.clone());
let other_data = vectorcraft_format::base64_encode(&asking(other, r#"["doc.read"]"#, &json!({"objects": []})));
run(&mut s, "plugin.install", json!({"dataBase64": other_data, "grant": ["doc.read"]}));
assert_eq!(generation_of(&std::fs::read(&grants).unwrap()), Some(1));
assert_eq!(generation_of(&std::fs::read(&grants).unwrap()), Some(3));
assert_eq!(starts_from(&folder.0, id, &data), (true, false));
let mut s = session();
s.attach_plugin_store(folder.0.clone());
@@ -4728,20 +4731,19 @@ fn a_grant_revoked_while_a_generation_zero_file_is_gone_doesnt_come_back() {
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));
assert_eq!(kept_generation(&keys, &folder.0), Some(2));
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
/// leave it.
/// of the kept one and grants nothing, so its plug-ins ask again; so does the earlier file, since
/// the generation was raised past it before the write, and a file behind the kept generation.
#[test]
fn a_grants_file_whose_generation_was_not_kept_grants_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 fail = shared.file_generations_fail.clone();
let _keys = ThreadKeys::using(shared);
let folder = crate::tests_links::Folder::new("plugin-store-generation-unkept");
let store = crate::store::plugin_store_key(&folder.0);
@@ -4760,13 +4762,15 @@ fn a_grants_file_whose_generation_was_not_kept_grants_nothing() {
fail.store(false, std::sync::atomic::Ordering::SeqCst);
let ahead = std::fs::read(&grants).unwrap();
let kept = crate::store::grant_keys::GrantKeyStore::generation(keys.as_ref(), &store).unwrap();
assert_eq!((generation_of(&ahead), kept), (Some(2), Some(1)), "the file is one generation ahead");
assert_eq!((generation_of(&ahead), kept), (Some(6), Some(5)), "the file is one generation ahead");
assert_eq!(starts_from(&folder.0, id, &data), (false, true), "and grants nothing");
assert_eq!(starts_from(&folder.0, other, &other_data), (false, true));
std::fs::write(&grants, &written).unwrap();
assert_eq!(starts_from(&folder.0, id, &data), (false, true), "the earlier file grants nothing");
crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 3).unwrap();
assert_eq!(starts_from(&folder.0, id, &data), (true, false), "the file at the kept generation keeps its grant");
crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 2).unwrap();
crate::store::grant_keys::GrantKeyStore::set_generation(keys.as_ref(), &store, 4).unwrap();
assert_eq!(starts_from(&folder.0, id, &data), (false, true), "a file one generation behind grants nothing");
}
@@ -4776,7 +4780,7 @@ fn a_grants_file_whose_generation_was_not_kept_grants_nothing() {
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 fail = shared.file_generations_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");
@@ -4792,17 +4796,148 @@ fn a_revoke_over_a_file_ahead_of_its_generation_leaves_it_granting_nothing() {
_ = 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)));
assert_eq!((generation_of(&ahead), kept(&folder.0)), (Some(6), Some(5)));
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!(kept(&folder.0), Some(7), "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));
}
/// A signed write raises the generation before it writes the file, so a signed write whose generation
/// wasn't kept also leaves the earlier file granting nothing; a revoke over that earlier file put back
/// is then not at the generation of the unkept write, and a copy of that write put back after the
/// revoke grants nothing.
#[test]
fn a_revoke_after_a_write_whose_generation_wasnt_kept_keeps_that_write_granting_nothing() {
let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
let shared = SharedKeys::new(&keys);
let fail = shared.file_generations_fail.clone();
let _keys = ThreadKeys::using(shared);
let folder = crate::tests_links::Folder::new("plugin-store-revoke-after-unkept");
let ids = ["test.engine.permissions.afterunkept", "test.engine.permissions.afterunkeptother", "test.engine.permissions.afterunkeptthird"];
let data: Vec<String> = ids.iter().map(|id| vectorcraft_format::base64_encode(&asking(id, r#"["doc.read"]"#, &json!({"objects": []})))).collect();
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[0], "grant": ["doc.read"]}));
run(&mut s, "plugin.install", json!({"dataBase64": data[1], "grant": ["doc.read"]}));
let earlier = std::fs::read(&grants).unwrap();
fail.store(true, std::sync::atomic::Ordering::SeqCst);
_ = s.execute("plugin.install", &json!({"dataBase64": data[2], "grant": ["doc.read"]}));
fail.store(false, std::sync::atomic::Ordering::SeqCst);
let unkept = std::fs::read(&grants).unwrap();
std::fs::write(&grants, &earlier).unwrap();
assert_eq!(starts_from(&folder.0, ids[0], &data[0]), (false, true), "the earlier file grants nothing");
let mut s = session();
s.attach_plugin_store(folder.0.clone());
assert!(s.store_grant(ids[1], None));
std::fs::write(&grants, &unkept).unwrap();
assert_eq!(starts_from(&folder.0, ids[1], &data[1]), (false, true), "the revoked grant doesn't come back");
assert_eq!(starts_from(&folder.0, ids[2], &data[2]), (false, true), "the unkept write grants nothing");
std::fs::remove_file(&grants).unwrap();
let mut s = session();
s.attach_plugin_store(folder.0.clone());
for id in ids {
_ = s.execute("plugin.remove", &json!({"id": id}));
}
}
/// A grants file edited to carry the largest generations doesn't stop a revoke and doesn't move the
/// generation the key store keeps near the limit, so later grants are still kept: the generation
/// comes from the key store alone.
#[test]
fn a_grants_file_at_the_largest_generations_doesnt_stop_a_revoke() {
use vectorcraft_plugins::permissions::sha256_hex;
for carried in [u64::MAX, u64::MAX - 1] {
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(&format!("plugin-store-largest-generation-{}", u64::MAX - carried));
let id = "test.engine.permissions.largestgeneration";
let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let data = vectorcraft_format::base64_encode(&wasm);
let grants = folder.0.join("grants.json");
let edited = |entries: Value| json!({"version": 1, "generation": carried, "grants": entries, "mac": "0".repeat(64)}).to_string();
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
assert_eq!(kept(&folder.0), Some(3));
// The edited file names the grant, which the revoke takes out.
std::fs::write(&grants, edited(json!([{"id": id, "hash": sha256_hex(&wasm), "permissions": ["doc.read"]}]))).unwrap();
run(&mut s, "plugin.remove", json!({"id": id}));
assert!(!grants.exists(), "generation {carried}: the entry is taken out");
assert_eq!(kept(&folder.0), Some(5), "generation {carried}: the kept generation is raised from its own value");
// The edited file names no grant for it.
std::fs::write(&grants, edited(json!([]))).unwrap();
assert!(s.store_grant(id, None), "generation {carried}: the revoke is recorded");
assert_eq!(kept(&folder.0), Some(7), "generation {carried}: the kept generation is raised from its own value");
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
assert_eq!((generation_of(&std::fs::read(&grants).unwrap()), kept(&folder.0)), (Some(10), Some(10)), "generation {carried}");
assert_eq!(starts_from(&folder.0, id, &data), (true, false), "generation {carried}: a later grant is kept");
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.remove", json!({"id": id}));
}
}
/// A signed write whose generation wasn't kept leaves a file one generation past the kept one. A
/// revoke raises the generation past that file too, so a copy of it put back grants nothing: a revoke
/// from a file without a MAC, one while the file is gone, one over a file that doesn't hold a list,
/// and one that removes the last grant of a signed file.
#[test]
fn a_write_whose_generation_wasnt_kept_grants_nothing_after_a_revoke() {
use vectorcraft_plugins::permissions::sha256_hex;
for path in ["unsigned", "gone", "not-a-list", "signed"] {
let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
let shared = SharedKeys::new(&keys);
let fail = shared.file_generations_fail.clone();
let _keys = ThreadKeys::using(shared);
let kept = |dir: &std::path::Path| kept_generation(&keys, dir);
let folder = crate::tests_links::Folder::new(&format!("plugin-store-unkept-copy-{path}"));
let id = "test.engine.permissions.unkeptcopy";
let other = "test.engine.permissions.unkeptcopyother";
let wasm = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let other_wasm = asking(other, r#"["doc.read"]"#, &json!({"objects": []}));
let (data, other_data) = (vectorcraft_format::base64_encode(&wasm), vectorcraft_format::base64_encode(&other_wasm));
let grants = folder.0.join("grants.json");
let mut s = session();
s.attach_plugin_store(folder.0.clone());
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
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 unkept = std::fs::read(&grants).unwrap();
let before = kept(&folder.0).unwrap();
assert_eq!(generation_of(&unkept), Some(before + 1), "{path}: the file is one generation past the kept one");
let other_grant = json!([{"id": other, "hash": sha256_hex(&other_wasm), "permissions": ["doc.read"]}]).to_string();
match path {
"unsigned" => std::fs::write(&grants, &other_grant).unwrap(),
"gone" => std::fs::remove_file(&grants).unwrap(),
"not-a-list" => std::fs::write(&grants, br#""not a list""#).unwrap(),
_ => std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &other_grant)).unwrap(),
}
assert_eq!(s.store_grant(other, None), path != "not-a-list", "{path}");
std::fs::write(&grants, &unkept).unwrap();
assert_eq!(starts_from(&folder.0, other, &other_data), (false, true), "{path}: the revoked grant doesn't come back");
assert_eq!(starts_from(&folder.0, id, &data), (false, true), "{path}: the copy grants nothing");
assert_eq!(kept(&folder.0), Some(before + 2), "{path}: the generation is past the file whose generation wasn't kept");
std::fs::remove_file(&grants).unwrap();
let mut s = session();
s.attach_plugin_store(folder.0.clone());
_ = s.execute("plugin.remove", &json!({"id": id}));
_ = s.execute("plugin.remove", &json!({"id": other}));
}
}
/// 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]
+12 -10
View File
@@ -375,12 +375,15 @@ is made, and approvals last for the session only, as when the key store can't be
The key store also keeps a generation for each `Plug-ins` folder, as an 8-byte secret of the account `generation-v1-`
followed by the SHA-256 of the folder's resolved path in hexadecimal, in the same service. A key store that holds no
generation for a folder counts as generation 0. Each time VectorCraft writes a signed `grants.json`, in the folder's
turn (`disabled.lock`), it writes the file at the next generation and then keeps that generation. When it removes a
signed `grants.json`, it keeps the next generation first, and puts the earlier one back when the file can't be removed;
generation for a folder counts as generation 0. VectorCraft reads the generation from the key store only, never from
`grants.json`. Each time VectorCraft writes a signed `grants.json`, in the folder's turn (`disabled.lock`), it first
raises the kept generation by two, then writes the file at the generation after the raised one, and then keeps that
generation; when the file can't be written, it puts the earlier generation back. When it removes a signed
`grants.json`, it raises the generation by two first, and puts the earlier one back when the file can't be removed;
when the key store can't put it back either, the file grants nothing.
When the key store can't keep the generation of a write, the file just written grants nothing, and the write reports a
failure.
failure. That file is one generation past the kept one, so the next raise by two moves past it. When raising the
generation by two would pass the largest 64-bit value, VectorCraft logs a warning and changes nothing.
VectorCraft compares the MAC in constant time. A `grants.json` without the MAC of its generation, its grants and its
folder, or at another generation than the one the key store keeps for the folder, grants nothing, and each plug-in it
@@ -390,13 +393,12 @@ another `Plug-ins` folder or another computer, an earlier copy of the file put b
file was removed, a write whose generation the key store didn't keep, and a file whose key is no longer in the key
store. The next approval replaces such a file with a signed file that holds that grant alone, making a key first when
the key store has none. When a grant is forgotten without an approval (`plugin.remove`, installing a module that lists
no permissions under that id, or a folder load that forgets the grant), VectorCraft keeps the next generation, then
no permissions under that id, or a folder load that forgets the grant), VectorCraft raises the generation by two, then
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.
also raises the generation by two 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. A `generation` written into such a file has no effect on the raise. When the key
store can't raise the 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