Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 29 additions & 8 deletions client/src/file/locked_keyring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,14 @@ impl LockedKeyring {

/// Unlocks a keyring and validates it
pub async fn unlock(self, secret: Secret) -> Result<UnlockedKeyring, Error> {
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<UnlockedKeyring, Error> {
self.unlock_inner(secret, true).await
}

Expand All @@ -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
Expand All @@ -128,7 +136,7 @@ impl LockedKeyring {
}

async fn unlock_inner(
self,
&self,
secret: Secret,
validate_items: bool,
) -> Result<UnlockedKeyring, Error> {
Expand All @@ -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")]
Expand Down Expand Up @@ -180,11 +188,16 @@ impl LockedKeyring {
}
}

fn into_unlocked(self, key: Option<Arc<Key>>, secret: Option<Arc<Secret>>) -> UnlockedKeyring {
/// An unlocked handle on the same keyring data.
async fn to_unlocked(
&self,
key: Option<Arc<Key>>,
secret: Option<Arc<Secret>>,
) -> 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),
}
Expand All @@ -196,6 +209,14 @@ impl LockedKeyring {
/// encryption. Returns [`Error::IncorrectSecret`] if encrypted items
/// are found.
pub async fn unlock_unencrypted(self) -> Result<UnlockedKeyring, Error> {
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<UnlockedKeyring, Error> {
let inner_keyring = self.keyring.read().await;
for encrypted_item in &inner_keyring.items {
if !encrypted_item.is_valid(None) {
Expand All @@ -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.
Expand Down
16 changes: 5 additions & 11 deletions server/src/collection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
)));
Expand Down
90 changes: 90 additions & 0 deletions server/src/collection/tests/locking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,93 @@ async fn locked_collection_operations() -> Result<(), Box<dyn std::error::Error>

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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
unlock_after_keyring_file_is_damaged(KeyringDamage::Corrupted).await
}

#[tokio::test]
async fn unlock_after_keyring_file_is_deleted() -> Result<(), Box<dyn std::error::Error>> {
unlock_after_keyring_file_is_damaged(KeyringDamage::Deleted).await
}
Loading