From 0a323742897decee814198b92450cc01969494a3 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Thu, 19 Nov 2026 20:37:20 +0100 Subject: [PATCH] server: Keep the locked keyring on a failed unlock A failed unlock reloaded the keyring from disk, which bricks the collection when the file can no longer be parsed and silently discards the in-memory items when it was deleted. Add a borrowing LockedKeyring::try_unlock that leaves the keyring untouched on failure and use it from the server. --- client/src/file/locked_keyring.rs | 37 ++++++++--- server/src/collection/mod.rs | 16 ++--- server/src/collection/tests/locking.rs | 90 ++++++++++++++++++++++++++ 3 files changed, 124 insertions(+), 19 deletions(-) diff --git a/client/src/file/locked_keyring.rs b/client/src/file/locked_keyring.rs index 8e221f81..cf1f2a28 100644 --- a/client/src/file/locked_keyring.rs +++ b/client/src/file/locked_keyring.rs @@ -90,6 +90,14 @@ impl LockedKeyring { /// Unlocks a keyring and validates it pub async fn unlock(self, secret: Secret) -> Result { + self.try_unlock(secret).await + } + + /// Unlocks a keyring and validates it + /// + /// The keyring is left untouched when the secret does not decrypt it, + /// unlike [`Self::unlock`] which consumes it. + pub async fn try_unlock(&self, secret: Secret) -> Result { self.unlock_inner(secret, true).await } @@ -111,7 +119,7 @@ impl LockedKeyring { Self::log_validation_error(&validation, false); validation?; - Ok(self.into_unlocked(Some(Arc::new(key)), None)) + Ok(self.to_unlocked(Some(Arc::new(key)), None).await) } /// Unlocks a keyring without validating it @@ -128,7 +136,7 @@ impl LockedKeyring { } async fn unlock_inner( - self, + &self, secret: Secret, validate_items: bool, ) -> Result { @@ -146,7 +154,7 @@ impl LockedKeyring { None }; - Ok(self.into_unlocked(key, Some(Arc::new(secret)))) + Ok(self.to_unlocked(key, Some(Arc::new(secret))).await) } #[cfg(feature = "tracing")] @@ -180,11 +188,16 @@ impl LockedKeyring { } } - fn into_unlocked(self, key: Option>, secret: Option>) -> UnlockedKeyring { + /// An unlocked handle on the same keyring data. + async fn to_unlocked( + &self, + key: Option>, + secret: Option>, + ) -> UnlockedKeyring { UnlockedKeyring { - keyring: self.keyring, - path: self.path, - mtime: self.mtime, + keyring: Arc::clone(&self.keyring), + path: self.path.clone(), + mtime: Mutex::new(*self.mtime.lock().await), key: Mutex::new(key), secret: Mutex::new(secret), } @@ -196,6 +209,14 @@ impl LockedKeyring { /// encryption. Returns [`Error::IncorrectSecret`] if encrypted items /// are found. pub async fn unlock_unencrypted(self) -> Result { + self.try_unlock_unencrypted().await + } + + /// Unlocks a keyring without a secret, for unencrypted keyrings. + /// + /// The keyring is left untouched when it holds encrypted items, + /// unlike [`Self::unlock_unencrypted`] which consumes it. + pub async fn try_unlock_unencrypted(&self) -> Result { let inner_keyring = self.keyring.read().await; for encrypted_item in &inner_keyring.items { if !encrypted_item.is_valid(None) { @@ -204,7 +225,7 @@ impl LockedKeyring { } drop(inner_keyring); - Ok(self.into_unlocked(None, None)) + Ok(self.to_unlocked(None, None).await) } /// Load a keyring from a file path. diff --git a/server/src/collection/mod.rs b/server/src/collection/mod.rs index 48aa8e20..42611641 100644 --- a/server/src/collection/mod.rs +++ b/server/src/collection/mod.rs @@ -639,24 +639,18 @@ impl Collection { Keyring::Locked(unlocked.lock()) } (Keyring::Locked(locked_kr), false) => { - let keyring_path = locked_kr.path().map(|p| p.to_path_buf()); - let unlock_result = if let Some(secret) = secret { - locked_kr.unlock(secret).await + locked_kr.try_unlock(secret).await } else { - locked_kr.unlock_unencrypted().await + locked_kr.try_unlock_unencrypted().await }; let unlocked = match unlock_result { Ok(unlocked) => unlocked, Err(err) => { - // Reload the locked keyring from disk before - // returning error - if let Some(path) = keyring_path - && let Ok(reloaded) = oo7::file::LockedKeyring::load(&path).await - { - *keyring_guard = Some(Keyring::Locked(reloaded)); - } + // Put the locked keyring back, it can be + // unlocked again + *keyring_guard = Some(Keyring::Locked(locked_kr)); return Err(custom_service_error(&format!( "Failed to unlock keyring: {err}" ))); diff --git a/server/src/collection/tests/locking.rs b/server/src/collection/tests/locking.rs index 5d6ebbfd..883c7972 100644 --- a/server/src/collection/tests/locking.rs +++ b/server/src/collection/tests/locking.rs @@ -97,3 +97,93 @@ async fn locked_collection_operations() -> Result<(), Box Ok(()) } + +// A failed unlock must not brick the collection when the keyring file +// can no longer be read from disk +enum KeyringDamage { + Corrupted, + Deleted, +} + +async fn unlock_after_keyring_file_is_damaged( + damage: KeyringDamage, +) -> Result<(), Box> { + use oo7::{Secret, file::UnlockedKeyring}; + + let temp_dir = tempfile::tempdir()?; + let secret = Secret::from("test-password-long-enough"); + let keyring = UnlockedKeyring::open_at(temp_dir.path(), "login", Some(secret.clone())).await?; + keyring + .create_item( + "Test Item", + &[("app", "test")], + Secret::text("item-secret"), + false, + ) + .await?; + keyring.write().await?; + + let setup = TestServiceSetup::with_disk_keyrings( + temp_dir.path().to_path_buf(), + None, + Some(secret.clone()), + ) + .await?; + + let collection = setup + .server + .collection_from_path( + setup + .service_api + .read_alias("default") + .await? + .expect("default collection should exist") + .inner() + .path(), + ) + .await + .expect("collection should exist"); + + // Damage the keyring file behind the daemon's back + let keyring_path = temp_dir.path().join("keyrings/v1/login.keyring"); + match damage { + KeyringDamage::Corrupted => tokio::fs::write(&keyring_path, b"corrupted").await?, + KeyringDamage::Deleted => tokio::fs::remove_file(&keyring_path).await?, + } + + collection.set_locked(true, None).await?; + assert!(collection.is_locked().await); + + // A wrong secret fails and leaves the collection locked + assert!( + collection + .set_locked(false, Some(Secret::from("wrong-password"))) + .await + .is_err() + ); + assert!(collection.is_locked().await); + + // The correct secret still unlocks the in-memory keyring, with its + // items + collection.set_locked(false, Some(secret)).await?; + assert!(!collection.is_locked().await); + let found = collection + .search_inner_items(&std::collections::HashMap::from([( + "app".to_string(), + "test".to_string(), + )])) + .await?; + assert_eq!(found.len(), 1, "The in-memory items should have survived"); + + Ok(()) +} + +#[tokio::test] +async fn unlock_after_keyring_file_is_corrupted() -> Result<(), Box> { + unlock_after_keyring_file_is_damaged(KeyringDamage::Corrupted).await +} + +#[tokio::test] +async fn unlock_after_keyring_file_is_deleted() -> Result<(), Box> { + unlock_after_keyring_file_is_damaged(KeyringDamage::Deleted).await +}