mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 05:52:09 +00:00
Plug-ins: a failed removal keeps settings, and the key store reconnects
- plugin.remove deletes the stored module of a plug-in that isn't installed while its settings and cache are still moved aside, so a module that can't be deleted leaves them in place for the next try. - plugin.remove of an invalid id no longer raises the grants generation. - The size check before a signed grants write uses the generation the file is written at, so a file that fits the 1 MiB limit is kept. - The system key store connection is dropped when the key store can't be reached through it or fails, and the next call connects again; a missing entry keeps the connection.
This commit is contained in:
@@ -1218,19 +1218,36 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let installed = registry::get(id).is_some();
|
||||
// Settings and cache the store keeps for an id that isn't installed are deleted too.
|
||||
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
|
||||
// A module stored for an id that isn't installed (one no grant covers is skipped at startup)
|
||||
// counts as removed once its file is gone.
|
||||
let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id);
|
||||
let module_left = std::cell::Cell::new(false);
|
||||
let cant_delete = || format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default());
|
||||
// Installed again, it asks again. A grant that can't be removed may still approve the module, and
|
||||
// so may a grants file that can't be opened or read, or a signed copy of the file put back when
|
||||
// the generation couldn't be raised (the key store can't be reached). Without a plug-in folder
|
||||
// nothing keeps a grant.
|
||||
let forget = || s.store_grant_in(&turn, id, None) || s.plugin_dir.is_none();
|
||||
// Its settings and cache are moved aside and its grant removed before anything is deleted: when
|
||||
// either can't be done, the plug-in stays installed, as it was, and a second `plugin.remove`
|
||||
// tries again.
|
||||
// nothing keeps a grant. The stored module of an id that isn't installed is deleted next, while
|
||||
// its settings and cache can still be moved back.
|
||||
let forget = || {
|
||||
if !s.store_grant_in(&turn, id, None) && s.plugin_dir.is_some() {
|
||||
return false;
|
||||
}
|
||||
let deleted = !module || s.unstore_plugin(&turn, id);
|
||||
module_left.set(!deleted);
|
||||
deleted
|
||||
};
|
||||
// Its settings and cache are moved aside, its grant removed and its stored module deleted before
|
||||
// anything else is deleted: when one of them can't be done, the settings and cache are moved back,
|
||||
// the plug-in stays installed, as it was, and a second `plugin.remove` tries again. An invalid id
|
||||
// names no grant and no module.
|
||||
let failed = if installed || stored {
|
||||
s.remove_plugin_storage(&turn, id, forget).err().map(|e| e.to_string())
|
||||
} else {
|
||||
} else if vectorcraft_plugins::manifest::valid_id(id) {
|
||||
(!forget()).then(|| crate::store::GRANT_NOT_REMOVED.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let failed = failed.map(|e| if module_left.get() && e == crate::store::GRANT_NOT_REMOVED { cant_delete() } else { e });
|
||||
if let Some(e) = failed {
|
||||
if installed {
|
||||
s.attach_plugin_storage(&turn, id);
|
||||
@@ -1238,11 +1255,8 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other(e));
|
||||
}
|
||||
registry::revoke(id);
|
||||
// A module stored for an id that isn't installed (one no grant covers is skipped at startup)
|
||||
// counts as removed once its file is gone.
|
||||
let module = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.holds_stored_plugin(id);
|
||||
if !s.unstore_plugin(&turn, id) && module {
|
||||
return Err(EngineError::Other(format!("plugin.remove: can't delete {}", s.stored_plugin_file(id).unwrap_or_default())));
|
||||
return Err(EngineError::Other(cant_delete()));
|
||||
}
|
||||
if !stored && !module && (!installed || !registry::remove(id)) {
|
||||
return Err(err(vectorcraft_plugins::Error::NotFound(id.into())));
|
||||
|
||||
@@ -1652,10 +1652,13 @@ fn put_grants(dir: &Path, entries: Vec<serde_json::Value>, signed: bool) -> bool
|
||||
return false;
|
||||
}
|
||||
};
|
||||
// A file too large to keep is found before the raise, at the longest generation and a MAC of its
|
||||
// length, so the file in place keeps its grants when nothing can be written.
|
||||
// A file too large to keep is found before the raise, at the generation it would be written at
|
||||
// (three past the kept one, [`raise_generation`]) and a MAC of its length, so the file in place
|
||||
// keeps its grants when nothing can be written. When the kept generation can't be read, the raise
|
||||
// fails too.
|
||||
let expected = grant_keys::current_generation(&folder).ok().and_then(|kept| kept.checked_add(3)).unwrap_or(u64::MAX);
|
||||
let mut file =
|
||||
SignedGrants { version: GRANTS_VERSION, generation: Some(u64::MAX), grants: entries, mac: Some("0".repeat(2 * grant_keys::KEY_LEN)) };
|
||||
SignedGrants { version: GRANTS_VERSION, generation: Some(expected), grants: entries, mac: Some("0".repeat(2 * grant_keys::KEY_LEN)) };
|
||||
if grants_bytes(serde_json::to_value(&file).ok()).is_none() {
|
||||
log::warn!("not updating the stored plug-in grants {}: {}", path.display(), too_large(MAX_GRANTS_FILE));
|
||||
return false;
|
||||
|
||||
@@ -269,7 +269,9 @@ struct OsGrantKeys {
|
||||
/// same time keep one.
|
||||
making: Mutex<()>,
|
||||
/// The connection to the system's key store, once one is made. A failed connection is not
|
||||
/// kept: the next call tries again, so a key store that starts after VectorCraft is used.
|
||||
/// kept, and a kept one is dropped when the key store can't be reached through it or fails
|
||||
/// ([`OsGrantKeys::failed`]): the next call connects again, so a key store that starts after
|
||||
/// VectorCraft, or restarts, is used.
|
||||
store: Mutex<Option<Arc<keyring_core::CredentialStore>>>,
|
||||
/// How a connection is made ([`connect`]).
|
||||
connect: fn() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error>,
|
||||
@@ -296,8 +298,18 @@ impl OsGrantKeys {
|
||||
Ok(store.insert((self.connect)().map_err(store_error)?).clone())
|
||||
}
|
||||
|
||||
/// What the key store error `e` says ([`store_error`]). When the key store can't be reached or
|
||||
/// fails, the connection is dropped first, so the next call makes a new one: the Secret Service
|
||||
/// loses the session of a connection when it restarts. An entry that isn't there keeps it.
|
||||
fn failed(&self, e: keyring_core::Error) -> KeyStoreError {
|
||||
if matches!(e, keyring_core::Error::NoStorageAccess(_) | keyring_core::Error::PlatformFailure(_)) {
|
||||
*self.store.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||
}
|
||||
store_error(e)
|
||||
}
|
||||
|
||||
fn entry(&self, account: &str) -> Result<keyring_core::Entry, KeyStoreError> {
|
||||
self.store()?.build(Self::SERVICE, account, None).map_err(store_error)
|
||||
self.store()?.build(Self::SERVICE, account, None).map_err(|e| self.failed(e))
|
||||
}
|
||||
|
||||
fn key_entry(&self) -> Result<keyring_core::Entry, KeyStoreError> {
|
||||
@@ -305,7 +317,7 @@ impl OsGrantKeys {
|
||||
}
|
||||
|
||||
/// The key the system's key store keeps, read from it.
|
||||
fn stored(entry: &keyring_core::Entry) -> Result<Option<GrantKey>, KeyStoreError> {
|
||||
fn stored(&self, entry: &keyring_core::Entry) -> Result<Option<GrantKey>, KeyStoreError> {
|
||||
match entry.get_secret() {
|
||||
// A secret that is not 64 hexadecimal digits is not a key this version made: there is none.
|
||||
Ok(secret) => Ok(std::str::from_utf8(&secret)
|
||||
@@ -314,7 +326,7 @@ impl OsGrantKeys {
|
||||
.and_then(|bytes| <[u8; KEY_LEN]>::try_from(bytes.as_slice()).ok())
|
||||
.map(GrantKey)),
|
||||
Err(keyring_core::Error::NoEntry) => Ok(None),
|
||||
Err(e) => Err(store_error(e)),
|
||||
Err(e) => Err(self.failed(e)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,12 +373,12 @@ fn to_hex(bytes: &[u8]) -> String {
|
||||
impl GrantKeyStore for OsGrantKeys {
|
||||
/// Read from the key store each time, so that a key removed or replaced there is not used.
|
||||
fn key(&self) -> Result<Option<GrantKey>, KeyStoreError> {
|
||||
Self::stored(&self.key_entry()?)
|
||||
self.stored(&self.key_entry()?)
|
||||
}
|
||||
|
||||
fn set_key(&self, key: &GrantKey) -> Result<(), KeyStoreError> {
|
||||
let _making = self.making.lock().unwrap_or_else(|e| e.into_inner());
|
||||
self.key_entry()?.set_secret(to_hex(&key.0).as_bytes()).map_err(store_error)
|
||||
self.key_entry()?.set_secret(to_hex(&key.0).as_bytes()).map_err(|e| self.failed(e))
|
||||
}
|
||||
|
||||
/// Reads the key store again and makes the key only while holding [`creation_lock`], so that
|
||||
@@ -374,15 +386,15 @@ impl GrantKeyStore for OsGrantKeys {
|
||||
fn create_key(&self) -> Result<GrantKey, KeyStoreError> {
|
||||
let _making = self.making.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let entry = self.key_entry()?;
|
||||
if let Some(key) = Self::stored(&entry)? {
|
||||
if let Some(key) = self.stored(&entry)? {
|
||||
return Ok(key);
|
||||
}
|
||||
let _turn = creation_lock()?;
|
||||
match Self::stored(&entry)? {
|
||||
match self.stored(&entry)? {
|
||||
Some(key) => Ok(key),
|
||||
None => {
|
||||
entry.set_secret(to_hex(&GrantKey::random()?.0).as_bytes()).map_err(store_error)?;
|
||||
Self::stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into()))
|
||||
entry.set_secret(to_hex(&GrantKey::random()?.0).as_bytes()).map_err(|e| self.failed(e))?;
|
||||
self.stored(&entry)?.ok_or_else(|| KeyStoreError("the key store didn't keep the key".into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -399,12 +411,12 @@ impl GrantKeyStore for OsGrantKeys {
|
||||
.map(|bytes| Some(u64::from_be_bytes(bytes)))
|
||||
.ok_or_else(|| KeyStoreError("the key store holds a generation that is not 16 hexadecimal digits".into())),
|
||||
Err(keyring_core::Error::NoEntry) => Ok(None),
|
||||
Err(e) => Err(store_error(e)),
|
||||
Err(e) => Err(self.failed(e)),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_generation(&self, folder: &Path, generation: u64) -> Result<(), KeyStoreError> {
|
||||
self.generation_entry(folder)?.set_secret(to_hex(&generation.to_be_bytes()).as_bytes()).map_err(store_error)
|
||||
self.generation_entry(folder)?.set_secret(to_hex(&generation.to_be_bytes()).as_bytes()).map_err(|e| self.failed(e))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,6 +477,37 @@ mod tests {
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
/// Connections asked for from [`restarting`].
|
||||
static RESTARTS: AtomicUsize = AtomicUsize::new(0);
|
||||
/// The store [`restarting`] connects to first.
|
||||
static BEFORE: LazyLock<Arc<keyring_core::mock::Store>> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
|
||||
/// The store [`restarting`] connects to on every later try.
|
||||
static AFTER: LazyLock<Arc<keyring_core::mock::Store>> = LazyLock::new(|| keyring_core::mock::Store::new().unwrap());
|
||||
|
||||
/// A key store that restarts after the first connection: later connections reach another store.
|
||||
fn restarting() -> Result<Arc<keyring_core::CredentialStore>, keyring_core::Error> {
|
||||
let store: Arc<keyring_core::CredentialStore> = if RESTARTS.fetch_add(1, Ordering::SeqCst) == 0 { BEFORE.clone() } else { AFTER.clone() };
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
/// A connection that the key store can't be reached through is dropped, and the next call
|
||||
/// connects again; an entry that isn't there keeps the connection.
|
||||
#[test]
|
||||
fn the_system_key_store_reconnects_after_it_restarts() {
|
||||
let keys = OsGrantKeys { connect: restarting, ..OsGrantKeys::default() };
|
||||
assert_eq!(keys.key().unwrap(), None, "no key is kept yet");
|
||||
keys.set_key(&GrantKey::from_bytes([0xc1; KEY_LEN])).unwrap();
|
||||
assert_eq!(RESTARTS.load(Ordering::SeqCst), 1, "an entry that isn't there keeps the connection");
|
||||
|
||||
AFTER.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap().set_secret("d2".repeat(KEY_LEN).as_bytes()).unwrap();
|
||||
let entry = BEFORE.build(OsGrantKeys::SERVICE, OsGrantKeys::ACCOUNT, None).unwrap();
|
||||
let cred: &keyring_core::mock::Cred = entry.as_any().downcast_ref().unwrap();
|
||||
cred.set_error(keyring_core::Error::NoStorageAccess("the session is gone".into()));
|
||||
assert!(keys.key().is_err(), "the connection fails");
|
||||
assert_eq!(keys.key().unwrap(), Some(GrantKey::from_bytes([0xd2; KEY_LEN])), "the next call reads the key through a new connection");
|
||||
assert_eq!(RESTARTS.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
/// The secret `MOCK` keeps for `account`, as it is kept.
|
||||
fn kept(account: &str) -> Vec<u8> {
|
||||
MOCK.build(OsGrantKeys::SERVICE, account, None).unwrap().get_secret().unwrap()
|
||||
|
||||
@@ -4514,7 +4514,8 @@ fn a_removal_the_key_store_cannot_make_last_fails() {
|
||||
|
||||
/// A stored plug-in that didn't load, because the grants file of an older version doesn't count, and
|
||||
/// that keeps no settings or cache, is removed with its module and its entry, and the removal
|
||||
/// reports it removed. A removal whose stored module can't be deleted fails.
|
||||
/// reports it removed. A removal whose stored module can't be deleted fails and keeps its settings.
|
||||
/// Removing an invalid id leaves the kept generation as it is.
|
||||
#[test]
|
||||
fn removing_a_stored_plugin_that_did_not_load_reports_it_removed() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
@@ -4536,13 +4537,29 @@ fn removing_a_stored_plugin_that_did_not_load_reports_it_removed() {
|
||||
assert!(s.execute("plugin.remove", &json!({"id": id})).is_err(), "a second removal finds nothing");
|
||||
|
||||
// A stored module that can't be deleted (here a folder in its place), of a plug-in that keeps
|
||||
// settings, fails the removal.
|
||||
// settings, fails the removal, and the settings stay for the next try.
|
||||
std::fs::create_dir_all(module.join("held")).unwrap();
|
||||
std::fs::create_dir_all(crate::store::plugin_data_dir(&folder.0, id)).unwrap();
|
||||
let data_dir = crate::store::plugin_data_dir(&folder.0, id);
|
||||
std::fs::create_dir_all(&data_dir).unwrap();
|
||||
let setting = data_dir.join("settings.json");
|
||||
std::fs::write(&setting, b"{}").unwrap();
|
||||
let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
|
||||
assert!(refused.contains("can't delete"), "{refused}");
|
||||
assert!(module.exists());
|
||||
assert_eq!(std::fs::read(&setting).ok().as_deref(), Some(&b"{}"[..]), "the settings are moved back");
|
||||
std::fs::remove_dir_all(&module).unwrap();
|
||||
assert_eq!(s.execute("plugin.remove", &json!({"id": id})).ok(), Some(json!({"removed": id})), "a second removal deletes them");
|
||||
assert!(!data_dir.exists());
|
||||
|
||||
// An invalid id names no grant: its removal doesn't raise the generation.
|
||||
let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::with_key(crate::store::grant_keys::GrantKey::from_bytes([3; 32])));
|
||||
let _keys = ThreadKeys::using(SharedKeys::new(&keys));
|
||||
for invalid in ["", "not an id"] {
|
||||
assert!(s.execute("plugin.remove", &json!({"id": invalid})).is_err(), "{invalid:?} isn't found");
|
||||
assert_eq!(kept_generation(&keys, &folder.0), None, "{invalid:?}: the generation is left as it is");
|
||||
}
|
||||
assert!(s.execute("plugin.remove", &json!({"id": id})).is_err());
|
||||
assert_eq!(kept_generation(&keys, &folder.0), Some(2), "a valid id's removal still retires signed copies");
|
||||
}
|
||||
|
||||
/// A MAC is made over the generation, the grants and the folder, and only the whole MAC of the same
|
||||
@@ -4935,6 +4952,30 @@ fn a_revoke_after_a_write_whose_generation_wasnt_kept_keeps_that_write_granting_
|
||||
}
|
||||
}
|
||||
|
||||
/// A grant whose signed file fits the 1 MiB limit at the generation it is written at is kept, also
|
||||
/// when the file would not fit with a longer generation number.
|
||||
#[test]
|
||||
fn a_grants_file_that_fits_at_its_generation_is_written() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
let keys = std::sync::Arc::new(crate::store::grant_keys::MemoryGrantKeys::default());
|
||||
let _keys = ThreadKeys::using(SharedKeys::new(&keys));
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-grants-fit");
|
||||
let id = "test.engine.permissions.grantsfit";
|
||||
let grant = doc_read_grant(id, &sha256_hex(b"module"));
|
||||
let grants = folder.0.join("grants.json");
|
||||
// The file as it is written: compact, since pretty-printed it is larger than the limit.
|
||||
let size = |pad: &str| serde_json::to_vec(&json!({"version": 1, "generation": 3, "grants": [grant, pad], "mac": "0".repeat(64)})).unwrap().len();
|
||||
let pad = "a".repeat((1 << 20) - size(""));
|
||||
assert_eq!(size(&pad), 1 << 20);
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
std::fs::write(&grants, crate::store::signed_grants_file(&folder.0, &json!([pad]).to_string())).unwrap();
|
||||
assert!(s.store_grant(id, Some(grant)), "the grant is kept");
|
||||
let written = std::fs::read(&grants).unwrap();
|
||||
assert_eq!((written.len(), generation_of(&written)), (1 << 20, Some(3)));
|
||||
assert_eq!(kept_generation(&keys, &folder.0), Some(3));
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
Reference in New Issue
Block a user