From b19eed462cdcb8a1ed7c1cd1b3c14e0a8346e123 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Wed, 11 Nov 2026 13:57:26 +0100 Subject: [PATCH 01/12] server: Add assert_next_signal test helper --- server/src/collection/tests.rs | 52 ++++++---------------------------- server/src/item/tests.rs | 37 +++++------------------- server/src/service/tests.rs | 13 +-------- server/src/tests.rs | 10 +++++++ 4 files changed, 26 insertions(+), 86 deletions(-) diff --git a/server/src/collection/tests.rs b/server/src/collection/tests.rs index 5ff71efe..1248bba0 100644 --- a/server/src/collection/tests.rs +++ b/server/src/collection/tests.rs @@ -4,9 +4,11 @@ use std::sync::{ }; use oo7::dbus; -use tokio_stream::StreamExt; -use crate::{service::PrompterType, tests::TestServiceSetup}; +use crate::{ + service::PrompterType, + tests::{TestServiceSetup, assert_next_signal}, +}; #[tokio::test] async fn create_item_plain() -> Result<(), Box> { @@ -421,15 +423,7 @@ async fn item_created_signal() -> Result<(), Box> { .create_item("Test Item", &[("app", "test")], "test-secret", false) .await?; - // Wait for signal with timeout - let signal_result = - tokio::time::timeout(tokio::time::Duration::from_secs(1), signal_stream.next()).await; - - assert!(signal_result.is_ok(), "Should receive ItemCreated signal"); - let signal = signal_result.unwrap(); - assert!(signal.is_some(), "Signal should not be None"); - - let signal_item = signal.unwrap(); + let signal_item = assert_next_signal(&mut signal_stream).await; assert_eq!( signal_item.inner().path().as_str(), item.inner().path().as_str(), @@ -457,15 +451,7 @@ async fn item_deleted_signal() -> Result<(), Box> { // Delete the item item.delete(None).await?; - // Wait for signal with timeout - let signal_result = - tokio::time::timeout(tokio::time::Duration::from_secs(1), signal_stream.next()).await; - - assert!(signal_result.is_ok(), "Should receive ItemDeleted signal"); - let signal = signal_result.unwrap(); - assert!(signal.is_some(), "Signal should not be None"); - - let signal_item = signal.unwrap(); + let signal_item = assert_next_signal(&mut signal_stream).await; assert_eq!( signal_item.as_str(), item_path.as_str(), @@ -488,18 +474,7 @@ async fn collection_changed_signal() -> Result<(), Box> { .set_label("Updated Collection Label") .await?; - // Wait for signal with timeout - let signal_result = - tokio::time::timeout(tokio::time::Duration::from_secs(1), signal_stream.next()).await; - - assert!( - signal_result.is_ok(), - "Should receive CollectionChanged signal after label change" - ); - let signal = signal_result.unwrap(); - assert!(signal.is_some(), "Signal should not be None"); - - let signal_collection = signal.unwrap(); + let signal_collection = assert_next_signal(&mut signal_stream).await; assert_eq!( signal_collection.inner().path().as_str(), setup.collections[0].inner().path().as_str(), @@ -573,18 +548,7 @@ async fn collection_deleted_signal() -> Result<(), Box> { // Delete the collection setup.collections[0].delete(None).await?; - // Wait for signal with timeout - let signal_result = - tokio::time::timeout(tokio::time::Duration::from_secs(1), signal_stream.next()).await; - - assert!( - signal_result.is_ok(), - "Should receive CollectionDeleted signal" - ); - let signal = signal_result.unwrap(); - assert!(signal.is_some(), "Signal should not be None"); - - let signal_collection = signal.unwrap(); + let signal_collection = assert_next_signal(&mut signal_stream).await; assert_eq!( signal_collection.as_str(), collection_path.as_str(), diff --git a/server/src/item/tests.rs b/server/src/item/tests.rs index b7fd327c..81eba832 100644 --- a/server/src/item/tests.rs +++ b/server/src/item/tests.rs @@ -1,9 +1,11 @@ use std::sync::Arc; use oo7::dbus; -use tokio_stream::StreamExt; -use crate::{service::PrompterType, tests::TestServiceSetup}; +use crate::{ + service::PrompterType, + tests::{TestServiceSetup, assert_next_signal}, +}; #[tokio::test] async fn label_property() -> Result<(), Box> { @@ -357,18 +359,7 @@ async fn item_changed_signal() -> Result<(), Box> { // Change the label item.set_label("Updated Label").await?; - // Wait for signal - let signal_result = - tokio::time::timeout(tokio::time::Duration::from_secs(1), signal_stream.next()).await; - - assert!( - signal_result.is_ok(), - "Should receive ItemChanged signal after label change" - ); - let signal = signal_result.unwrap(); - assert!(signal.is_some(), "Signal should not be None"); - - let signal_item = signal.unwrap(); + let signal_item = assert_next_signal(&mut signal_stream).await; assert_eq!( signal_item.inner().path().as_str(), item.inner().path().as_str(), @@ -377,26 +368,12 @@ async fn item_changed_signal() -> Result<(), Box> { // Change attributes and verify signal again item.set_attributes(&[("app", "updated-app")]).await?; - - let signal_result = - tokio::time::timeout(tokio::time::Duration::from_secs(1), signal_stream.next()).await; - - assert!( - signal_result.is_ok(), - "Should receive ItemChanged signal after attributes change" - ); + assert_next_signal(&mut signal_stream).await; // Change secret and verify signal again let new_dbus_secret = setup.create_dbus_secret("new-secret")?; item.set_secret(&new_dbus_secret).await?; - - let signal_result = - tokio::time::timeout(tokio::time::Duration::from_secs(1), signal_stream.next()).await; - - assert!( - signal_result.is_ok(), - "Should receive ItemChanged signal after secret change" - ); + assert_next_signal(&mut signal_stream).await; Ok(()) } diff --git a/server/src/service/tests.rs b/server/src/service/tests.rs index ddb2f3a7..a8896970 100644 --- a/server/src/service/tests.rs +++ b/server/src/service/tests.rs @@ -937,18 +937,7 @@ async fn create_collection_signal_impl( .create_collection("TestKeyring", None, None) .await?; - // Wait for signal with timeout - let signal_result = - tokio::time::timeout(tokio::time::Duration::from_secs(1), signal_stream.next()).await; - - assert!( - signal_result.is_ok(), - "Should receive CollectionCreated signal" - ); - let signal = signal_result.unwrap(); - assert!(signal.is_some(), "Signal should not be None"); - - let signal_collection = signal.unwrap(); + let signal_collection = crate::tests::assert_next_signal(&mut signal_stream).await; assert_eq!( signal_collection.inner().path().as_str(), collection.inner().path().as_str(), diff --git a/server/src/tests.rs b/server/src/tests.rs index 9277a763..8dfbf807 100644 --- a/server/src/tests.rs +++ b/server/src/tests.rs @@ -13,6 +13,16 @@ use crate::gnome::{ }; use crate::service::{PrompterType, Service}; +pub(crate) async fn assert_next_signal( + stream: &mut (impl tokio_stream::Stream + Unpin), +) -> T { + let result = tokio::time::timeout(tokio::time::Duration::from_secs(1), stream.next()).await; + assert!(result.is_ok(), "Signal not received within timeout"); + let signal = result.unwrap(); + assert!(signal.is_some(), "Signal stream ended unexpectedly"); + signal.unwrap() +} + /// Helper to create a peer-to-peer connection pair using Unix socket pub(crate) async fn create_p2p_connection() -> Result<(zbus::Connection, zbus::Connection), Box> { From e7d0f4478c937b906699910aa2cb47ca32e20541 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Wed, 11 Nov 2026 14:05:19 +0100 Subject: [PATCH 02/12] server: Add Service::collection_by_label test helper --- server/src/pam_listener/tests.rs | 79 +++++++++---------------- server/src/service/mod.rs | 11 ++++ server/src/service/unencrypted_tests.rs | 15 ++--- 3 files changed, 43 insertions(+), 62 deletions(-) diff --git a/server/src/pam_listener/tests.rs b/server/src/pam_listener/tests.rs index 78cb083d..59f315a2 100644 --- a/server/src/pam_listener/tests.rs +++ b/server/src/pam_listener/tests.rs @@ -115,18 +115,6 @@ async fn pam_migrates_v0_keyrings() -> Result<(), Box> { 1, "Should have exactly one non-session collection (placeholder replaced in place, not duplicated)" ); - let mut legacy_collection = None; - for collection in collections.values() { - if collection.label().await == "Legacy" { - legacy_collection = Some(collection); - break; - } - } - assert!( - legacy_collection.is_some(), - "Migrated Legacy collection should exist" - ); - // The migrated collection is served at the path of its alias, like the // others for collection in collections.values() { @@ -138,6 +126,12 @@ async fn pam_migrates_v0_keyrings() -> Result<(), Box> { .await?; assert_eq!(served.get().await.path(), collection.path()); } + drop(collections); + + assert!( + setup.server.collection_by_label("Legacy").await.is_some(), + "Migrated Legacy collection should exist" + ); let v1_migrated = v1_dir.join("legacy.keyring"); assert!(v1_migrated.exists(), "V1 file should exist after migration"); @@ -222,7 +216,7 @@ async fn pam_migration_then_write_to_default_alias() -> Result<(), Box Result<(), Box Result<(), Box Result<(), Box> { ) .await?; - let collections = setup.server.collections.lock().await; - let mut work_collection = None; - for collection in collections.values() { - if collection.label().await == "Work" { - work_collection = Some(collection); - break; - } - } - let work_collection = work_collection.unwrap(); + let work_collection = setup + .server + .collection_by_label("Work") + .await + .expect("Work collection should exist"); assert!( work_collection.is_locked().await, "Work collection should be locked" ); - drop(collections); let pam_listener = PamListener::new(setup.server.clone()); let socket_path = pam_listener.socket_path.clone(); @@ -362,15 +341,11 @@ async fn pam_change_password() -> Result<(), Box> { ); send_pam_message(&socket_path, &message).await?; - let collections = setup.server.collections.lock().await; - let mut work_collection = None; - for collection in collections.values() { - if collection.label().await == "Work" { - work_collection = Some(collection); - break; - } - } - let work_collection = work_collection.unwrap(); + let work_collection = setup + .server + .collection_by_label("Work") + .await + .expect("Work collection should exist"); assert!( work_collection.is_locked().await, "Collection should be locked after password change" diff --git a/server/src/service/mod.rs b/server/src/service/mod.rs index 8c92f7b5..59e0e5a4 100644 --- a/server/src/service/mod.rs +++ b/server/src/service/mod.rs @@ -535,6 +535,17 @@ impl Service { None } + #[cfg(test)] + pub async fn collection_by_label(&self, label: &str) -> Option { + let collections = self.collections.lock().await; + for collection in collections.values() { + if collection.label().await == label { + return Some(collection.clone()); + } + } + None + } + pub async fn collection_from_path(&self, path: &ObjectPath<'_>) -> Option { let collections = self.collections.lock().await; if let Some(collection) = collections.get(path).cloned() { diff --git a/server/src/service/unencrypted_tests.rs b/server/src/service/unencrypted_tests.rs index 118a0785..afaae552 100644 --- a/server/src/service/unencrypted_tests.rs +++ b/server/src/service/unencrypted_tests.rs @@ -26,20 +26,15 @@ async fn discover_unencrypted_keyrings() -> Result<(), Box Date: Wed, 11 Nov 2026 14:07:42 +0100 Subject: [PATCH 03/12] server: Add spawn_pam_listener test helper --- server/src/pam_listener/tests.rs | 42 +++++++++++--------------------- 1 file changed, 14 insertions(+), 28 deletions(-) diff --git a/server/src/pam_listener/tests.rs b/server/src/pam_listener/tests.rs index 59f315a2..ffb00628 100644 --- a/server/src/pam_listener/tests.rs +++ b/server/src/pam_listener/tests.rs @@ -3,6 +3,16 @@ use zgvariant::serialized::Context; use super::*; +async fn spawn_pam_listener(server: &crate::Service) -> std::path::PathBuf { + let pam_listener = PamListener::new(server.clone()); + let socket_path = pam_listener.socket_path.clone(); + tokio::spawn(async move { + let _ = pam_listener.start().await; + }); + tokio::time::sleep(tokio::time::Duration::from_millis(10)).await; + socket_path +} + fn create_pam_message( operation: PamOperation, username: &str, @@ -84,13 +94,7 @@ async fn pam_migrates_v0_keyrings() -> Result<(), Box> { "V0 keyring should be pending migration" ); - let pam_listener = PamListener::new(setup.server.clone()); - let socket_path = pam_listener.socket_path.clone(); - tokio::spawn(async move { - let _ = pam_listener.start().await; - }); - - tokio::time::sleep(tokio::time::Duration::from_millis(10)).await; + let socket_path = spawn_pam_listener(&setup.server).await; let message = create_pam_message(PamOperation::Unlock, "testuser", &[], v0_secret.as_bytes()); send_pam_message(&socket_path, &message).await?; @@ -175,13 +179,7 @@ async fn pam_migration_then_write_to_default_alias() -> Result<(), Box Result<(), Box Result<(), Box> { "Work collection should be locked" ); - let pam_listener = PamListener::new(setup.server.clone()); - let socket_path = pam_listener.socket_path.clone(); - tokio::spawn(async move { - let _ = pam_listener.start().await; - }); - - tokio::time::sleep(tokio::time::Duration::from_millis(10)).await; + let socket_path = spawn_pam_listener(&setup.server).await; let new_secret = Secret::from("new-password"); let message = create_pam_message( From 7f752e85b13ec053ad9a57c6fb537b6daccd8d10 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Wed, 11 Nov 2026 14:23:50 +0100 Subject: [PATCH 04/12] server: Sort test collections by path, remove default_collection helper --- server/src/collection/tests.rs | 6 +++--- server/src/gnome/internal.rs | 14 +++++++------- server/src/item/tests.rs | 8 ++++---- server/src/service/tests.rs | 6 +++--- server/src/tests.rs | 25 ++++++++----------------- 5 files changed, 25 insertions(+), 34 deletions(-) diff --git a/server/src/collection/tests.rs b/server/src/collection/tests.rs index 1248bba0..ea5336c3 100644 --- a/server/src/collection/tests.rs +++ b/server/src/collection/tests.rs @@ -624,7 +624,7 @@ async fn delete_locked_collection_with_prompt_impl( ) -> Result<(), Box> { let setup = TestServiceSetup::plain_session(true).await?; setup.server.set_prompter_type(prompter_type).await; - let default_collection = setup.default_collection().await?; + let default_collection = &setup.collections[0]; setup.lock_collection(default_collection).await?; @@ -681,7 +681,7 @@ async fn delete_locked_collection_with_prompt_plasma() -> Result<(), Box Result<(), Box> { let setup = TestServiceSetup::plain_session(true).await?; setup.server.set_prompter_type(prompter_type).await; - let default_collection = setup.default_collection().await?; + let default_collection = &setup.collections[0]; let dbus_secret = setup.create_dbus_secret("test-secret-data")?; default_collection @@ -781,7 +781,7 @@ async fn locked_collection_operations() -> Result<(), Box async fn concurrent_replace_and_lookup() -> Result<(), Box> { let setup = TestServiceSetup::plain_session(true).await?; let conn = &setup.client_conn; - let default_collection = setup.default_collection().await?; + let default_collection = &setup.collections[0]; let collection_path = default_collection.inner().path().to_owned(); // Seed both items. diff --git a/server/src/gnome/internal.rs b/server/src/gnome/internal.rs index f6aaef0b..764aceee 100644 --- a/server/src/gnome/internal.rs +++ b/server/src/gnome/internal.rs @@ -305,7 +305,7 @@ mod tests { .await?; // Get the default collection - let default_collection = setup.default_collection().await?; + let default_collection = &setup.collections[0]; let collection_path: zbus::wire::OwnedObjectPath = default_collection.inner().path().to_owned().into(); @@ -347,7 +347,7 @@ mod tests { .build() .await?; - let default_collection = setup.default_collection().await?; + let default_collection = &setup.collections[0]; let collection_path: zbus::wire::OwnedObjectPath = default_collection.inner().path().to_owned().into(); @@ -401,7 +401,7 @@ mod tests { .build() .await?; - let default_collection = setup.default_collection().await?; + let default_collection = &setup.collections[0]; let collection_path: zbus::wire::OwnedObjectPath = default_collection.inner().path().to_owned().into(); @@ -462,7 +462,7 @@ mod tests { .build() .await?; - let default_collection = setup.default_collection().await?; + let default_collection = &setup.collections[0]; let collection_path: zbus::wire::OwnedObjectPath = default_collection.inner().path().to_owned().into(); @@ -548,7 +548,7 @@ mod tests { .build() .await?; - let default_collection = setup.default_collection().await?; + let default_collection = &setup.collections[0]; let collection_path: zbus::wire::OwnedObjectPath = default_collection.inner().path().to_owned().into(); @@ -621,7 +621,7 @@ mod tests { .build() .await?; - let default_collection = setup.default_collection().await?; + let default_collection = &setup.collections[0]; let collection_path: zbus::wire::OwnedObjectPath = default_collection.inner().path().to_owned().into(); @@ -654,7 +654,7 @@ mod tests { .build() .await?; - let default_collection = setup.default_collection().await?; + let default_collection = &setup.collections[0]; let collection_path: zbus::wire::OwnedObjectPath = default_collection.inner().path().to_owned().into(); diff --git a/server/src/item/tests.rs b/server/src/item/tests.rs index 81eba832..153360c4 100644 --- a/server/src/item/tests.rs +++ b/server/src/item/tests.rs @@ -383,7 +383,7 @@ async fn delete_locked_item_with_prompt_impl( ) -> Result<(), Box> { let setup = TestServiceSetup::plain_session(true).await?; setup.server.set_prompter_type(prompter_type).await; - let default_collection = setup.default_collection().await?; + let default_collection = &setup.collections[0]; let dbus_secret = setup.create_dbus_secret("test-password")?; @@ -532,7 +532,7 @@ async fn set_label_persists() -> Result<(), Box> { let setup = TestServiceSetup::with_login_keyring(oo7::Secret::from("test-password-long-enough")) .await?; - let collection = setup.default_collection().await?; + let collection = &setup.collections[0]; // Stored first, with a superset of the changed item's attributes let other_secret = setup.create_dbus_secret("other-secret")?; @@ -564,7 +564,7 @@ async fn set_attributes_persists() -> Result<(), Box> { let setup = TestServiceSetup::with_login_keyring(oo7::Secret::from("test-password-long-enough")) .await?; - let collection = setup.default_collection().await?; + let collection = &setup.collections[0]; // Stored first, with a superset of the changed item's attributes let other_secret = setup.create_dbus_secret("other-secret")?; @@ -597,7 +597,7 @@ async fn set_secret_persists() -> Result<(), Box> { let setup = TestServiceSetup::with_login_keyring(oo7::Secret::from("test-password-long-enough")) .await?; - let collection = setup.default_collection().await?; + let collection = &setup.collections[0]; // Stored first, with a superset of the changed item's attributes let other_secret = setup.create_dbus_secret("other-secret")?; diff --git a/server/src/service/tests.rs b/server/src/service/tests.rs index a8896970..f067636f 100644 --- a/server/src/service/tests.rs +++ b/server/src/service/tests.rs @@ -1815,7 +1815,7 @@ async fn concurrent_item_unlock_creates_single_prompt_impl( let setup = TestServiceSetup::plain_session(true).await?; setup.server.set_prompter_type(prompter_type).await; - let collection = setup.default_collection().await?; + let collection = &setup.collections[0]; let dbus_secret = setup.create_dbus_secret("item-secret")?; let item = collection .create_item( @@ -1872,7 +1872,7 @@ async fn unlock_wrong_password_dismissed_impl( let setup = TestServiceSetup::plain_session(true).await?; setup.server.set_prompter_type(prompter_type).await; - let collection = setup.default_collection().await?; + let collection = &setup.collections[0]; let dbus_secret = setup.create_dbus_secret("item-secret")?; collection .create_item( @@ -1914,7 +1914,7 @@ async fn concurrent_unlock_creates_single_prompt_impl( let setup = TestServiceSetup::plain_session(true).await?; setup.server.set_prompter_type(prompter_type).await; - let collection = setup.default_collection().await?; + let collection = &setup.collections[0]; // Lock the collection setup.lock_collection(collection).await?; diff --git a/server/src/tests.rs b/server/src/tests.rs index 8dfbf807..4bd24162 100644 --- a/server/src/tests.rs +++ b/server/src/tests.rs @@ -77,19 +77,6 @@ impl Drop for TestServiceSetup { } impl TestServiceSetup { - /// Get the default/Login collection - pub async fn default_collection( - &self, - ) -> Result<&dbus::api::Collection, Box> { - for collection in &self.collections { - let label = collection.label().await?; - if label == "Login" { - return Ok(collection); - } - } - Err("Default collection not found".into()) - } - async fn setup_server( secret: Option, encrypted_supported: bool, @@ -154,7 +141,8 @@ impl TestServiceSetup { let s = Self::setup_server(secret.clone(), true).await?; let (server_public_key, session) = s.service_api.open_session(None).await?; - let collections = s.service_api.collections().await?; + let mut collections = s.service_api.collections().await?; + collections.sort_by(|a, b| a.inner().path().cmp(b.inner().path())); Ok(TestServiceSetup { server: s.server, @@ -181,7 +169,8 @@ impl TestServiceSetup { let s = Self::setup_server(secret.clone(), false).await?; let (server_public_key, session) = s.service_api.open_session(None).await?; - let collections = s.service_api.collections().await?; + let mut collections = s.service_api.collections().await?; + collections.sort_by(|a, b| a.inner().path().cmp(b.inner().path())); Ok(TestServiceSetup { server: s.server, @@ -220,7 +209,8 @@ impl TestServiceSetup { let aes_key = oo7::Key::generate_aes_key(&client_private_key, server_public_key.as_ref().unwrap())?; - let collections = s.service_api.collections().await?; + let mut collections = s.service_api.collections().await?; + collections.sort_by(|a, b| a.inner().path().cmp(b.inner().path())); Ok(Self { server: s.server, @@ -303,7 +293,8 @@ impl TestServiceSetup { let (server_public_key, session) = service_api.open_session(None).await?; let session = Arc::new(session); - let collections = service_api.collections().await?; + let mut collections = service_api.collections().await?; + collections.sort_by(|a, b| a.inner().path().cmp(b.inner().path())); Ok(TestServiceSetup { server: service, From 899074cd4c9d1a7bb804950c9e3dd4a2081fecd3 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Wed, 11 Nov 2026 15:12:11 +0100 Subject: [PATCH 05/12] server: Merge redundant service tests --- server/src/service/tests.rs | 174 +++++++----------------------------- 1 file changed, 31 insertions(+), 143 deletions(-) diff --git a/server/src/service/tests.rs b/server/src/service/tests.rs index f067636f..ffa6aa8b 100644 --- a/server/src/service/tests.rs +++ b/server/src/service/tests.rs @@ -421,60 +421,19 @@ async fn get_secrets_with_non_existent_items() -> Result<(), Box Result<(), Box> { +async fn lock_unlock_edge_cases() -> Result<(), Box> { let setup = TestServiceSetup::plain_session(true).await?; - let collections = setup.service_api.collections().await?; - assert_eq!(collections.len(), 2, "Should have 2 collections"); - - // Create item in first collection - let dbus_secret1 = setup.create_dbus_secret("password1")?; - - collections[0] - .create_item( - "Default Item", - &[("shared", "attr")], - &dbus_secret1, - false, - None, - ) - .await?; - - // Create item in second collection with same attributes - let dbus_secret2 = setup.create_dbus_secret("password2")?; - - collections[1] - .create_item( - "Session Item", - &[("shared", "attr")], - &dbus_secret2, - false, - None, - ) - .await?; - - // Search should find items from both collections - let (unlocked, locked) = setup - .service_api - .search_items(&[("shared", "attr")]) - .await?; - - assert_eq!(unlocked.len(), 2, "Should find items from both collections"); - assert!(locked.is_empty(), "Should have no locked items"); - - Ok(()) -} - -#[tokio::test] -async fn unlock_edge_cases() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Test 1: Empty object list + // Unlock: empty object list let items: Vec> = vec![]; let unlocked = setup.service_api.unlock(&items, None).await?; assert!(unlocked.is_empty(), "Should return empty for empty input"); - // Test 2: Non-existent objects + // Lock: empty object list + let locked = setup.service_api.lock(&items, None).await?; + assert!(locked.is_empty(), "Should return empty for empty input"); + + // Shared fake objects for non-existent tests let fake_collection = dbus::api::Collection::new( &setup.client_conn, "/org/freedesktop/secrets/collection/NonExistent", @@ -487,28 +446,29 @@ async fn unlock_edge_cases() -> Result<(), Box> { ) .await?; - let unlocked = setup - .service_api - .unlock( - &[fake_collection.inner().path(), fake_item.inner().path()], - None, - ) - .await?; + let fake_paths = [fake_collection.inner().path(), fake_item.inner().path()]; + // Unlock: non-existent objects + let unlocked = setup.service_api.unlock(&fake_paths, None).await?; assert!( unlocked.is_empty(), "Should have no unlocked objects for non-existent paths" ); - // Test 3: Already unlocked objects + // Lock: non-existent objects + let locked = setup.service_api.lock(&fake_paths, None).await?; + assert!( + locked.is_empty(), + "Should have no locked objects for non-existent paths" + ); + + // Unlock: already unlocked item let item = setup .create_item("Test Item", &[("app", "test")], "test-password", false) .await?; - // Verify item is unlocked assert!(!item.is_locked().await?, "Item should be unlocked"); - // Try to unlock already unlocked item let unlocked = setup .service_api .unlock(&[item.inner().path()], None) @@ -521,7 +481,7 @@ async fn unlock_edge_cases() -> Result<(), Box> { "Should return the same item path" ); - // Also test with collection (starts unlocked by default) + // Unlock: already unlocked collection assert!( !setup.collections[0].is_locked().await?, "Collection should be unlocked" @@ -541,44 +501,6 @@ async fn unlock_edge_cases() -> Result<(), Box> { Ok(()) } -#[tokio::test] -async fn lock_non_existent_objects() -> Result<(), Box> { - let setup = TestServiceSetup::encrypted_session(true).await?; - - // Test with empty object list - let items: Vec> = vec![]; - let locked = setup.service_api.lock(&items, None).await?; - assert!(locked.is_empty(), "Should return empty for empty input"); - - // Test locking non-existent objects - let fake_collection = dbus::api::Collection::new( - &setup.client_conn, - "/org/freedesktop/secrets/collection/NonExistent", - ) - .await?; - - let fake_item = dbus::api::Item::new( - &setup.client_conn, - "/org/freedesktop/secrets/collection/Login/999", - ) - .await?; - - let locked = setup - .service_api - .lock( - &[fake_collection.inner().path(), fake_item.inner().path()], - None, - ) - .await?; - - assert!( - locked.is_empty(), - "Should have no locked objects for non-existent paths" - ); - - Ok(()) -} - async fn unlock_collection_prompt_impl( prompter_type: PrompterType, ) -> Result<(), Box> { @@ -857,12 +779,24 @@ async fn create_collection_basic_impl( let initial_collections = setup.service_api.collections().await?; let initial_count = initial_collections.len(); + // Subscribe to CollectionCreated signal before creating + let signal_stream = setup.service_api.receive_collection_created().await?; + tokio::pin!(signal_stream); + // Create a new collection let collection = setup .service_api .create_collection("MyNewKeyring", Some("my-custom-alias"), None) .await?; + // Verify CollectionCreated signal was emitted + let signal_collection = crate::tests::assert_next_signal(&mut signal_stream).await; + assert_eq!( + signal_collection.inner().path().as_str(), + collection.inner().path().as_str(), + "Signal should contain the created collection path" + ); + // Verify collection appears in collections list let collections = setup.service_api.collections().await?; assert_eq!( @@ -921,52 +855,6 @@ async fn create_collection_basic_plasma() -> Result<(), Box Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - - // Subscribe to CollectionCreated signal - let signal_stream = setup.service_api.receive_collection_created().await?; - tokio::pin!(signal_stream); - - // Create a new collection - let collection = setup - .service_api - .create_collection("TestKeyring", None, None) - .await?; - - let signal_collection = crate::tests::assert_next_signal(&mut signal_stream).await; - assert_eq!( - signal_collection.inner().path().as_str(), - collection.inner().path().as_str(), - "Signal should contain the created collection path" - ); - - let server_collection = setup - .server - .collection_from_path(collection.inner().path()) - .await - .expect("Collection should exist on server"); - let keyring_guard = server_collection.keyring.read().await; - let keyring_path = keyring_guard.as_ref().unwrap().path().unwrap(); - tokio::fs::remove_file(keyring_path).await?; - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn create_collection_signal_gnome() -> Result<(), Box> { - create_collection_signal_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn create_collection_signal_plasma() -> Result<(), Box> { - create_collection_signal_impl(PrompterType::Plasma).await -} - async fn create_collection_and_add_items_impl( prompter_type: PrompterType, ) -> Result<(), Box> { From d04cc8ea1854296c1306fbce8a7d58366436d8fd Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Wed, 11 Nov 2026 15:22:51 +0100 Subject: [PATCH 06/12] server: Split service tests into per-area modules --- server/src/service/tests.rs | 1904 ------------------------ server/src/service/tests/alias.rs | 262 ++++ server/src/service/tests/collection.rs | 232 +++ server/src/service/tests/discovery.rs | 495 ++++++ server/src/service/tests/locking.rs | 522 +++++++ server/src/service/tests/mod.rs | 7 + server/src/service/tests/search.rs | 197 +++ server/src/service/tests/secrets.rs | 168 +++ server/src/service/tests/session.rs | 44 + 9 files changed, 1927 insertions(+), 1904 deletions(-) delete mode 100644 server/src/service/tests.rs create mode 100644 server/src/service/tests/alias.rs create mode 100644 server/src/service/tests/collection.rs create mode 100644 server/src/service/tests/discovery.rs create mode 100644 server/src/service/tests/locking.rs create mode 100644 server/src/service/tests/mod.rs create mode 100644 server/src/service/tests/search.rs create mode 100644 server/src/service/tests/secrets.rs create mode 100644 server/src/service/tests/session.rs diff --git a/server/src/service/tests.rs b/server/src/service/tests.rs deleted file mode 100644 index ffa6aa8b..00000000 --- a/server/src/service/tests.rs +++ /dev/null @@ -1,1904 +0,0 @@ -use oo7::dbus; -use tokio_stream::StreamExt; - -use super::*; -use crate::{prompt::MAX_UNLOCK_ATTEMPTS, tests::TestServiceSetup}; - -#[tokio::test] -async fn open_session_plain() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - assert!( - setup.aes_key.is_none(), - "Plain session should not have AES key" - ); - - // Should have 2 collections: default + session - assert_eq!( - setup.collections.len(), - 2, - "Expected default and session collections" - ); - Ok(()) -} - -#[tokio::test] -async fn open_session_encrypted() -> Result<(), Box> { - let setup = TestServiceSetup::encrypted_session(false).await?; - assert!( - setup.server_public_key.is_some(), - "Encrypted session should have server public key" - ); - let key = setup.aes_key.as_deref().unwrap(); - assert_eq!(key.as_ref().len(), 16, "AES key should be 16 bytes"); - Ok(()) -} - -#[tokio::test] -async fn session_collection_only() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(false).await?; - - // Should have only session collection (no default) - assert_eq!( - setup.collections.len(), - 1, - "Should have exactly one collection" - ); - Ok(()) -} - -#[tokio::test] -async fn search_items() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Search for items (should return empty initially) - let (unlocked, locked) = setup - .service_api - .search_items(&[("application", "test-app")]) - .await?; - - assert!( - unlocked.is_empty(), - "Should have no unlocked items initially" - ); - assert!(locked.is_empty(), "Should have no locked items initially"); - - // Search with empty attributes - edge case - let attributes: HashMap<&str, &str> = HashMap::default(); - let (unlocked, locked) = setup.service_api.search_items(&attributes).await?; - - assert!( - locked.is_empty(), - "Should have no locked items with empty search" - ); - assert!( - unlocked.is_empty(), - "Should have no unlocked items with empty search" - ); - - // Test with both locked and unlocked items - // Create items in default collection (unlocked) - setup - .create_item("Unlocked Item", &[("app", "testapp")], "password1", false) - .await?; - - // Create item in default collection and lock it - let locked_item = setup - .create_item("Locked Item", &[("app", "testapp")], "password2", false) - .await?; - - // Lock just this item (not the whole collection) - setup.lock_item(&locked_item).await?; - - // Search for items with the shared attribute - let (unlocked, locked) = setup - .service_api - .search_items(&[("app", "testapp")]) - .await?; - - assert_eq!(unlocked.len(), 1, "Should find 1 unlocked item"); - assert_eq!(locked.len(), 1, "Should find 1 locked item"); - - Ok(()) -} - -#[tokio::test] -async fn get_secrets() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Test with empty items list - edge case - #[allow(clippy::mutable_key_type)] - let secrets = setup.service_api.secrets(&[], &setup.session).await?; - assert!( - secrets.is_empty(), - "Should return empty secrets for empty items list" - ); - - // Create two items with different secrets - let secret1 = Secret::text("password1"); - let item1 = setup - .create_item("Item 1", &[("app", "test1")], secret1.clone(), false) - .await?; - - let secret2 = Secret::text("password2"); - let item2 = setup - .create_item("Item 2", &[("app", "test2")], secret2.clone(), false) - .await?; - - // Get secrets for both items - let item_paths = vec![item1.clone(), item2.clone()]; - #[allow(clippy::mutable_key_type)] - let secrets = setup - .service_api - .secrets(&item_paths, &setup.session) - .await?; - - // Should have both secrets - assert_eq!(secrets.len(), 2, "Should retrieve both secrets"); - - // Verify first secret - let retrieved_secret1 = secrets.get(&item1).unwrap(); - assert_eq!(retrieved_secret1.value(), secret1.as_bytes()); - - // Verify second secret - let retrieved_secret2 = secrets.get(&item2).unwrap(); - assert_eq!(retrieved_secret2.value(), secret2.as_bytes()); - - Ok(()) -} - -#[tokio::test] -async fn get_secrets_multiple_collections() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Should have 2 collections: default (Login) and session - assert_eq!(setup.collections.len(), 2); - - // Create item in default collection (index 0) - let secret1 = Secret::text("default-password"); - let item1 = setup - .create_item( - "Default Item", - &[("app", "default-app")], - secret1.clone(), - false, - ) - .await?; - - // Create item in session collection (index 1) - let secret2 = Secret::text("session-password"); - let dbus_secret2 = setup.create_dbus_secret(secret2.clone())?; - - let item2 = setup.collections[1] - .create_item( - "Session Item", - &[("app", "session-app")], - &dbus_secret2, - false, - None, - ) - .await?; - - // Get secrets for both items from different collections - let item_paths = vec![item1.clone(), item2.clone()]; - #[allow(clippy::mutable_key_type)] - let secrets = setup - .service_api - .secrets(&item_paths, &setup.session) - .await?; - - // Should have both secrets - assert_eq!( - secrets.len(), - 2, - "Should retrieve secrets from both collections" - ); - - // Verify default collection secret - let retrieved_secret1 = secrets.get(&item1).unwrap(); - assert_eq!(retrieved_secret1.value(), secret1.as_bytes()); - - // Verify session collection secret - let retrieved_secret2 = secrets.get(&item2).unwrap(); - assert_eq!(retrieved_secret2.value(), secret2.as_bytes()); - - Ok(()) -} - -#[tokio::test] -async fn read_alias() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Default collection should have "default" alias - let default_collection = setup.service_api.read_alias("default").await?; - assert!( - default_collection.is_some(), - "Default alias should return a collection" - ); - - // Verify it's the Login collection by checking its label - let label = default_collection.as_ref().unwrap().label().await?; - assert_eq!( - label, "Login", - "Default alias should point to Login collection" - ); - - // Non-existent alias should return None - let nonexistent = setup.service_api.read_alias("nonexistent").await?; - assert!( - nonexistent.is_none(), - "Non-existent alias should return None" - ); - - Ok(()) -} - -#[tokio::test] -async fn set_alias() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Set alias for session collection - setup - .service_api - .set_alias("my-alias", &setup.collections[1]) - .await?; - - // Read the alias back - let alias_collection = setup.service_api.read_alias("my-alias").await?; - assert!( - alias_collection.is_some(), - "Alias should return a collection" - ); - assert_eq!( - alias_collection.unwrap().inner().path(), - setup.collections[1].inner().path(), - "Alias should point to session collection" - ); - - Ok(()) -} - -#[tokio::test] -async fn search_items_with_results() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Create items in default collection - setup - .create_item( - "Firefox Login", - &[("application", "firefox"), ("type", "login")], - "password1", - false, - ) - .await?; - - setup - .create_item( - "Chrome Login", - &[("application", "chrome"), ("type", "login")], - "password2", - false, - ) - .await?; - - // Create item in session collection - let dbus_secret3 = setup.create_dbus_secret("password3")?; - - setup.collections[1] - .create_item( - "Session Item", - &[("application", "firefox"), ("type", "session")], - &dbus_secret3, - false, - None, - ) - .await?; - - // Search for all firefox items - let (unlocked, locked) = setup - .service_api - .search_items(&[("application", "firefox")]) - .await?; - - assert_eq!(unlocked.len(), 2, "Should find 2 firefox items"); - assert!(locked.is_empty(), "Should have no locked items"); - - // Search for login type items - let (unlocked, locked) = setup.service_api.search_items(&[("type", "login")]).await?; - - assert_eq!(unlocked.len(), 2, "Should find 2 login items"); - assert!(locked.is_empty(), "Should have no locked items"); - - // Search for chrome items - let (unlocked, locked) = setup - .service_api - .search_items(&[("application", "chrome")]) - .await?; - - assert_eq!(unlocked.len(), 1, "Should find 1 chrome item"); - assert!(locked.is_empty(), "Should have no locked items"); - - // Search for non-existent - let (unlocked, locked) = setup - .service_api - .search_items(&[("application", "nonexistent")]) - .await?; - - assert!(unlocked.is_empty(), "Should find no items"); - assert!(locked.is_empty(), "Should have no locked items"); - - Ok(()) -} - -#[tokio::test] -async fn get_secrets_invalid_session() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Create an item - let item = setup - .create_item("Test Item", &[("app", "test")], "test-password", false) - .await?; - - // Try to get secrets with invalid session path - let invalid_session = - dbus::api::Session::new(&setup.client_conn, "/invalid/session/path").await?; - let result = setup.service_api.secrets(&[item], &invalid_session).await; - - assert!( - matches!( - result, - Err(oo7::dbus::Error::Service( - oo7::dbus::ServiceError::NoSession(_) - )) - ), - "Should be NoSession error" - ); - - Ok(()) -} - -#[tokio::test] -async fn set_alias_invalid_collection() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Try to set alias for non-existent collection - let invalid_collection = dbus::api::Collection::new( - &setup.client_conn, - "/org/freedesktop/secrets/collection/nonexistent", - ) - .await?; - let result = setup - .service_api - .set_alias("test-alias", &invalid_collection) - .await; - - assert!( - matches!( - result, - Err(oo7::dbus::Error::Service( - oo7::dbus::ServiceError::NoSuchObject(_) - )) - ), - "Should be NoSuchObject error" - ); - - Ok(()) -} - -#[tokio::test] -async fn get_secrets_with_non_existent_items() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Create one real item - let item1 = setup - .create_item("Item 1", &[("app", "test")], "password1", false) - .await?; - - // Create a fake item path that doesn't exist - let fake_item = dbus::api::Item::new( - &setup.client_conn, - "/org/freedesktop/secrets/collection/Login/999", - ) - .await?; - - // Request secrets for both real and fake items - let item_paths = vec![item1.clone(), fake_item]; - #[allow(clippy::mutable_key_type)] - let secrets = setup - .service_api - .secrets(&item_paths, &setup.session) - .await?; - - // Should only get the secret for the real item - assert_eq!( - secrets.len(), - 1, - "Should only retrieve secret for existing item" - ); - assert!(secrets.contains_key(&item1), "Should have item1 secret"); - - Ok(()) -} - -#[tokio::test] -async fn lock_unlock_edge_cases() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Unlock: empty object list - let items: Vec> = vec![]; - let unlocked = setup.service_api.unlock(&items, None).await?; - assert!(unlocked.is_empty(), "Should return empty for empty input"); - - // Lock: empty object list - let locked = setup.service_api.lock(&items, None).await?; - assert!(locked.is_empty(), "Should return empty for empty input"); - - // Shared fake objects for non-existent tests - let fake_collection = dbus::api::Collection::new( - &setup.client_conn, - "/org/freedesktop/secrets/collection/NonExistent", - ) - .await?; - - let fake_item = dbus::api::Item::new( - &setup.client_conn, - "/org/freedesktop/secrets/collection/Login/999", - ) - .await?; - - let fake_paths = [fake_collection.inner().path(), fake_item.inner().path()]; - - // Unlock: non-existent objects - let unlocked = setup.service_api.unlock(&fake_paths, None).await?; - assert!( - unlocked.is_empty(), - "Should have no unlocked objects for non-existent paths" - ); - - // Lock: non-existent objects - let locked = setup.service_api.lock(&fake_paths, None).await?; - assert!( - locked.is_empty(), - "Should have no locked objects for non-existent paths" - ); - - // Unlock: already unlocked item - let item = setup - .create_item("Test Item", &[("app", "test")], "test-password", false) - .await?; - - assert!(!item.is_locked().await?, "Item should be unlocked"); - - let unlocked = setup - .service_api - .unlock(&[item.inner().path()], None) - .await?; - - assert_eq!(unlocked.len(), 1, "Should return the already-unlocked item"); - assert_eq!( - unlocked[0].as_str(), - item.inner().path().as_str(), - "Should return the same item path" - ); - - // Unlock: already unlocked collection - assert!( - !setup.collections[0].is_locked().await?, - "Collection should be unlocked" - ); - - let unlocked = setup - .service_api - .unlock(&[setup.collections[0].inner().path()], None) - .await?; - - assert_eq!( - unlocked.len(), - 1, - "Should return the already-unlocked collection" - ); - - Ok(()) -} - -async fn unlock_collection_prompt_impl( - prompter_type: PrompterType, -) -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - - // Lock the collection using server-side API - setup.lock_collection(&setup.collections[0]).await?; - - assert!( - setup.collections[0].is_locked().await?, - "Collection should be locked" - ); - - // Test 1: Unlock with accept - let unlocked = setup - .service_api - .unlock(&[setup.collections[0].inner().path()], None) - .await?; - - assert_eq!(unlocked.len(), 1, "Should have unlocked 1 collection"); - assert_eq!( - unlocked[0].as_str(), - setup.collections[0].inner().path().as_str(), - "Should return the collection path" - ); - assert!( - !setup.collections[0].is_locked().await?, - "Collection should be unlocked after accepting prompt" - ); - - // Lock the collection again for dismiss test - setup.lock_collection(&setup.collections[0]).await?; - assert!( - setup.collections[0].is_locked().await?, - "Collection should be locked again" - ); - - // Test 2: Unlock with dismiss - setup.set_password_accept(false).await; - let result = setup - .service_api - .unlock(&[setup.collections[0].inner().path()], None) - .await; - - assert!( - matches!(result, Err(oo7::dbus::Error::Dismissed)), - "Should return Dismissed error when prompt dismissed" - ); - assert!( - setup.collections[0].is_locked().await?, - "Collection should still be locked after dismissing prompt" - ); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn unlock_collection_prompt_gnome() -> Result<(), Box> { - unlock_collection_prompt_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn unlock_collection_prompt_plasma() -> Result<(), Box> { - unlock_collection_prompt_impl(PrompterType::Plasma).await -} - -/// Clients like Chromium call Unlock and Prompt without opening a session. -async fn unlock_collection_prompt_without_session_impl( - prompter_type: PrompterType, -) -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - setup.lock_collection(&setup.collections[0]).await?; - setup.session.close().await?; - - let unlocked = setup - .service_api - .unlock(&[setup.collections[0].inner().path()], None) - .await?; - - assert_eq!(unlocked.len(), 1, "Should have unlocked 1 collection"); - assert!( - !setup.collections[0].is_locked().await?, - "Collection should be unlocked after accepting prompt" - ); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn unlock_collection_prompt_without_session_gnome() -> Result<(), Box> -{ - unlock_collection_prompt_without_session_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn unlock_collection_prompt_without_session_plasma() -> Result<(), Box> -{ - unlock_collection_prompt_without_session_impl(PrompterType::Plasma).await -} - -async fn unlock_item_prompt_impl( - prompter_type: PrompterType, -) -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - - // Create an item - let dbus_secret = setup.create_dbus_secret("test-password")?; - let default_collection = setup.service_api.read_alias("default").await?.unwrap(); - let item = default_collection - .create_item("Test Item", &[("app", "test")], &dbus_secret, false, None) - .await?; - - // Lock the collection (which locks the item) - setup.lock_collection(&default_collection).await?; - - assert!( - item.is_locked().await?, - "Item should be locked when collection is locked" - ); - - // Test 1: Unlock with accept - let unlocked = setup - .service_api - .unlock(&[item.inner().path()], None) - .await?; - - assert_eq!(unlocked.len(), 1, "Should have unlocked 1 item"); - assert_eq!( - unlocked[0].as_str(), - item.inner().path().as_str(), - "Should return the item path" - ); - assert!( - !item.is_locked().await?, - "Item should be unlocked after accepting prompt" - ); - - // Lock the item again for dismiss test - setup.lock_collection(&default_collection).await?; - assert!(item.is_locked().await?, "Item should be locked again"); - - // Test 2: Unlock with dismiss - setup.set_password_accept(false).await; - let result = setup.service_api.unlock(&[item.inner().path()], None).await; - - assert!( - matches!(result, Err(oo7::dbus::Error::Dismissed)), - "Should return Dismissed error when prompt dismissed" - ); - assert!( - item.is_locked().await?, - "Item should still be locked after dismissing prompt" - ); - - Ok(()) -} - -#[tokio::test] -async fn lock_item_in_unlocked_collection() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Create an item (starts unlocked) - let item = setup - .create_item("Test Item", &[("app", "test")], "test-password", false) - .await?; - - assert!(!item.is_locked().await?, "Item should start unlocked"); - assert!( - !setup.collections[0].is_locked().await?, - "Collection should be unlocked" - ); - - // When collection is unlocked, locking an item should happen directly - // without a prompt - let locked = setup.service_api.lock(&[item.inner().path()], None).await?; - - assert_eq!(locked.len(), 1, "Should have locked 1 item"); - assert_eq!( - locked[0].as_str(), - item.inner().path().as_str(), - "Should return the item path" - ); - assert!(item.is_locked().await?, "Item should be locked directly"); - - // Unlock the item again (using service API to unlock just the item) - let unlocked = setup - .service_api - .unlock(&[item.inner().path()], None) - .await?; - assert_eq!(unlocked.len(), 1, "Should have unlocked 1 item"); - assert!(!item.is_locked().await?, "Item should be unlocked again"); - - // Locking again should work the same way (no prompt) - let locked = setup.service_api.lock(&[item.inner().path()], None).await?; - assert_eq!(locked.len(), 1, "Should have locked 1 item again"); - assert!(item.is_locked().await?, "Item should be locked again"); - - Ok(()) -} - -#[tokio::test] -async fn lock_collection_no_prompt() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Collection starts unlocked - assert!( - !setup.collections[0].is_locked().await?, - "Collection should start unlocked" - ); - - // Lock the collection - let locked = setup - .service_api - .lock(&[setup.collections[0].inner().path()], None) - .await?; - - assert_eq!(locked.len(), 1, "Should have locked 1 collection"); - assert_eq!( - locked[0].as_str(), - setup.collections[0].inner().path().as_str(), - "Should return the collection path" - ); - assert!( - setup.collections[0].is_locked().await?, - "Collection should be locked instantly" - ); - - // Unlock the collection - setup.unlock_collection(&setup.collections[0]).await?; - assert!( - !setup.collections[0].is_locked().await?, - "Collection should be unlocked" - ); - - // Lock again to verify it works multiple times - let locked = setup - .service_api - .lock(&[setup.collections[0].inner().path()], None) - .await?; - - assert_eq!(locked.len(), 1, "Should have locked 1 collection again"); - assert!( - setup.collections[0].is_locked().await?, - "Collection should be locked again" - ); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn unlock_item_prompt_gnome() -> Result<(), Box> { - unlock_item_prompt_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn unlock_item_prompt_plasma() -> Result<(), Box> { - unlock_item_prompt_impl(PrompterType::Plasma).await -} - -async fn create_collection_basic_impl( - prompter_type: PrompterType, -) -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - - // Get initial collection count - let initial_collections = setup.service_api.collections().await?; - let initial_count = initial_collections.len(); - - // Subscribe to CollectionCreated signal before creating - let signal_stream = setup.service_api.receive_collection_created().await?; - tokio::pin!(signal_stream); - - // Create a new collection - let collection = setup - .service_api - .create_collection("MyNewKeyring", Some("my-custom-alias"), None) - .await?; - - // Verify CollectionCreated signal was emitted - let signal_collection = crate::tests::assert_next_signal(&mut signal_stream).await; - assert_eq!( - signal_collection.inner().path().as_str(), - collection.inner().path().as_str(), - "Signal should contain the created collection path" - ); - - // Verify collection appears in collections list - let collections = setup.service_api.collections().await?; - assert_eq!( - collections.len(), - initial_count + 1, - "Should have one more collection" - ); - - // Verify the collection label - let label = collection.label().await?; - assert_eq!( - label, "MyNewKeyring", - "Collection should have correct label" - ); - - // Verify the keyring file exists on disk - let server_collection = setup - .server - .collection_from_path(collection.inner().path()) - .await - .expect("Collection should exist on server"); - let keyring_guard = server_collection.keyring.read().await; - let keyring_path = keyring_guard.as_ref().unwrap().path().unwrap(); - - assert!( - keyring_path.exists(), - "Keyring file should exist on disk at {:?}", - keyring_path - ); - - // Verify the alias was set - let alias_collection = setup.service_api.read_alias("my-custom-alias").await?; - assert!( - alias_collection.is_some(), - "Should be able to read collection by alias" - ); - assert_eq!( - alias_collection.unwrap().inner().path(), - collection.inner().path(), - "Alias should point to the new collection" - ); - - tokio::fs::remove_file(keyring_path).await?; - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn create_collection_basic_gnome() -> Result<(), Box> { - create_collection_basic_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn create_collection_basic_plasma() -> Result<(), Box> { - create_collection_basic_impl(PrompterType::Plasma).await -} - -async fn create_collection_and_add_items_impl( - prompter_type: PrompterType, -) -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - - // Create a new collection - let collection = setup - .service_api - .create_collection("ItemTestKeyring", None, None) - .await?; - - // Verify collection is unlocked and ready for items - assert!( - !collection.is_locked().await?, - "New collection should be unlocked" - ); - - // Create an item in the new collection - let secret = oo7::Secret::text("hello-world-test"); - let dbus_secret = setup.create_dbus_secret(secret.clone())?; - - let item = collection - .create_item( - "Test Item", - &[("app", "test-app")], - &dbus_secret, - false, - None, - ) - .await?; - - // Verify item was created - let items = collection.items().await?; - assert_eq!(items.len(), 1, "Should have one item in new collection"); - assert_eq!( - items[0].inner().path(), - item.inner().path(), - "Item path should match" - ); - - // Verify we can retrieve the secret - let retrieved_secret = item.secret(&setup.session).await?; - assert_eq!( - retrieved_secret.value(), - secret.as_bytes(), - "Should be able to retrieve secret from item in new collection" - ); - - let server_collection = setup - .server - .collection_from_path(collection.inner().path()) - .await - .expect("Collection should exist on server"); - let keyring_guard = server_collection.keyring.read().await; - let keyring_path = keyring_guard.as_ref().unwrap().path().unwrap(); - tokio::fs::remove_file(&keyring_path).await?; - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn create_collection_and_add_items_gnome() -> Result<(), Box> { - create_collection_and_add_items_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn create_collection_and_add_items_plasma() -> Result<(), Box> { - create_collection_and_add_items_impl(PrompterType::Plasma).await -} - -async fn create_collection_dismissed_impl( - prompter_type: PrompterType, -) -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - - // Get initial collection count - let initial_collections = setup.service_api.collections().await?; - let initial_count = initial_collections.len(); - - // Set mock prompter to dismiss - setup.set_password_accept(false).await; - - // Try to create a collection - let result = setup - .service_api - .create_collection("DismissedKeyring", None, None) - .await; - - // Should get Dismissed error - assert!( - matches!(result, Err(oo7::dbus::Error::Dismissed)), - "Should return Dismissed error when prompt dismissed" - ); - - // Verify collection was NOT created - let collections = setup.service_api.collections().await?; - assert_eq!( - collections.len(), - initial_count, - "Should not have created a new collection after dismissal" - ); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn create_collection_dismissed_gnome() -> Result<(), Box> { - create_collection_dismissed_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn create_collection_dismissed_plasma() -> Result<(), Box> { - create_collection_dismissed_impl(PrompterType::Plasma).await -} - -#[tokio::test] -async fn complete_collection_creation_no_pending() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Try to complete collection creation with a prompt path that has no - // pending collection - let fake_prompt_path = ObjectPath::try_from("/org/freedesktop/secrets/prompt/p999").unwrap(); - let secret = Secret::from("test-password-long-enough"); - - let result = setup - .server - .complete_collection_creation(&fake_prompt_path, Some(secret)) - .await; - - // Should get NoSuchObject error - assert!( - matches!(result, Err(ServiceError::NoSuchObject(_))), - "Should return NoSuchObject error when no pending collection exists" - ); - Ok(()) -} - -#[tokio::test] -async fn discover_v1_keyrings() -> Result<(), Box> { - // Set up a temporary data directory - let temp_dir = tempfile::tempdir()?; - let service = Service::new(temp_dir.path().to_path_buf(), None, true); - - // Create v1 keyrings directory - let v1_dir = temp_dir.path().join("keyrings/v1"); - tokio::fs::create_dir_all(&v1_dir).await?; - - // Test 1: Empty directory - let discovered = service.discover_keyrings(None).await?; - assert!( - discovered.is_empty(), - "Should discover no keyrings in empty directory" - ); - - // Create multiple keyrings with different passwords - // Add items to each so password validation works - let secret1 = Secret::from("password-for-work"); - let keyring1 = UnlockedKeyring::open_at(temp_dir.path(), "work", Some(secret1.clone())).await?; - keyring1 - .create_item( - "Work Item", - &[("type", "work")], - Secret::text("work-secret"), - false, - ) - .await?; - keyring1.write().await?; - - let secret2 = Secret::from("password-for-personal"); - let keyring2 = - UnlockedKeyring::open_at(temp_dir.path(), "personal", Some(secret2.clone())).await?; - keyring2 - .create_item( - "Personal Item", - &[("type", "personal")], - Secret::text("personal-secret"), - false, - ) - .await?; - keyring2.write().await?; - - // Create a "login" keyring which should get the default alias - let secret3 = Secret::from("password-for-login"); - let keyring3 = - UnlockedKeyring::open_at(temp_dir.path(), "login", Some(secret3.clone())).await?; - keyring3 - .create_item( - "Login Item", - &[("type", "login")], - Secret::text("login-secret"), - false, - ) - .await?; - keyring3.write().await?; - - // Create some non-keyring files that should be skipped - tokio::fs::write(v1_dir.join("README.txt"), b"This is a readme").await?; - tokio::fs::write(v1_dir.join("config.json"), b"{}").await?; - tokio::fs::create_dir(v1_dir.join("subdir")).await?; - - // Test 2: Discover without any password, all should be locked - let discovered = service.discover_keyrings(None).await?; - assert_eq!(discovered.len(), 3, "Should discover 3 keyrings"); - for dk in &discovered { - assert!( - dk.keyring.is_locked(), - "All keyrings should be locked without secret" - ); - } - - // Test 3: Discover with one password, only that keyring should be unlocked - let discovered = service.discover_keyrings(Some(secret1.clone())).await?; - assert_eq!(discovered.len(), 3, "Should discover 3 keyrings"); - - let work_keyring = discovered.iter().find(|dk| dk.label == "Work").unwrap(); - assert!( - !work_keyring.keyring.is_locked(), - "Work keyring should be unlocked with correct password" - ); - - let personal_keyring = discovered.iter().find(|dk| dk.label == "Personal").unwrap(); - assert!( - personal_keyring.keyring.is_locked(), - "Personal keyring should be locked with wrong password" - ); - - // Test 4: Verify login keyring gets default alias - let login_keyring = discovered.iter().find(|dk| dk.label == "Login").unwrap(); - assert_eq!( - login_keyring.alias, - oo7::dbus::Service::DEFAULT_COLLECTION, - "Login keyring should have default alias" - ); - assert!( - login_keyring.keyring.is_locked(), - "Login keyring should be locked with wrong password" - ); - - // Test 5: Verify labels are properly capitalized - let labels: Vec<_> = discovered.iter().map(|dk| dk.label.as_str()).collect(); - assert!(labels.contains(&"Work"), "Should have Work with capital W"); - assert!( - labels.contains(&"Personal"), - "Should have Personal with capital P" - ); - assert!( - labels.contains(&"Login"), - "Should have Login with capital L" - ); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn unlock_pending_v0_migration_gnome() -> Result<(), Box> { - unlock_pending_v0_migration_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn unlock_pending_v0_migration_plasma() -> Result<(), Box> { - unlock_pending_v0_migration_impl(PrompterType::Plasma).await -} - -async fn unlock_pending_v0_migration_impl( - prompter_type: PrompterType, -) -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - - let keyrings_dir = temp_dir.path().join("keyrings"); - let v1_dir = keyrings_dir.join("v1"); - tokio::fs::create_dir_all(&v1_dir).await?; - - // Copy the v0 keyring fixture - let v0_secret = Secret::from("test"); - let fixture_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .join("client/fixtures/legacy.keyring"); - let v0_path = keyrings_dir.join("legacy.keyring"); - tokio::fs::copy(&fixture_path, &v0_path).await?; - - // Create test service that discovers keyrings WITHOUT the password - let setup = crate::tests::TestServiceSetup::with_disk_keyrings( - temp_dir.path().to_path_buf(), - None, - None, - ) - .await?; - setup.server.set_prompter_type(prompter_type).await; - - // Verify v0 is pending migration - assert_eq!( - setup.server.pending_migrations.lock().await.len(), - 1, - "V0 keyring should be pending migration" - ); - - // Find the placeholder collection - let collections = setup.service_api.collections().await?; - let mut legacy_collection = None; - for collection in &collections { - if collection.label().await? == "Legacy" { - legacy_collection = Some(collection); - break; - } - } - let legacy_collection = legacy_collection.expect("Should have Legacy placeholder collection"); - - // Verify it's locked - assert!( - legacy_collection.is_locked().await?, - "Placeholder should be locked" - ); - - // Set up mock prompter to provide the correct password - setup.set_password_queue(vec![v0_secret.clone()]).await; - - // Unlock via D-Bus API (should trigger migration) - let unlocked = setup - .service_api - .unlock(&[legacy_collection.inner().path()], None) - .await?; - - assert_eq!(unlocked.len(), 1, "Should have unlocked the collection"); - assert!( - !legacy_collection.is_locked().await?, - "Collection should be unlocked" - ); - - // Verify migration happened - assert_eq!( - setup.server.pending_migrations.lock().await.len(), - 0, - "Should have no pending migrations after unlock" - ); - - // Verify v1 file was created - let v1_migrated = v1_dir.join("legacy.keyring"); - assert!(v1_migrated.exists(), "V1 file should exist after migration"); - - // Verify v0 file still exists but stamp was created - assert!( - v0_path.exists(), - "V0 file should still exist after migration" - ); - assert!( - crate::migration::stamp_path(&v0_path).exists(), - "Migration stamp file should exist" - ); - Ok(()) -} - -#[tokio::test] -async fn discover_v0_keyrings() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let service = Service::new(temp_dir.path().to_path_buf(), None, true); - - let keyrings_dir = temp_dir.path().join("keyrings"); - let v1_dir = keyrings_dir.join("v1"); - tokio::fs::create_dir_all(&keyrings_dir).await?; - tokio::fs::create_dir_all(&v1_dir).await?; - - // Copy the existing v0 keyring fixture - let v0_secret = Secret::from("test"); - let fixture_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .join("client/fixtures/legacy.keyring"); - let v0_path = keyrings_dir.join("legacy.keyring"); - tokio::fs::copy(&fixture_path, &v0_path).await?; - - // Create a v1 keyring for mixed scenario - let v1_secret = Secret::from("v1-password"); - let v1_keyring = - UnlockedKeyring::open_at(temp_dir.path(), "modern", Some(v1_secret.clone())).await?; - v1_keyring - .create_item( - "V1 Item", - &[("type", "v1")], - Secret::text("v1-secret"), - false, - ) - .await?; - v1_keyring.write().await?; - - // Test 1: Discover without secret, v0 marked for migration, v1 locked - let discovered = service.discover_keyrings(None).await?; - assert_eq!( - discovered.len(), - 2, - "Should discover v1 keyring + v0 placeholder" - ); - - let pending = service.pending_migrations.lock().await; - assert_eq!(pending.len(), 1, "V0 should be pending migration"); - assert!(pending.contains_key("legacy")); - drop(pending); - - // Test 2: Discover with v0 secret, v0 migrated, v1 locked - service.pending_migrations.lock().await.clear(); - let discovered = service.discover_keyrings(Some(v0_secret.clone())).await?; - assert_eq!(discovered.len(), 2, "Should discover both keyrings"); - - let legacy = discovered.iter().find(|dk| dk.label == "Legacy").unwrap(); - assert!( - !legacy.keyring.is_locked(), - "V0 should be migrated and unlocked" - ); - assert_eq!( - service.pending_migrations.lock().await.len(), - 0, - "No pending after successful migration" - ); - - // Verify v1 file was created - let v1_migrated = temp_dir.path().join("keyrings/v1/legacy.keyring"); - assert!(v1_migrated.exists(), "V1 file should exist after migration"); - - // Test 3: Discover with wrong v0 secret, marked for pending migration - tokio::fs::remove_file(&v1_migrated).await?; - let _ = tokio::fs::remove_file(crate::migration::stamp_path(&v0_path)).await; - service.pending_migrations.lock().await.clear(); - - // Restore the v0 file for this test - tokio::fs::copy(&fixture_path, &v0_path).await?; - - let wrong_secret = Secret::from("wrong-password"); - let discovered = service.discover_keyrings(Some(wrong_secret)).await?; - assert_eq!( - discovered.len(), - 2, - "V1 + v0 placeholder should be discovered with wrong v0 password" - ); - assert_eq!( - service.pending_migrations.lock().await.len(), - 1, - "V0 should be pending with wrong password" - ); - - Ok(()) -} - -#[tokio::test] -async fn discover_plain_v0_keyrings() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let service = Service::new(temp_dir.path().to_path_buf(), None, true); - - let keyrings_dir = temp_dir.path().join("keyrings"); - tokio::fs::create_dir_all(keyrings_dir.join("v1")).await?; - - let fixture_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .join("client/fixtures/plain.keyring"); - let v0_path = keyrings_dir.join("plain.keyring"); - tokio::fs::copy(&fixture_path, &v0_path).await?; - // Not a keyring, should be skipped - tokio::fs::write(keyrings_dir.join("junk.keyring"), b"junk").await?; - - // Plain keyrings are migrated even without a secret - let discovered = service.discover_keyrings(None).await?; - assert_eq!(discovered.len(), 1, "Only the plain keyring is discovered"); - - assert_eq!(discovered[0].label, "Plain"); - assert!( - !discovered[0].keyring.is_locked(), - "Plain keyring should be migrated" - ); - assert!(service.pending_migrations.lock().await.is_empty()); - assert!(keyrings_dir.join("v1/plain.keyring").exists()); - assert!(crate::migration::stamp_path(&v0_path).exists()); - - Ok(()) -} - -// https://github.com/linux-credentials/oo7/issues/586 -#[tokio::test] -async fn migrate_v0_items_without_schema() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let service = Service::new(temp_dir.path().to_path_buf(), None, true); - - let keyrings_dir = temp_dir.path().join("keyrings"); - tokio::fs::create_dir_all(keyrings_dir.join("v1")).await?; - - // Its item only has a `unique` attribute and the generic secret type - let fixture_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .join("client/fixtures/legacy-no-schema.keyring"); - tokio::fs::copy(&fixture_path, keyrings_dir.join("login.keyring")).await?; - - let secret = Secret::from("test"); - service.discover_keyrings(Some(secret.clone())).await?; - - let keyring = UnlockedKeyring::open_at(temp_dir.path(), "login", Some(secret)).await?; - let items = keyring.items().await?; - assert_eq!(items.len(), 1); - let attributes = items[0].attributes(); - assert_eq!( - attributes - .get(oo7::XDG_SCHEMA_ATTRIBUTE) - .map(|v| v.as_ref()), - Some(oo7::GENERIC_SCHEMA) - ); - - Ok(()) -} - -#[cfg(feature = "kwallet_migration")] -#[cfg(target_endian = "little")] -#[tokio::test] -async fn discover_kwallet_keyrings() -> Result<(), Box> { - let temp_dir = tempfile::tempdir()?; - let service = Service::new(temp_dir.path().to_path_buf(), None, true); - - let kwallet_dir = temp_dir.path().join("kwalletd"); - let v1_dir = temp_dir.path().join("keyrings/v1"); - tokio::fs::create_dir_all(&kwallet_dir).await?; - tokio::fs::create_dir_all(&v1_dir).await?; - - // Copy KWallet test fixture - let kwallet_secret = Secret::from("password"); - let fixture_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .parent() - .unwrap() - .join("kwallet/parser/tests/blowfish_cbc_pbkdf2_sha512_manual.kwl"); - let kwallet_path = kwallet_dir.join("kdewallet.kwl"); - tokio::fs::copy(&fixture_path, &kwallet_path).await?; - - // Copy the salt file too (required for PBKDF2-SHA512) - let salt_fixture = fixture_path.with_extension("salt"); - let salt_path = kwallet_path.with_extension("salt"); - tokio::fs::copy(&salt_fixture, &salt_path).await?; - - // Create a v1 keyring for mixed scenario - let v1_secret = Secret::from("v1-password"); - let v1_keyring = - UnlockedKeyring::open_at(temp_dir.path(), "modern", Some(v1_secret.clone())).await?; - v1_keyring - .create_item( - "V1 Item", - &[("type", "v1")], - Secret::text("v1-secret"), - false, - ) - .await?; - v1_keyring.write().await?; - - // Test 1: Discover without secret, KWallet marked for migration, v1 locked - let discovered = service.discover_keyrings(None).await?; - assert_eq!( - discovered.len(), - 2, - "Should discover v1 keyring + kwallet placeholder" - ); - - let pending = service.pending_migrations.lock().await; - assert_eq!(pending.len(), 1, "KWallet should be pending migration"); - assert!(pending.contains_key("kdewallet")); - drop(pending); - - // Test 2: Discover with KWallet secret, KWallet migrated, v1 locked - service.pending_migrations.lock().await.clear(); - let discovered = service - .discover_keyrings(Some(kwallet_secret.clone())) - .await?; - assert_eq!(discovered.len(), 2, "Should discover both keyrings"); - - let kdewallet = discovered - .iter() - .find(|dk| dk.label == "Kdewallet") - .unwrap(); - assert!( - !kdewallet.keyring.is_locked(), - "KWallet should be migrated and unlocked" - ); - assert_eq!( - kdewallet.alias, "kdewallet", - "kdewallet should have kdewallet alias (not default)" - ); - assert_eq!( - service.pending_migrations.lock().await.len(), - 0, - "No pending after successful migration" - ); - - // Verify v1 file was created - let v1_migrated = temp_dir.path().join("keyrings/v1/kdewallet.keyring"); - assert!(v1_migrated.exists(), "V1 file should exist after migration"); - - // Verify old KWallet file still exists but stamp was created - assert!( - kwallet_path.exists(), - "Original .kwl file should still exist" - ); - assert!( - crate::migration::stamp_path(&kwallet_path).exists(), - "Migration stamp file should exist" - ); - - // Test 3: Discover with wrong KWallet secret, marked for pending migration - tokio::fs::remove_file(&v1_migrated).await?; - let _ = tokio::fs::remove_file(crate::migration::stamp_path(&kwallet_path)).await; - service.pending_migrations.lock().await.clear(); - - // Restore the KWallet files for this test - tokio::fs::copy(&fixture_path, &kwallet_path).await?; - tokio::fs::copy(&salt_fixture, &salt_path).await?; - - let wrong_secret = Secret::from("wrong-password"); - let discovered = service.discover_keyrings(Some(wrong_secret)).await?; - assert_eq!( - discovered.len(), - 2, - "V1 + kwallet placeholder should be discovered with wrong KWallet password" - ); - assert_eq!( - service.pending_migrations.lock().await.len(), - 1, - "KWallet should be pending with wrong password" - ); - - // Verify the pending migration has the correct type - let pending = service.pending_migrations.lock().await; - let migration = pending.get("kdewallet").unwrap(); - assert_eq!(migration.label(), "Kdewallet"); - assert_eq!(migration.alias(), "kdewallet"); - Ok(()) -} - -#[tokio::test] -async fn set_alias_updates_alias_path() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - let login = setup.service_api.read_alias("default").await?.unwrap(); - let other = setup - .collections - .iter() - .find(|c| c.inner().path() != login.inner().path()) - .unwrap(); - let alias = |name: &str| { - dbus::api::Collection::new( - &setup.client_conn, - format!("/org/freedesktop/secrets/aliases/{name}"), - ) - }; - - setup.service_api.set_alias("work", other).await?; - assert_eq!(alias("work").await?.label().await?, other.label().await?); - - setup.service_api.set_alias("default", other).await?; - assert_eq!(alias("default").await?.label().await?, other.label().await?); - assert!(alias("work").await?.label().await.is_err()); - - Ok(()) -} - -#[tokio::test] -async fn delete_collection_removes_alias_path() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - let login = setup.service_api.read_alias("default").await?.unwrap(); - - login.delete(None).await?; - - let alias = dbus::api::Collection::new( - &setup.client_conn, - "/org/freedesktop/secrets/aliases/default", - ) - .await?; - assert!(alias.label().await.is_err()); - - Ok(()) -} - -#[tokio::test] -async fn delete_collection_through_alias_path() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - let login = setup.service_api.read_alias("default").await?.unwrap(); - let other = setup - .collections - .iter() - .find(|c| c.inner().path() != login.inner().path()) - .unwrap(); - setup.service_api.set_alias("work", other).await?; - - for name in ["default", "work"] { - let alias = dbus::api::Collection::new( - &setup.client_conn, - format!("/org/freedesktop/secrets/aliases/{name}"), - ) - .await?; - tokio::time::timeout(std::time::Duration::from_secs(5), alias.delete(None)).await??; - assert!(alias.label().await.is_err()); - } - assert!(setup.service_api.collections().await?.is_empty()); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn create_collection_serves_alias_path() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - let collection = setup - .service_api - .create_collection("Extra", Some("spare"), None) - .await?; - - let alias = - dbus::api::Collection::new(&setup.client_conn, "/org/freedesktop/secrets/aliases/spare") - .await?; - assert_eq!(alias.label().await?, "Extra"); - let path = setup.service_api.read_alias("spare").await?.unwrap(); - assert_eq!(path.inner().path(), collection.inner().path()); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn alias_paths_served_at_startup() -> Result<(), Box> { - let secret = Secret::from("test-password-long-enough"); - let data_dir = tempfile::tempdir()?; - UnlockedKeyring::open_at(data_dir.path(), "login", Some(secret.clone())) - .await? - .write() - .await?; - let setup = TestServiceSetup::with_disk_keyrings( - data_dir.path().to_path_buf(), - None, - Some(secret.clone()), - ) - .await?; - setup - .service_api - .create_collection("Work", Some("work"), None) - .await?; - - // A new service on the same keyrings - let setup = - TestServiceSetup::with_disk_keyrings(data_dir.path().to_path_buf(), None, Some(secret)) - .await?; - - for (name, label) in [ - ("default", "Login"), - ("work", "Work"), - ("session", "session"), - ] { - let alias = dbus::api::Collection::new( - &setup.client_conn, - format!("/org/freedesktop/secrets/aliases/{name}"), - ) - .await?; - assert_eq!(alias.label().await?, label); - } - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn duplicate_default_alias_resolved() -> Result<(), Box> { - let secret = Secret::from("test-password-long-enough"); - let data_dir = tempfile::tempdir()?; - - // Create a "login" keyring - let login_kr = UnlockedKeyring::open_at(data_dir.path(), "login", Some(secret.clone())).await?; - login_kr - .create_item("Login Item", &[("src", "login")], Secret::text("s"), false) - .await?; - login_kr.write().await?; - - // Create a "default" keyring - let default_kr = - UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret.clone())).await?; - default_kr - .create_item( - "Default Item", - &[("src", "default")], - Secret::text("s"), - false, - ) - .await?; - default_kr.write().await?; - - let setup = - TestServiceSetup::with_disk_keyrings(data_dir.path().to_path_buf(), None, Some(secret)) - .await?; - - // ReadAlias("default") must return the login collection - let default_collection = setup.service_api.read_alias("default").await?.unwrap(); - assert_eq!( - default_collection.label().await?, - "Login", - "ReadAlias(\"default\") should return the Login collection, not Default" - ); - - // Both keyrings plus the session collection should be present - let collections = setup.service_api.collections().await?; - assert_eq!( - collections.len(), - 3, - "Both keyrings + session should be registered" - ); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn concurrent_unlock_creates_single_prompt_gnome() -> Result<(), Box> { - concurrent_unlock_creates_single_prompt_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn concurrent_unlock_creates_single_prompt_plasma() -> Result<(), Box> -{ - concurrent_unlock_creates_single_prompt_impl(PrompterType::Plasma).await -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn concurrent_item_unlock_creates_single_prompt_gnome() --> Result<(), Box> { - concurrent_item_unlock_creates_single_prompt_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn concurrent_item_unlock_creates_single_prompt_plasma() --> Result<(), Box> { - concurrent_item_unlock_creates_single_prompt_impl(PrompterType::Plasma).await -} - -async fn concurrent_item_unlock_creates_single_prompt_impl( - prompter_type: PrompterType, -) -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - - let collection = &setup.collections[0]; - let dbus_secret = setup.create_dbus_secret("item-secret")?; - let item = collection - .create_item( - "test-item", - &HashMap::from([("app", "test")]), - &dbus_secret, - false, - None, - ) - .await?; - - setup.lock_collection(collection).await?; - assert!(collection.is_locked().await?); - - let secret = setup.keyring_secret.clone().unwrap(); - setup - .set_password_queue(vec![secret.clone(), secret.clone(), secret]) - .await; - - let item_path = item.inner().path().to_owned(); - let paths1 = [item_path.clone()]; - let paths2 = [item_path]; - let (r1, r2) = tokio::join!( - setup.service_api.unlock(&paths1, None), - setup.service_api.unlock(&paths2, None), - ); - - let _unlocked1 = r1?; - let _unlocked2 = r2?; - - assert!( - !collection.is_locked().await?, - "Collection should be unlocked after concurrent item unlock requests" - ); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn unlock_wrong_password_dismissed_gnome() -> Result<(), Box> { - unlock_wrong_password_dismissed_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn unlock_wrong_password_dismissed_plasma() -> Result<(), Box> { - unlock_wrong_password_dismissed_impl(PrompterType::Plasma).await -} - -async fn unlock_wrong_password_dismissed_impl( - prompter_type: PrompterType, -) -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - - let collection = &setup.collections[0]; - let dbus_secret = setup.create_dbus_secret("item-secret")?; - collection - .create_item( - "test-item", - &HashMap::from([("app", "test")]), - &dbus_secret, - false, - None, - ) - .await?; - - setup.lock_collection(collection).await?; - assert!(collection.is_locked().await?); - - let wrong = oo7::Secret::from("wrong-password-intentionally"); - setup - .set_password_queue(vec![wrong; MAX_UNLOCK_ATTEMPTS as usize + 1]) - .await; - - let collection_path = collection.inner().path().to_owned(); - let result = setup.service_api.unlock(&[collection_path], None).await; - - assert!( - matches!(result, Err(dbus::Error::Dismissed)), - "Expected Dismissed error after max failed attempts, got: {result:?}" - ); - - assert!( - collection.is_locked().await?, - "Collection should remain locked after failed unlock attempts" - ); - - Ok(()) -} - -async fn concurrent_unlock_creates_single_prompt_impl( - prompter_type: PrompterType, -) -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - - let collection = &setup.collections[0]; - - // Lock the collection - setup.lock_collection(collection).await?; - assert!(collection.is_locked().await?); - - // Queue enough passwords for however many prompts get created - let secret = setup.keyring_secret.clone().unwrap(); - setup - .set_password_queue(vec![secret.clone(), secret.clone(), secret]) - .await; - - // Fire two Unlock calls concurrently for the same collection. - let collection_path = collection.inner().path().to_owned(); - let paths1 = [collection_path.clone()]; - let paths2 = [collection_path]; - let (r1, r2) = tokio::join!( - setup.service_api.unlock(&paths1, None), - setup.service_api.unlock(&paths2, None), - ); - - // Both should succeed (not panic the daemon). - let _unlocked1 = r1?; - let _unlocked2 = r2?; - - // The collection should be unlocked. - assert!( - !collection.is_locked().await?, - "Collection should be unlocked after concurrent requests" - ); - - Ok(()) -} - -// Reproducer for https://github.com/linux-credentials/oo7/issues/586 -#[tokio::test] -async fn search_items_missing_xdg_schema() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Item without xdg:schema, as found in old gnome-keyring migrations. - setup - .create_item( - "Unlock password for: user@example.com", - &[("unique", "ssh-store:/home/user/.ssh/id_rsa")], - "my-ssh-passphrase", - false, - ) - .await?; - - // gcr searches with xdg:schema via libsecret's SECRET_SCHEMA_NONE. - let (unlocked, locked) = setup - .service_api - .search_items(&[ - ("unique", "ssh-store:/home/user/.ssh/id_rsa"), - (oo7::XDG_SCHEMA_ATTRIBUTE, oo7::GENERIC_SCHEMA), - ]) - .await?; - - assert_eq!(unlocked.len(), 1); - assert!(locked.is_empty()); - - Ok(()) -} - -// gcr stores the passphrase again with its schema, which must replace the -// item migrated without one instead of duplicating it. -#[tokio::test] -async fn replace_item_missing_xdg_schema() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - let unique = ("unique", "ssh-store:/home/user/.ssh/id_rsa"); - - setup - .create_item("Unlock password", &[unique], "old-passphrase", false) - .await?; - setup - .create_item( - "Unlock password", - &[unique, (oo7::XDG_SCHEMA_ATTRIBUTE, oo7::GENERIC_SCHEMA)], - "new-passphrase", - true, - ) - .await?; - - let items = setup.collections[0].items().await?; - assert_eq!(items.len(), 1); - assert_eq!( - items[0].attributes().await?.get(oo7::XDG_SCHEMA_ATTRIBUTE), - Some(&oo7::GENERIC_SCHEMA.to_owned()) - ); - - let server_collection = setup - .server - .collection_from_path(setup.collections[0].inner().path()) - .await - .unwrap(); - let keyring = server_collection.keyring.read().await; - assert_eq!(keyring.as_ref().unwrap().items().await?.len(), 1); - - Ok(()) -} diff --git a/server/src/service/tests/alias.rs b/server/src/service/tests/alias.rs new file mode 100644 index 00000000..fb7fb179 --- /dev/null +++ b/server/src/service/tests/alias.rs @@ -0,0 +1,262 @@ +use oo7::{Secret, dbus, file::UnlockedKeyring}; + +use crate::tests::TestServiceSetup; + +#[tokio::test] +async fn read_alias() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Default collection should have "default" alias + let default_collection = setup.service_api.read_alias("default").await?; + assert!( + default_collection.is_some(), + "Default alias should return a collection" + ); + + // Verify it's the Login collection by checking its label + let label = default_collection.as_ref().unwrap().label().await?; + assert_eq!( + label, "Login", + "Default alias should point to Login collection" + ); + + // Non-existent alias should return None + let nonexistent = setup.service_api.read_alias("nonexistent").await?; + assert!( + nonexistent.is_none(), + "Non-existent alias should return None" + ); + + Ok(()) +} + +#[tokio::test] +async fn set_alias() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Set alias for session collection + setup + .service_api + .set_alias("my-alias", &setup.collections[1]) + .await?; + + // Read the alias back + let alias_collection = setup.service_api.read_alias("my-alias").await?; + assert!( + alias_collection.is_some(), + "Alias should return a collection" + ); + assert_eq!( + alias_collection.unwrap().inner().path(), + setup.collections[1].inner().path(), + "Alias should point to session collection" + ); + + Ok(()) +} + +#[tokio::test] +async fn set_alias_invalid_collection() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Try to set alias for non-existent collection + let invalid_collection = dbus::api::Collection::new( + &setup.client_conn, + "/org/freedesktop/secrets/collection/nonexistent", + ) + .await?; + let result = setup + .service_api + .set_alias("test-alias", &invalid_collection) + .await; + + assert!( + matches!( + result, + Err(oo7::dbus::Error::Service( + oo7::dbus::ServiceError::NoSuchObject(_) + )) + ), + "Should be NoSuchObject error" + ); + + Ok(()) +} + +#[tokio::test] +async fn set_alias_updates_alias_path() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + let login = setup.service_api.read_alias("default").await?.unwrap(); + let other = setup + .collections + .iter() + .find(|c| c.inner().path() != login.inner().path()) + .unwrap(); + let alias = |name: &str| { + dbus::api::Collection::new( + &setup.client_conn, + format!("/org/freedesktop/secrets/aliases/{name}"), + ) + }; + + setup.service_api.set_alias("work", other).await?; + assert_eq!(alias("work").await?.label().await?, other.label().await?); + + setup.service_api.set_alias("default", other).await?; + assert_eq!(alias("default").await?.label().await?, other.label().await?); + assert!(alias("work").await?.label().await.is_err()); + + Ok(()) +} + +#[tokio::test] +async fn delete_collection_removes_alias_path() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + let login = setup.service_api.read_alias("default").await?.unwrap(); + + login.delete(None).await?; + + let alias = dbus::api::Collection::new( + &setup.client_conn, + "/org/freedesktop/secrets/aliases/default", + ) + .await?; + assert!(alias.label().await.is_err()); + + Ok(()) +} + +#[tokio::test] +async fn delete_collection_through_alias_path() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + let login = setup.service_api.read_alias("default").await?.unwrap(); + let other = setup + .collections + .iter() + .find(|c| c.inner().path() != login.inner().path()) + .unwrap(); + setup.service_api.set_alias("work", other).await?; + + for name in ["default", "work"] { + let alias = dbus::api::Collection::new( + &setup.client_conn, + format!("/org/freedesktop/secrets/aliases/{name}"), + ) + .await?; + tokio::time::timeout(std::time::Duration::from_secs(5), alias.delete(None)).await??; + assert!(alias.label().await.is_err()); + } + assert!(setup.service_api.collections().await?.is_empty()); + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn create_collection_serves_alias_path() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + let collection = setup + .service_api + .create_collection("Extra", Some("spare"), None) + .await?; + + let alias = + dbus::api::Collection::new(&setup.client_conn, "/org/freedesktop/secrets/aliases/spare") + .await?; + assert_eq!(alias.label().await?, "Extra"); + let path = setup.service_api.read_alias("spare").await?.unwrap(); + assert_eq!(path.inner().path(), collection.inner().path()); + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn alias_paths_served_at_startup() -> Result<(), Box> { + let secret = Secret::from("test-password-long-enough"); + let data_dir = tempfile::tempdir()?; + UnlockedKeyring::open_at(data_dir.path(), "login", Some(secret.clone())) + .await? + .write() + .await?; + let setup = TestServiceSetup::with_disk_keyrings( + data_dir.path().to_path_buf(), + None, + Some(secret.clone()), + ) + .await?; + setup + .service_api + .create_collection("Work", Some("work"), None) + .await?; + + // A new service on the same keyrings + let setup = + TestServiceSetup::with_disk_keyrings(data_dir.path().to_path_buf(), None, Some(secret)) + .await?; + + for (name, label) in [ + ("default", "Login"), + ("work", "Work"), + ("session", "session"), + ] { + let alias = dbus::api::Collection::new( + &setup.client_conn, + format!("/org/freedesktop/secrets/aliases/{name}"), + ) + .await?; + assert_eq!(alias.label().await?, label); + } + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn duplicate_default_alias_resolved() -> Result<(), Box> { + let secret = Secret::from("test-password-long-enough"); + let data_dir = tempfile::tempdir()?; + + // Create a "login" keyring + let login_kr = UnlockedKeyring::open_at(data_dir.path(), "login", Some(secret.clone())).await?; + login_kr + .create_item("Login Item", &[("src", "login")], Secret::text("s"), false) + .await?; + login_kr.write().await?; + + // Create a "default" keyring + let default_kr = + UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret.clone())).await?; + default_kr + .create_item( + "Default Item", + &[("src", "default")], + Secret::text("s"), + false, + ) + .await?; + default_kr.write().await?; + + let setup = + TestServiceSetup::with_disk_keyrings(data_dir.path().to_path_buf(), None, Some(secret)) + .await?; + + // ReadAlias("default") must return the login collection + let default_collection = setup.service_api.read_alias("default").await?.unwrap(); + assert_eq!( + default_collection.label().await?, + "Login", + "ReadAlias(\"default\") should return the Login collection, not Default" + ); + + // Both keyrings plus the session collection should be present + let collections = setup.service_api.collections().await?; + assert_eq!( + collections.len(), + 3, + "Both keyrings + session should be registered" + ); + + Ok(()) +} diff --git a/server/src/service/tests/collection.rs b/server/src/service/tests/collection.rs new file mode 100644 index 00000000..37273fa3 --- /dev/null +++ b/server/src/service/tests/collection.rs @@ -0,0 +1,232 @@ +use zbus::wire::ObjectPath; + +use super::super::*; +use crate::tests::TestServiceSetup; + +async fn create_collection_basic_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + + // Get initial collection count + let initial_collections = setup.service_api.collections().await?; + let initial_count = initial_collections.len(); + + // Subscribe to CollectionCreated signal before creating + let signal_stream = setup.service_api.receive_collection_created().await?; + tokio::pin!(signal_stream); + + // Create a new collection + let collection = setup + .service_api + .create_collection("MyNewKeyring", Some("my-custom-alias"), None) + .await?; + + // Verify CollectionCreated signal was emitted + let signal_collection = crate::tests::assert_next_signal(&mut signal_stream).await; + assert_eq!( + signal_collection.inner().path().as_str(), + collection.inner().path().as_str(), + "Signal should contain the created collection path" + ); + + // Verify collection appears in collections list + let collections = setup.service_api.collections().await?; + assert_eq!( + collections.len(), + initial_count + 1, + "Should have one more collection" + ); + + // Verify the collection label + let label = collection.label().await?; + assert_eq!( + label, "MyNewKeyring", + "Collection should have correct label" + ); + + // Verify the keyring file exists on disk + let server_collection = setup + .server + .collection_from_path(collection.inner().path()) + .await + .expect("Collection should exist on server"); + let keyring_guard = server_collection.keyring.read().await; + let keyring_path = keyring_guard.as_ref().unwrap().path().unwrap(); + + assert!( + keyring_path.exists(), + "Keyring file should exist on disk at {:?}", + keyring_path + ); + + // Verify the alias was set + let alias_collection = setup.service_api.read_alias("my-custom-alias").await?; + assert!( + alias_collection.is_some(), + "Should be able to read collection by alias" + ); + assert_eq!( + alias_collection.unwrap().inner().path(), + collection.inner().path(), + "Alias should point to the new collection" + ); + + tokio::fs::remove_file(keyring_path).await?; + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn create_collection_basic_gnome() -> Result<(), Box> { + create_collection_basic_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn create_collection_basic_plasma() -> Result<(), Box> { + create_collection_basic_impl(PrompterType::Plasma).await +} + +async fn create_collection_and_add_items_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + + // Create a new collection + let collection = setup + .service_api + .create_collection("ItemTestKeyring", None, None) + .await?; + + // Verify collection is unlocked and ready for items + assert!( + !collection.is_locked().await?, + "New collection should be unlocked" + ); + + // Create an item in the new collection + let secret = oo7::Secret::text("hello-world-test"); + let dbus_secret = setup.create_dbus_secret(secret.clone())?; + + let item = collection + .create_item( + "Test Item", + &[("app", "test-app")], + &dbus_secret, + false, + None, + ) + .await?; + + // Verify item was created + let items = collection.items().await?; + assert_eq!(items.len(), 1, "Should have one item in new collection"); + assert_eq!( + items[0].inner().path(), + item.inner().path(), + "Item path should match" + ); + + // Verify we can retrieve the secret + let retrieved_secret = item.secret(&setup.session).await?; + assert_eq!( + retrieved_secret.value(), + secret.as_bytes(), + "Should be able to retrieve secret from item in new collection" + ); + + let server_collection = setup + .server + .collection_from_path(collection.inner().path()) + .await + .expect("Collection should exist on server"); + let keyring_guard = server_collection.keyring.read().await; + let keyring_path = keyring_guard.as_ref().unwrap().path().unwrap(); + tokio::fs::remove_file(&keyring_path).await?; + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn create_collection_and_add_items_gnome() -> Result<(), Box> { + create_collection_and_add_items_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn create_collection_and_add_items_plasma() -> Result<(), Box> { + create_collection_and_add_items_impl(PrompterType::Plasma).await +} + +async fn create_collection_dismissed_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + + // Get initial collection count + let initial_collections = setup.service_api.collections().await?; + let initial_count = initial_collections.len(); + + // Set mock prompter to dismiss + setup.set_password_accept(false).await; + + // Try to create a collection + let result = setup + .service_api + .create_collection("DismissedKeyring", None, None) + .await; + + // Should get Dismissed error + assert!( + matches!(result, Err(oo7::dbus::Error::Dismissed)), + "Should return Dismissed error when prompt dismissed" + ); + + // Verify collection was NOT created + let collections = setup.service_api.collections().await?; + assert_eq!( + collections.len(), + initial_count, + "Should not have created a new collection after dismissal" + ); + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn create_collection_dismissed_gnome() -> Result<(), Box> { + create_collection_dismissed_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn create_collection_dismissed_plasma() -> Result<(), Box> { + create_collection_dismissed_impl(PrompterType::Plasma).await +} + +#[tokio::test] +async fn complete_collection_creation_no_pending() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Try to complete collection creation with a prompt path that has no + // pending collection + let fake_prompt_path = ObjectPath::try_from("/org/freedesktop/secrets/prompt/p999").unwrap(); + let secret = oo7::Secret::from("test-password-long-enough"); + + let result = setup + .server + .complete_collection_creation(&fake_prompt_path, Some(secret)) + .await; + + // Should get NoSuchObject error + assert!( + matches!(result, Err(ServiceError::NoSuchObject(_))), + "Should return NoSuchObject error when no pending collection exists" + ); + Ok(()) +} diff --git a/server/src/service/tests/discovery.rs b/server/src/service/tests/discovery.rs new file mode 100644 index 00000000..7aa68e68 --- /dev/null +++ b/server/src/service/tests/discovery.rs @@ -0,0 +1,495 @@ +use oo7::{Secret, file::UnlockedKeyring}; + +use super::super::*; +use crate::tests::TestServiceSetup; + +#[tokio::test] +async fn discover_v1_keyrings() -> Result<(), Box> { + // Set up a temporary data directory + let temp_dir = tempfile::tempdir()?; + let service = Service::new(temp_dir.path().to_path_buf(), None, true); + + // Create v1 keyrings directory + let v1_dir = temp_dir.path().join("keyrings/v1"); + tokio::fs::create_dir_all(&v1_dir).await?; + + // Test 1: Empty directory + let discovered = service.discover_keyrings(None).await?; + assert!( + discovered.is_empty(), + "Should discover no keyrings in empty directory" + ); + + // Create multiple keyrings with different passwords + // Add items to each so password validation works + let secret1 = Secret::from("password-for-work"); + let keyring1 = UnlockedKeyring::open_at(temp_dir.path(), "work", Some(secret1.clone())).await?; + keyring1 + .create_item( + "Work Item", + &[("type", "work")], + Secret::text("work-secret"), + false, + ) + .await?; + keyring1.write().await?; + + let secret2 = Secret::from("password-for-personal"); + let keyring2 = + UnlockedKeyring::open_at(temp_dir.path(), "personal", Some(secret2.clone())).await?; + keyring2 + .create_item( + "Personal Item", + &[("type", "personal")], + Secret::text("personal-secret"), + false, + ) + .await?; + keyring2.write().await?; + + // Create a "login" keyring which should get the default alias + let secret3 = Secret::from("password-for-login"); + let keyring3 = + UnlockedKeyring::open_at(temp_dir.path(), "login", Some(secret3.clone())).await?; + keyring3 + .create_item( + "Login Item", + &[("type", "login")], + Secret::text("login-secret"), + false, + ) + .await?; + keyring3.write().await?; + + // Create some non-keyring files that should be skipped + tokio::fs::write(v1_dir.join("README.txt"), b"This is a readme").await?; + tokio::fs::write(v1_dir.join("config.json"), b"{}").await?; + tokio::fs::create_dir(v1_dir.join("subdir")).await?; + + // Test 2: Discover without any password, all should be locked + let discovered = service.discover_keyrings(None).await?; + assert_eq!(discovered.len(), 3, "Should discover 3 keyrings"); + for dk in &discovered { + assert!( + dk.keyring.is_locked(), + "All keyrings should be locked without secret" + ); + } + + // Test 3: Discover with one password, only that keyring should be unlocked + let discovered = service.discover_keyrings(Some(secret1.clone())).await?; + assert_eq!(discovered.len(), 3, "Should discover 3 keyrings"); + + let work_keyring = discovered.iter().find(|dk| dk.label == "Work").unwrap(); + assert!( + !work_keyring.keyring.is_locked(), + "Work keyring should be unlocked with correct password" + ); + + let personal_keyring = discovered.iter().find(|dk| dk.label == "Personal").unwrap(); + assert!( + personal_keyring.keyring.is_locked(), + "Personal keyring should be locked with wrong password" + ); + + // Test 4: Verify login keyring gets default alias + let login_keyring = discovered.iter().find(|dk| dk.label == "Login").unwrap(); + assert_eq!( + login_keyring.alias, + oo7::dbus::Service::DEFAULT_COLLECTION, + "Login keyring should have default alias" + ); + assert!( + login_keyring.keyring.is_locked(), + "Login keyring should be locked with wrong password" + ); + + // Test 5: Verify labels are properly capitalized + let labels: Vec<_> = discovered.iter().map(|dk| dk.label.as_str()).collect(); + assert!(labels.contains(&"Work"), "Should have Work with capital W"); + assert!( + labels.contains(&"Personal"), + "Should have Personal with capital P" + ); + assert!( + labels.contains(&"Login"), + "Should have Login with capital L" + ); + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn unlock_pending_v0_migration_gnome() -> Result<(), Box> { + unlock_pending_v0_migration_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn unlock_pending_v0_migration_plasma() -> Result<(), Box> { + unlock_pending_v0_migration_impl(PrompterType::Plasma).await +} + +async fn unlock_pending_v0_migration_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + + let keyrings_dir = temp_dir.path().join("keyrings"); + let v1_dir = keyrings_dir.join("v1"); + tokio::fs::create_dir_all(&v1_dir).await?; + + // Copy the v0 keyring fixture + let v0_secret = Secret::from("test"); + let fixture_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .join("client/fixtures/legacy.keyring"); + let v0_path = keyrings_dir.join("legacy.keyring"); + tokio::fs::copy(&fixture_path, &v0_path).await?; + + // Create test service that discovers keyrings WITHOUT the password + let setup = + TestServiceSetup::with_disk_keyrings(temp_dir.path().to_path_buf(), None, None).await?; + setup.server.set_prompter_type(prompter_type).await; + + // Verify v0 is pending migration + assert_eq!( + setup.server.pending_migrations.lock().await.len(), + 1, + "V0 keyring should be pending migration" + ); + + // Find the placeholder collection + let collections = setup.service_api.collections().await?; + let mut legacy_collection = None; + for collection in &collections { + if collection.label().await? == "Legacy" { + legacy_collection = Some(collection); + break; + } + } + let legacy_collection = legacy_collection.expect("Should have Legacy placeholder collection"); + + // Verify it's locked + assert!( + legacy_collection.is_locked().await?, + "Placeholder should be locked" + ); + + // Set up mock prompter to provide the correct password + setup.set_password_queue(vec![v0_secret.clone()]).await; + + // Unlock via D-Bus API (should trigger migration) + let unlocked = setup + .service_api + .unlock(&[legacy_collection.inner().path()], None) + .await?; + + assert_eq!(unlocked.len(), 1, "Should have unlocked the collection"); + assert!( + !legacy_collection.is_locked().await?, + "Collection should be unlocked" + ); + + // Verify migration happened + assert_eq!( + setup.server.pending_migrations.lock().await.len(), + 0, + "Should have no pending migrations after unlock" + ); + + // Verify v1 file was created + let v1_migrated = v1_dir.join("legacy.keyring"); + assert!(v1_migrated.exists(), "V1 file should exist after migration"); + + // Verify v0 file still exists but stamp was created + assert!( + v0_path.exists(), + "V0 file should still exist after migration" + ); + assert!( + crate::migration::stamp_path(&v0_path).exists(), + "Migration stamp file should exist" + ); + Ok(()) +} + +#[tokio::test] +async fn discover_v0_keyrings() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let service = Service::new(temp_dir.path().to_path_buf(), None, true); + + let keyrings_dir = temp_dir.path().join("keyrings"); + let v1_dir = keyrings_dir.join("v1"); + tokio::fs::create_dir_all(&keyrings_dir).await?; + tokio::fs::create_dir_all(&v1_dir).await?; + + // Copy the existing v0 keyring fixture + let v0_secret = Secret::from("test"); + let fixture_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .join("client/fixtures/legacy.keyring"); + let v0_path = keyrings_dir.join("legacy.keyring"); + tokio::fs::copy(&fixture_path, &v0_path).await?; + + // Create a v1 keyring for mixed scenario + let v1_secret = Secret::from("v1-password"); + let v1_keyring = + UnlockedKeyring::open_at(temp_dir.path(), "modern", Some(v1_secret.clone())).await?; + v1_keyring + .create_item( + "V1 Item", + &[("type", "v1")], + Secret::text("v1-secret"), + false, + ) + .await?; + v1_keyring.write().await?; + + // Test 1: Discover without secret, v0 marked for migration, v1 locked + let discovered = service.discover_keyrings(None).await?; + assert_eq!( + discovered.len(), + 2, + "Should discover v1 keyring + v0 placeholder" + ); + + let pending = service.pending_migrations.lock().await; + assert_eq!(pending.len(), 1, "V0 should be pending migration"); + assert!(pending.contains_key("legacy")); + drop(pending); + + // Test 2: Discover with v0 secret, v0 migrated, v1 locked + service.pending_migrations.lock().await.clear(); + let discovered = service.discover_keyrings(Some(v0_secret.clone())).await?; + assert_eq!(discovered.len(), 2, "Should discover both keyrings"); + + let legacy = discovered.iter().find(|dk| dk.label == "Legacy").unwrap(); + assert!( + !legacy.keyring.is_locked(), + "V0 should be migrated and unlocked" + ); + assert_eq!( + service.pending_migrations.lock().await.len(), + 0, + "No pending after successful migration" + ); + + // Verify v1 file was created + let v1_migrated = temp_dir.path().join("keyrings/v1/legacy.keyring"); + assert!(v1_migrated.exists(), "V1 file should exist after migration"); + + // Test 3: Discover with wrong v0 secret, marked for pending migration + tokio::fs::remove_file(&v1_migrated).await?; + let _ = tokio::fs::remove_file(crate::migration::stamp_path(&v0_path)).await; + service.pending_migrations.lock().await.clear(); + + // Restore the v0 file for this test + tokio::fs::copy(&fixture_path, &v0_path).await?; + + let wrong_secret = Secret::from("wrong-password"); + let discovered = service.discover_keyrings(Some(wrong_secret)).await?; + assert_eq!( + discovered.len(), + 2, + "V1 + v0 placeholder should be discovered with wrong v0 password" + ); + assert_eq!( + service.pending_migrations.lock().await.len(), + 1, + "V0 should be pending with wrong password" + ); + + Ok(()) +} + +#[tokio::test] +async fn discover_plain_v0_keyrings() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let service = Service::new(temp_dir.path().to_path_buf(), None, true); + + let keyrings_dir = temp_dir.path().join("keyrings"); + tokio::fs::create_dir_all(keyrings_dir.join("v1")).await?; + + let fixture_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .join("client/fixtures/plain.keyring"); + let v0_path = keyrings_dir.join("plain.keyring"); + tokio::fs::copy(&fixture_path, &v0_path).await?; + // Not a keyring, should be skipped + tokio::fs::write(keyrings_dir.join("junk.keyring"), b"junk").await?; + + // Plain keyrings are migrated even without a secret + let discovered = service.discover_keyrings(None).await?; + assert_eq!(discovered.len(), 1, "Only the plain keyring is discovered"); + + assert_eq!(discovered[0].label, "Plain"); + assert!( + !discovered[0].keyring.is_locked(), + "Plain keyring should be migrated" + ); + assert!(service.pending_migrations.lock().await.is_empty()); + assert!(keyrings_dir.join("v1/plain.keyring").exists()); + assert!(crate::migration::stamp_path(&v0_path).exists()); + + Ok(()) +} + +// https://github.com/linux-credentials/oo7/issues/586 +#[tokio::test] +async fn migrate_v0_items_without_schema() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let service = Service::new(temp_dir.path().to_path_buf(), None, true); + + let keyrings_dir = temp_dir.path().join("keyrings"); + tokio::fs::create_dir_all(keyrings_dir.join("v1")).await?; + + // Its item only has a `unique` attribute and the generic secret type + let fixture_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .join("client/fixtures/legacy-no-schema.keyring"); + tokio::fs::copy(&fixture_path, keyrings_dir.join("login.keyring")).await?; + + let secret = Secret::from("test"); + service.discover_keyrings(Some(secret.clone())).await?; + + let keyring = UnlockedKeyring::open_at(temp_dir.path(), "login", Some(secret)).await?; + let items = keyring.items().await?; + assert_eq!(items.len(), 1); + let attributes = items[0].attributes(); + assert_eq!( + attributes + .get(oo7::XDG_SCHEMA_ATTRIBUTE) + .map(|v| v.as_ref()), + Some(oo7::GENERIC_SCHEMA) + ); + + Ok(()) +} + +#[cfg(feature = "kwallet_migration")] +#[cfg(target_endian = "little")] +#[tokio::test] +async fn discover_kwallet_keyrings() -> Result<(), Box> { + let temp_dir = tempfile::tempdir()?; + let service = Service::new(temp_dir.path().to_path_buf(), None, true); + + let kwallet_dir = temp_dir.path().join("kwalletd"); + let v1_dir = temp_dir.path().join("keyrings/v1"); + tokio::fs::create_dir_all(&kwallet_dir).await?; + tokio::fs::create_dir_all(&v1_dir).await?; + + // Copy KWallet test fixture + let kwallet_secret = Secret::from("password"); + let fixture_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .join("kwallet/parser/tests/blowfish_cbc_pbkdf2_sha512_manual.kwl"); + let kwallet_path = kwallet_dir.join("kdewallet.kwl"); + tokio::fs::copy(&fixture_path, &kwallet_path).await?; + + // Copy the salt file too (required for PBKDF2-SHA512) + let salt_fixture = fixture_path.with_extension("salt"); + let salt_path = kwallet_path.with_extension("salt"); + tokio::fs::copy(&salt_fixture, &salt_path).await?; + + // Create a v1 keyring for mixed scenario + let v1_secret = Secret::from("v1-password"); + let v1_keyring = + UnlockedKeyring::open_at(temp_dir.path(), "modern", Some(v1_secret.clone())).await?; + v1_keyring + .create_item( + "V1 Item", + &[("type", "v1")], + Secret::text("v1-secret"), + false, + ) + .await?; + v1_keyring.write().await?; + + // Test 1: Discover without secret, KWallet marked for migration, v1 locked + let discovered = service.discover_keyrings(None).await?; + assert_eq!( + discovered.len(), + 2, + "Should discover v1 keyring + kwallet placeholder" + ); + + let pending = service.pending_migrations.lock().await; + assert_eq!(pending.len(), 1, "KWallet should be pending migration"); + assert!(pending.contains_key("kdewallet")); + drop(pending); + + // Test 2: Discover with KWallet secret, KWallet migrated, v1 locked + service.pending_migrations.lock().await.clear(); + let discovered = service + .discover_keyrings(Some(kwallet_secret.clone())) + .await?; + assert_eq!(discovered.len(), 2, "Should discover both keyrings"); + + let kdewallet = discovered + .iter() + .find(|dk| dk.label == "Kdewallet") + .unwrap(); + assert!( + !kdewallet.keyring.is_locked(), + "KWallet should be migrated and unlocked" + ); + assert_eq!( + kdewallet.alias, "kdewallet", + "kdewallet should have kdewallet alias (not default)" + ); + assert_eq!( + service.pending_migrations.lock().await.len(), + 0, + "No pending after successful migration" + ); + + // Verify v1 file was created + let v1_migrated = temp_dir.path().join("keyrings/v1/kdewallet.keyring"); + assert!(v1_migrated.exists(), "V1 file should exist after migration"); + + // Verify old KWallet file still exists but stamp was created + assert!( + kwallet_path.exists(), + "Original .kwl file should still exist" + ); + assert!( + crate::migration::stamp_path(&kwallet_path).exists(), + "Migration stamp file should exist" + ); + + // Test 3: Discover with wrong KWallet secret, marked for pending migration + tokio::fs::remove_file(&v1_migrated).await?; + let _ = tokio::fs::remove_file(crate::migration::stamp_path(&kwallet_path)).await; + service.pending_migrations.lock().await.clear(); + + // Restore the KWallet files for this test + tokio::fs::copy(&fixture_path, &kwallet_path).await?; + tokio::fs::copy(&salt_fixture, &salt_path).await?; + + let wrong_secret = Secret::from("wrong-password"); + let discovered = service.discover_keyrings(Some(wrong_secret)).await?; + assert_eq!( + discovered.len(), + 2, + "V1 + kwallet placeholder should be discovered with wrong KWallet password" + ); + assert_eq!( + service.pending_migrations.lock().await.len(), + 1, + "KWallet should be pending with wrong password" + ); + + // Verify the pending migration has the correct type + let pending = service.pending_migrations.lock().await; + let migration = pending.get("kdewallet").unwrap(); + assert_eq!(migration.label(), "Kdewallet"); + assert_eq!(migration.alias(), "kdewallet"); + Ok(()) +} diff --git a/server/src/service/tests/locking.rs b/server/src/service/tests/locking.rs new file mode 100644 index 00000000..ff1e84ba --- /dev/null +++ b/server/src/service/tests/locking.rs @@ -0,0 +1,522 @@ +use std::collections::HashMap; + +use oo7::dbus; +use zbus::wire::ObjectPath; + +use super::super::*; +use crate::{prompt::MAX_UNLOCK_ATTEMPTS, tests::TestServiceSetup}; + +#[tokio::test] +async fn lock_unlock_edge_cases() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Unlock: empty object list + let items: Vec> = vec![]; + let unlocked = setup.service_api.unlock(&items, None).await?; + assert!(unlocked.is_empty(), "Should return empty for empty input"); + + // Lock: empty object list + let locked = setup.service_api.lock(&items, None).await?; + assert!(locked.is_empty(), "Should return empty for empty input"); + + // Shared fake objects for non-existent tests + let fake_collection = dbus::api::Collection::new( + &setup.client_conn, + "/org/freedesktop/secrets/collection/NonExistent", + ) + .await?; + + let fake_item = dbus::api::Item::new( + &setup.client_conn, + "/org/freedesktop/secrets/collection/Login/999", + ) + .await?; + + let fake_paths = [fake_collection.inner().path(), fake_item.inner().path()]; + + // Unlock: non-existent objects + let unlocked = setup.service_api.unlock(&fake_paths, None).await?; + assert!( + unlocked.is_empty(), + "Should have no unlocked objects for non-existent paths" + ); + + // Lock: non-existent objects + let locked = setup.service_api.lock(&fake_paths, None).await?; + assert!( + locked.is_empty(), + "Should have no locked objects for non-existent paths" + ); + + // Unlock: already unlocked item + let item = setup + .create_item("Test Item", &[("app", "test")], "test-password", false) + .await?; + + assert!(!item.is_locked().await?, "Item should be unlocked"); + + let unlocked = setup + .service_api + .unlock(&[item.inner().path()], None) + .await?; + + assert_eq!(unlocked.len(), 1, "Should return the already-unlocked item"); + assert_eq!( + unlocked[0].as_str(), + item.inner().path().as_str(), + "Should return the same item path" + ); + + // Unlock: already unlocked collection + assert!( + !setup.collections[0].is_locked().await?, + "Collection should be unlocked" + ); + + let unlocked = setup + .service_api + .unlock(&[setup.collections[0].inner().path()], None) + .await?; + + assert_eq!( + unlocked.len(), + 1, + "Should return the already-unlocked collection" + ); + + Ok(()) +} + +async fn unlock_collection_prompt_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + + // Lock the collection using server-side API + setup.lock_collection(&setup.collections[0]).await?; + + assert!( + setup.collections[0].is_locked().await?, + "Collection should be locked" + ); + + // Test 1: Unlock with accept + let unlocked = setup + .service_api + .unlock(&[setup.collections[0].inner().path()], None) + .await?; + + assert_eq!(unlocked.len(), 1, "Should have unlocked 1 collection"); + assert_eq!( + unlocked[0].as_str(), + setup.collections[0].inner().path().as_str(), + "Should return the collection path" + ); + assert!( + !setup.collections[0].is_locked().await?, + "Collection should be unlocked after accepting prompt" + ); + + // Lock the collection again for dismiss test + setup.lock_collection(&setup.collections[0]).await?; + assert!( + setup.collections[0].is_locked().await?, + "Collection should be locked again" + ); + + // Test 2: Unlock with dismiss + setup.set_password_accept(false).await; + let result = setup + .service_api + .unlock(&[setup.collections[0].inner().path()], None) + .await; + + assert!( + matches!(result, Err(oo7::dbus::Error::Dismissed)), + "Should return Dismissed error when prompt dismissed" + ); + assert!( + setup.collections[0].is_locked().await?, + "Collection should still be locked after dismissing prompt" + ); + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn unlock_collection_prompt_gnome() -> Result<(), Box> { + unlock_collection_prompt_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn unlock_collection_prompt_plasma() -> Result<(), Box> { + unlock_collection_prompt_impl(PrompterType::Plasma).await +} + +/// Clients like Chromium call Unlock and Prompt without opening a session. +async fn unlock_collection_prompt_without_session_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + setup.lock_collection(&setup.collections[0]).await?; + setup.session.close().await?; + + let unlocked = setup + .service_api + .unlock(&[setup.collections[0].inner().path()], None) + .await?; + + assert_eq!(unlocked.len(), 1, "Should have unlocked 1 collection"); + assert!( + !setup.collections[0].is_locked().await?, + "Collection should be unlocked after accepting prompt" + ); + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn unlock_collection_prompt_without_session_gnome() -> Result<(), Box> +{ + unlock_collection_prompt_without_session_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn unlock_collection_prompt_without_session_plasma() -> Result<(), Box> +{ + unlock_collection_prompt_without_session_impl(PrompterType::Plasma).await +} + +async fn unlock_item_prompt_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + + // Create an item + let dbus_secret = setup.create_dbus_secret("test-password")?; + let default_collection = setup.service_api.read_alias("default").await?.unwrap(); + let item = default_collection + .create_item("Test Item", &[("app", "test")], &dbus_secret, false, None) + .await?; + + // Lock the collection (which locks the item) + setup.lock_collection(&default_collection).await?; + + assert!( + item.is_locked().await?, + "Item should be locked when collection is locked" + ); + + // Test 1: Unlock with accept + let unlocked = setup + .service_api + .unlock(&[item.inner().path()], None) + .await?; + + assert_eq!(unlocked.len(), 1, "Should have unlocked 1 item"); + assert_eq!( + unlocked[0].as_str(), + item.inner().path().as_str(), + "Should return the item path" + ); + assert!( + !item.is_locked().await?, + "Item should be unlocked after accepting prompt" + ); + + // Lock the item again for dismiss test + setup.lock_collection(&default_collection).await?; + assert!(item.is_locked().await?, "Item should be locked again"); + + // Test 2: Unlock with dismiss + setup.set_password_accept(false).await; + let result = setup.service_api.unlock(&[item.inner().path()], None).await; + + assert!( + matches!(result, Err(oo7::dbus::Error::Dismissed)), + "Should return Dismissed error when prompt dismissed" + ); + assert!( + item.is_locked().await?, + "Item should still be locked after dismissing prompt" + ); + + Ok(()) +} + +#[tokio::test] +async fn lock_item_in_unlocked_collection() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Create an item (starts unlocked) + let item = setup + .create_item("Test Item", &[("app", "test")], "test-password", false) + .await?; + + assert!(!item.is_locked().await?, "Item should start unlocked"); + assert!( + !setup.collections[0].is_locked().await?, + "Collection should be unlocked" + ); + + // When collection is unlocked, locking an item should happen directly + // without a prompt + let locked = setup.service_api.lock(&[item.inner().path()], None).await?; + + assert_eq!(locked.len(), 1, "Should have locked 1 item"); + assert_eq!( + locked[0].as_str(), + item.inner().path().as_str(), + "Should return the item path" + ); + assert!(item.is_locked().await?, "Item should be locked directly"); + + // Unlock the item again (using service API to unlock just the item) + let unlocked = setup + .service_api + .unlock(&[item.inner().path()], None) + .await?; + assert_eq!(unlocked.len(), 1, "Should have unlocked 1 item"); + assert!(!item.is_locked().await?, "Item should be unlocked again"); + + // Locking again should work the same way (no prompt) + let locked = setup.service_api.lock(&[item.inner().path()], None).await?; + assert_eq!(locked.len(), 1, "Should have locked 1 item again"); + assert!(item.is_locked().await?, "Item should be locked again"); + + Ok(()) +} + +#[tokio::test] +async fn lock_collection_no_prompt() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Collection starts unlocked + assert!( + !setup.collections[0].is_locked().await?, + "Collection should start unlocked" + ); + + // Lock the collection + let locked = setup + .service_api + .lock(&[setup.collections[0].inner().path()], None) + .await?; + + assert_eq!(locked.len(), 1, "Should have locked 1 collection"); + assert_eq!( + locked[0].as_str(), + setup.collections[0].inner().path().as_str(), + "Should return the collection path" + ); + assert!( + setup.collections[0].is_locked().await?, + "Collection should be locked instantly" + ); + + // Unlock the collection + setup.unlock_collection(&setup.collections[0]).await?; + assert!( + !setup.collections[0].is_locked().await?, + "Collection should be unlocked" + ); + + // Lock again to verify it works multiple times + let locked = setup + .service_api + .lock(&[setup.collections[0].inner().path()], None) + .await?; + + assert_eq!(locked.len(), 1, "Should have locked 1 collection again"); + assert!( + setup.collections[0].is_locked().await?, + "Collection should be locked again" + ); + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn unlock_item_prompt_gnome() -> Result<(), Box> { + unlock_item_prompt_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn unlock_item_prompt_plasma() -> Result<(), Box> { + unlock_item_prompt_impl(PrompterType::Plasma).await +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn concurrent_unlock_creates_single_prompt_gnome() -> Result<(), Box> { + concurrent_unlock_creates_single_prompt_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn concurrent_unlock_creates_single_prompt_plasma() -> Result<(), Box> +{ + concurrent_unlock_creates_single_prompt_impl(PrompterType::Plasma).await +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn concurrent_item_unlock_creates_single_prompt_gnome() +-> Result<(), Box> { + concurrent_item_unlock_creates_single_prompt_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn concurrent_item_unlock_creates_single_prompt_plasma() +-> Result<(), Box> { + concurrent_item_unlock_creates_single_prompt_impl(PrompterType::Plasma).await +} + +async fn concurrent_item_unlock_creates_single_prompt_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + + let collection = &setup.collections[0]; + let dbus_secret = setup.create_dbus_secret("item-secret")?; + let item = collection + .create_item( + "test-item", + &HashMap::from([("app", "test")]), + &dbus_secret, + false, + None, + ) + .await?; + + setup.lock_collection(collection).await?; + assert!(collection.is_locked().await?); + + let secret = setup.keyring_secret.clone().unwrap(); + setup + .set_password_queue(vec![secret.clone(), secret.clone(), secret]) + .await; + + let item_path = item.inner().path().to_owned(); + let paths1 = [item_path.clone()]; + let paths2 = [item_path]; + let (r1, r2) = tokio::join!( + setup.service_api.unlock(&paths1, None), + setup.service_api.unlock(&paths2, None), + ); + + let _unlocked1 = r1?; + let _unlocked2 = r2?; + + assert!( + !collection.is_locked().await?, + "Collection should be unlocked after concurrent item unlock requests" + ); + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn unlock_wrong_password_dismissed_gnome() -> Result<(), Box> { + unlock_wrong_password_dismissed_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn unlock_wrong_password_dismissed_plasma() -> Result<(), Box> { + unlock_wrong_password_dismissed_impl(PrompterType::Plasma).await +} + +async fn unlock_wrong_password_dismissed_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + + let collection = &setup.collections[0]; + let dbus_secret = setup.create_dbus_secret("item-secret")?; + collection + .create_item( + "test-item", + &HashMap::from([("app", "test")]), + &dbus_secret, + false, + None, + ) + .await?; + + setup.lock_collection(collection).await?; + assert!(collection.is_locked().await?); + + let wrong = oo7::Secret::from("wrong-password-intentionally"); + setup + .set_password_queue(vec![wrong; MAX_UNLOCK_ATTEMPTS as usize + 1]) + .await; + + let collection_path = collection.inner().path().to_owned(); + let result = setup.service_api.unlock(&[collection_path], None).await; + + assert!( + matches!(result, Err(dbus::Error::Dismissed)), + "Expected Dismissed error after max failed attempts, got: {result:?}" + ); + + assert!( + collection.is_locked().await?, + "Collection should remain locked after failed unlock attempts" + ); + + Ok(()) +} + +async fn concurrent_unlock_creates_single_prompt_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + + let collection = &setup.collections[0]; + + // Lock the collection + setup.lock_collection(collection).await?; + assert!(collection.is_locked().await?); + + // Queue enough passwords for however many prompts get created + let secret = setup.keyring_secret.clone().unwrap(); + setup + .set_password_queue(vec![secret.clone(), secret.clone(), secret]) + .await; + + // Fire two Unlock calls concurrently for the same collection. + let collection_path = collection.inner().path().to_owned(); + let paths1 = [collection_path.clone()]; + let paths2 = [collection_path]; + let (r1, r2) = tokio::join!( + setup.service_api.unlock(&paths1, None), + setup.service_api.unlock(&paths2, None), + ); + + // Both should succeed (not panic the daemon). + let _unlocked1 = r1?; + let _unlocked2 = r2?; + + // The collection should be unlocked. + assert!( + !collection.is_locked().await?, + "Collection should be unlocked after concurrent requests" + ); + + Ok(()) +} diff --git a/server/src/service/tests/mod.rs b/server/src/service/tests/mod.rs new file mode 100644 index 00000000..b5b987d1 --- /dev/null +++ b/server/src/service/tests/mod.rs @@ -0,0 +1,7 @@ +mod alias; +mod collection; +mod discovery; +mod locking; +mod search; +mod secrets; +mod session; diff --git a/server/src/service/tests/search.rs b/server/src/service/tests/search.rs new file mode 100644 index 00000000..85510b58 --- /dev/null +++ b/server/src/service/tests/search.rs @@ -0,0 +1,197 @@ +use std::collections::HashMap; + +use crate::tests::TestServiceSetup; + +#[tokio::test] +async fn search_items() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Search for items (should return empty initially) + let (unlocked, locked) = setup + .service_api + .search_items(&[("application", "test-app")]) + .await?; + + assert!( + unlocked.is_empty(), + "Should have no unlocked items initially" + ); + assert!(locked.is_empty(), "Should have no locked items initially"); + + // Search with empty attributes - edge case + let attributes: HashMap<&str, &str> = HashMap::default(); + let (unlocked, locked) = setup.service_api.search_items(&attributes).await?; + + assert!( + locked.is_empty(), + "Should have no locked items with empty search" + ); + assert!( + unlocked.is_empty(), + "Should have no unlocked items with empty search" + ); + + // Test with both locked and unlocked items + // Create items in default collection (unlocked) + setup + .create_item("Unlocked Item", &[("app", "testapp")], "password1", false) + .await?; + + // Create item in default collection and lock it + let locked_item = setup + .create_item("Locked Item", &[("app", "testapp")], "password2", false) + .await?; + + // Lock just this item (not the whole collection) + setup.lock_item(&locked_item).await?; + + // Search for items with the shared attribute + let (unlocked, locked) = setup + .service_api + .search_items(&[("app", "testapp")]) + .await?; + + assert_eq!(unlocked.len(), 1, "Should find 1 unlocked item"); + assert_eq!(locked.len(), 1, "Should find 1 locked item"); + + Ok(()) +} + +#[tokio::test] +async fn search_items_with_results() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Create items in default collection + setup + .create_item( + "Firefox Login", + &[("application", "firefox"), ("type", "login")], + "password1", + false, + ) + .await?; + + setup + .create_item( + "Chrome Login", + &[("application", "chrome"), ("type", "login")], + "password2", + false, + ) + .await?; + + // Create item in session collection + let dbus_secret3 = setup.create_dbus_secret("password3")?; + + setup.collections[1] + .create_item( + "Session Item", + &[("application", "firefox"), ("type", "session")], + &dbus_secret3, + false, + None, + ) + .await?; + + // Search for all firefox items + let (unlocked, locked) = setup + .service_api + .search_items(&[("application", "firefox")]) + .await?; + + assert_eq!(unlocked.len(), 2, "Should find 2 firefox items"); + assert!(locked.is_empty(), "Should have no locked items"); + + // Search for login type items + let (unlocked, locked) = setup.service_api.search_items(&[("type", "login")]).await?; + + assert_eq!(unlocked.len(), 2, "Should find 2 login items"); + assert!(locked.is_empty(), "Should have no locked items"); + + // Search for chrome items + let (unlocked, locked) = setup + .service_api + .search_items(&[("application", "chrome")]) + .await?; + + assert_eq!(unlocked.len(), 1, "Should find 1 chrome item"); + assert!(locked.is_empty(), "Should have no locked items"); + + // Search for non-existent + let (unlocked, locked) = setup + .service_api + .search_items(&[("application", "nonexistent")]) + .await?; + + assert!(unlocked.is_empty(), "Should find no items"); + assert!(locked.is_empty(), "Should have no locked items"); + + Ok(()) +} + +// Reproducer for https://github.com/linux-credentials/oo7/issues/586 +#[tokio::test] +async fn search_items_missing_xdg_schema() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Item without xdg:schema, as found in old gnome-keyring migrations. + setup + .create_item( + "Unlock password for: user@example.com", + &[("unique", "ssh-store:/home/user/.ssh/id_rsa")], + "my-ssh-passphrase", + false, + ) + .await?; + + // gcr searches with xdg:schema via libsecret's SECRET_SCHEMA_NONE. + let (unlocked, locked) = setup + .service_api + .search_items(&[ + ("unique", "ssh-store:/home/user/.ssh/id_rsa"), + (oo7::XDG_SCHEMA_ATTRIBUTE, oo7::GENERIC_SCHEMA), + ]) + .await?; + + assert_eq!(unlocked.len(), 1); + assert!(locked.is_empty()); + + Ok(()) +} + +// gcr stores the passphrase again with its schema, which must replace the +// item migrated without one instead of duplicating it. +#[tokio::test] +async fn replace_item_missing_xdg_schema() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + let unique = ("unique", "ssh-store:/home/user/.ssh/id_rsa"); + + setup + .create_item("Unlock password", &[unique], "old-passphrase", false) + .await?; + setup + .create_item( + "Unlock password", + &[unique, (oo7::XDG_SCHEMA_ATTRIBUTE, oo7::GENERIC_SCHEMA)], + "new-passphrase", + true, + ) + .await?; + + let items = setup.collections[0].items().await?; + assert_eq!(items.len(), 1); + assert_eq!( + items[0].attributes().await?.get(oo7::XDG_SCHEMA_ATTRIBUTE), + Some(&oo7::GENERIC_SCHEMA.to_owned()) + ); + + let server_collection = setup + .server + .collection_from_path(setup.collections[0].inner().path()) + .await + .unwrap(); + let keyring = server_collection.keyring.read().await; + assert_eq!(keyring.as_ref().unwrap().items().await?.len(), 1); + + Ok(()) +} diff --git a/server/src/service/tests/secrets.rs b/server/src/service/tests/secrets.rs new file mode 100644 index 00000000..830646b2 --- /dev/null +++ b/server/src/service/tests/secrets.rs @@ -0,0 +1,168 @@ +use oo7::{Secret, dbus}; + +use crate::tests::TestServiceSetup; + +#[tokio::test] +async fn get_secrets() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Test with empty items list - edge case + #[allow(clippy::mutable_key_type)] + let secrets = setup.service_api.secrets(&[], &setup.session).await?; + assert!( + secrets.is_empty(), + "Should return empty secrets for empty items list" + ); + + // Create two items with different secrets + let secret1 = Secret::text("password1"); + let item1 = setup + .create_item("Item 1", &[("app", "test1")], secret1.clone(), false) + .await?; + + let secret2 = Secret::text("password2"); + let item2 = setup + .create_item("Item 2", &[("app", "test2")], secret2.clone(), false) + .await?; + + // Get secrets for both items + let item_paths = vec![item1.clone(), item2.clone()]; + #[allow(clippy::mutable_key_type)] + let secrets = setup + .service_api + .secrets(&item_paths, &setup.session) + .await?; + + // Should have both secrets + assert_eq!(secrets.len(), 2, "Should retrieve both secrets"); + + // Verify first secret + let retrieved_secret1 = secrets.get(&item1).unwrap(); + assert_eq!(retrieved_secret1.value(), secret1.as_bytes()); + + // Verify second secret + let retrieved_secret2 = secrets.get(&item2).unwrap(); + assert_eq!(retrieved_secret2.value(), secret2.as_bytes()); + + Ok(()) +} + +#[tokio::test] +async fn get_secrets_multiple_collections() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Should have 2 collections: default (Login) and session + assert_eq!(setup.collections.len(), 2); + + // Create item in default collection (index 0) + let secret1 = Secret::text("default-password"); + let item1 = setup + .create_item( + "Default Item", + &[("app", "default-app")], + secret1.clone(), + false, + ) + .await?; + + // Create item in session collection (index 1) + let secret2 = Secret::text("session-password"); + let dbus_secret2 = setup.create_dbus_secret(secret2.clone())?; + + let item2 = setup.collections[1] + .create_item( + "Session Item", + &[("app", "session-app")], + &dbus_secret2, + false, + None, + ) + .await?; + + // Get secrets for both items from different collections + let item_paths = vec![item1.clone(), item2.clone()]; + #[allow(clippy::mutable_key_type)] + let secrets = setup + .service_api + .secrets(&item_paths, &setup.session) + .await?; + + // Should have both secrets + assert_eq!( + secrets.len(), + 2, + "Should retrieve secrets from both collections" + ); + + // Verify default collection secret + let retrieved_secret1 = secrets.get(&item1).unwrap(); + assert_eq!(retrieved_secret1.value(), secret1.as_bytes()); + + // Verify session collection secret + let retrieved_secret2 = secrets.get(&item2).unwrap(); + assert_eq!(retrieved_secret2.value(), secret2.as_bytes()); + + Ok(()) +} + +#[tokio::test] +async fn get_secrets_invalid_session() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Create an item + let item = setup + .create_item("Test Item", &[("app", "test")], "test-password", false) + .await?; + + // Try to get secrets with invalid session path + let invalid_session = + dbus::api::Session::new(&setup.client_conn, "/invalid/session/path").await?; + let result = setup.service_api.secrets(&[item], &invalid_session).await; + + assert!( + matches!( + result, + Err(oo7::dbus::Error::Service( + oo7::dbus::ServiceError::NoSession(_) + )) + ), + "Should be NoSession error" + ); + + Ok(()) +} + +#[tokio::test] +async fn get_secrets_with_non_existent_items() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Create one real item + let item1 = setup + .create_item("Item 1", &[("app", "test")], "password1", false) + .await?; + + // Create a fake item path that doesn't exist + let fake_item = dbus::api::Item::new( + &setup.client_conn, + "/org/freedesktop/secrets/collection/Login/999", + ) + .await?; + + // Request secrets for both real and fake items + let item_paths = vec![item1.clone(), fake_item]; + #[allow(clippy::mutable_key_type)] + let secrets = setup + .service_api + .secrets(&item_paths, &setup.session) + .await?; + + // Should only get the secret for the real item + assert_eq!( + secrets.len(), + 1, + "Should only retrieve secret for existing item" + ); + assert!(secrets.contains_key(&item1), "Should have item1 secret"); + + Ok(()) +} diff --git a/server/src/service/tests/session.rs b/server/src/service/tests/session.rs new file mode 100644 index 00000000..dbc489c2 --- /dev/null +++ b/server/src/service/tests/session.rs @@ -0,0 +1,44 @@ +use crate::tests::TestServiceSetup; + +#[tokio::test] +async fn open_session_plain() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + assert!( + setup.aes_key.is_none(), + "Plain session should not have AES key" + ); + + // Should have 2 collections: default + session + assert_eq!( + setup.collections.len(), + 2, + "Expected default and session collections" + ); + Ok(()) +} + +#[tokio::test] +async fn open_session_encrypted() -> Result<(), Box> { + let setup = TestServiceSetup::encrypted_session(false).await?; + assert!( + setup.server_public_key.is_some(), + "Encrypted session should have server public key" + ); + let key = setup.aes_key.as_deref().unwrap(); + assert_eq!(key.as_ref().len(), 16, "AES key should be 16 bytes"); + Ok(()) +} + +#[tokio::test] +async fn session_collection_only() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(false).await?; + + // Should have only session collection (no default) + assert_eq!( + setup.collections.len(), + 1, + "Should have exactly one collection" + ); + Ok(()) +} From 66a725572f5545bb84ac657968ed227349903060 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Wed, 11 Nov 2026 15:54:04 +0100 Subject: [PATCH 07/12] server: Merge redundant collection signal tests --- server/src/collection/tests.rs | 105 +++++++++++---------------------- 1 file changed, 36 insertions(+), 69 deletions(-) diff --git a/server/src/collection/tests.rs b/server/src/collection/tests.rs index ea5336c3..28819996 100644 --- a/server/src/collection/tests.rs +++ b/server/src/collection/tests.rs @@ -20,6 +20,10 @@ async fn create_item_plain() -> Result<(), Box> { // Wait to ensure timestamp will be different tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + // Subscribe to ItemCreated signal before creating + let signal_stream = setup.collections[0].receive_item_created().await?; + tokio::pin!(signal_stream); + // Create an item let item = setup .create_item( @@ -30,6 +34,14 @@ async fn create_item_plain() -> Result<(), Box> { ) .await?; + // Verify ItemCreated signal was emitted + let signal_item = assert_next_signal(&mut signal_stream).await; + assert_eq!( + signal_item.inner().path().as_str(), + item.inner().path().as_str(), + "Signal should contain the created item path" + ); + // Verify item exists in collection let items = setup.collections[0].items().await?; assert_eq!(items.len(), 1, "Collection should have one item"); @@ -337,9 +349,21 @@ async fn label_property() -> Result<(), Box> { // Wait to ensure timestamp will be different tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + // Subscribe to CollectionChanged signal before changing label + let signal_stream = setup.service_api.receive_collection_changed().await?; + tokio::pin!(signal_stream); + // Set new label login_collection.set_label("My Custom Collection").await?; + // Verify CollectionChanged signal was emitted + let signal_collection = assert_next_signal(&mut signal_stream).await; + assert_eq!( + signal_collection.inner().path().as_str(), + login_collection.inner().path().as_str(), + "Signal should contain the changed collection path" + ); + // Verify new label let label = login_collection.label().await?; assert_eq!(label, "My Custom Collection"); @@ -410,29 +434,6 @@ async fn create_item_invalid_session() -> Result<(), Box> Ok(()) } -#[tokio::test] -async fn item_created_signal() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Subscribe to ItemCreated signal - let signal_stream = setup.collections[0].receive_item_created().await?; - tokio::pin!(signal_stream); - - // Create an item - let item = setup - .create_item("Test Item", &[("app", "test")], "test-secret", false) - .await?; - - let signal_item = assert_next_signal(&mut signal_stream).await; - assert_eq!( - signal_item.inner().path().as_str(), - item.inner().path().as_str(), - "Signal should contain the created item path" - ); - - Ok(()) -} - #[tokio::test] async fn item_deleted_signal() -> Result<(), Box> { let setup = TestServiceSetup::plain_session(true).await?; @@ -461,29 +462,6 @@ async fn item_deleted_signal() -> Result<(), Box> { Ok(()) } -#[tokio::test] -async fn collection_changed_signal() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Subscribe to CollectionChanged signal - let signal_stream = setup.service_api.receive_collection_changed().await?; - tokio::pin!(signal_stream); - - // Change the collection label - setup.collections[0] - .set_label("Updated Collection Label") - .await?; - - let signal_collection = assert_next_signal(&mut signal_stream).await; - assert_eq!( - signal_collection.inner().path().as_str(), - setup.collections[0].inner().path().as_str(), - "Signal should contain the changed collection path" - ); - - Ok(()) -} - #[tokio::test] async fn delete_collection() -> Result<(), Box> { let setup = TestServiceSetup::plain_session(true).await?; @@ -508,9 +486,21 @@ async fn delete_collection() -> Result<(), Box> { let collections_before = setup.service_api.collections().await?; let initial_count = collections_before.len(); + // Subscribe to CollectionDeleted signal before deleting + let signal_stream = setup.service_api.receive_collection_deleted().await?; + tokio::pin!(signal_stream); + // Delete the collection setup.collections[0].delete(None).await?; + // Verify CollectionDeleted signal was emitted + let signal_collection = assert_next_signal(&mut signal_stream).await; + assert_eq!( + signal_collection.as_str(), + collection_path.as_str(), + "Signal should contain the deleted collection path" + ); + // Give the system a moment to process the deletion tokio::time::sleep(tokio::time::Duration::from_millis(50)).await; @@ -535,29 +525,6 @@ async fn delete_collection() -> Result<(), Box> { Ok(()) } -#[tokio::test] -async fn collection_deleted_signal() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Subscribe to CollectionDeleted signal - let signal_stream = setup.service_api.receive_collection_deleted().await?; - tokio::pin!(signal_stream); - - let collection_path = setup.collections[0].inner().path().to_owned(); - - // Delete the collection - setup.collections[0].delete(None).await?; - - let signal_collection = assert_next_signal(&mut signal_stream).await; - assert_eq!( - signal_collection.as_str(), - collection_path.as_str(), - "Signal should contain the deleted collection path" - ); - - Ok(()) -} - async fn create_item_in_locked_collection_impl( prompter_type: PrompterType, ) -> Result<(), Box> { From 5382bc77711dc2294d5856d5ed08facd80424aeb Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Wed, 11 Nov 2026 16:29:51 +0100 Subject: [PATCH 08/12] server: Split collection tests into per-area modules --- server/src/collection/tests/deletion.rs | 126 ++++++ .../collection/{tests.rs => tests/items.rs} | 419 ------------------ server/src/collection/tests/locking.rs | 99 +++++ server/src/collection/tests/mod.rs | 5 + server/src/collection/tests/properties.rs | 85 ++++ server/src/collection/tests/search.rs | 116 +++++ 6 files changed, 431 insertions(+), 419 deletions(-) create mode 100644 server/src/collection/tests/deletion.rs rename server/src/collection/{tests.rs => tests/items.rs} (52%) create mode 100644 server/src/collection/tests/locking.rs create mode 100644 server/src/collection/tests/mod.rs create mode 100644 server/src/collection/tests/properties.rs create mode 100644 server/src/collection/tests/search.rs diff --git a/server/src/collection/tests/deletion.rs b/server/src/collection/tests/deletion.rs new file mode 100644 index 00000000..fa79e7de --- /dev/null +++ b/server/src/collection/tests/deletion.rs @@ -0,0 +1,126 @@ +use crate::{ + service::PrompterType, + tests::{TestServiceSetup, assert_next_signal}, +}; + +#[tokio::test] +async fn delete_collection() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Create some items in the collection + setup + .create_item("Item 1", &[("app", "test")], "password1", false) + .await?; + + setup + .create_item("Item 2", &[("app", "test")], "password2", false) + .await?; + + // Verify items were created + let items = setup.collections[0].items().await?; + assert_eq!(items.len(), 2, "Should have 2 items before deletion"); + + // Get collection path for later verification + let collection_path = setup.collections[0].inner().path().to_owned(); + + // Verify collection exists in service + let collections_before = setup.service_api.collections().await?; + let initial_count = collections_before.len(); + + // Subscribe to CollectionDeleted signal before deleting + let signal_stream = setup.service_api.receive_collection_deleted().await?; + tokio::pin!(signal_stream); + + // Delete the collection + setup.collections[0].delete(None).await?; + + // Verify CollectionDeleted signal was emitted + let signal_collection = assert_next_signal(&mut signal_stream).await; + assert_eq!( + signal_collection.as_str(), + collection_path.as_str(), + "Signal should contain the deleted collection path" + ); + + // Give the system a moment to process the deletion + tokio::time::sleep(tokio::time::Duration::from_millis(50)).await; + + // Verify collection is no longer in service's collection list + let collections_after = setup.service_api.collections().await?; + assert_eq!( + collections_after.len(), + initial_count - 1, + "Service should have one less collection after deletion" + ); + + // Verify the specific collection is not in the list + let collection_paths: Vec<_> = collections_after + .iter() + .map(|c| c.inner().path().as_str()) + .collect(); + assert!( + !collection_paths.contains(&collection_path.as_str()), + "Deleted collection should not be in service collections list" + ); + + Ok(()) +} + +async fn delete_locked_collection_with_prompt_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + let default_collection = &setup.collections[0]; + + setup.lock_collection(default_collection).await?; + + assert!( + default_collection.is_locked().await?, + "Collection should be locked" + ); + + let collection_path = default_collection.inner().path().to_owned(); + + // Get initial collection count + let collections_before = setup.service_api.collections().await?; + let initial_count = collections_before.len(); + + // Delete the locked collection + default_collection.delete(None).await?; + + // Give the system a moment to process the deletion + tokio::time::sleep(tokio::time::Duration::from_millis(50)).await; + + // Verify collection was deleted + let collections_after = setup.service_api.collections().await?; + assert_eq!( + collections_after.len(), + initial_count - 1, + "Collection should be deleted after prompt" + ); + + // Verify the specific collection is not in the list + let collection_paths: Vec<_> = collections_after + .iter() + .map(|c| c.inner().path().as_str()) + .collect(); + assert!( + !collection_paths.contains(&collection_path.as_str()), + "Deleted collection should not be in service collections list" + ); + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn delete_locked_collection_with_prompt_gnome() -> Result<(), Box> { + delete_locked_collection_with_prompt_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn delete_locked_collection_with_prompt_plasma() -> Result<(), Box> { + delete_locked_collection_with_prompt_impl(PrompterType::Plasma).await +} diff --git a/server/src/collection/tests.rs b/server/src/collection/tests/items.rs similarity index 52% rename from server/src/collection/tests.rs rename to server/src/collection/tests/items.rs index 28819996..b5a767b4 100644 --- a/server/src/collection/tests.rs +++ b/server/src/collection/tests/items.rs @@ -84,121 +84,6 @@ async fn create_item_encrypted() -> Result<(), Box> { Ok(()) } -#[tokio::test] -async fn search_items_after_creation() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Create two items with different attributes - setup - .create_item( - "Firefox Password", - &[("application", "firefox"), ("username", "user1")], - "password1", - false, - ) - .await?; - - setup - .create_item( - "Chrome Password", - &[("application", "chrome"), ("username", "user2")], - "password2", - false, - ) - .await?; - - // Search for firefox item - let firefox_attrs = &[("application", "firefox")]; - let firefox_items = setup.collections[0].search_items(firefox_attrs).await?; - - assert_eq!(firefox_items.len(), 1, "Should find one firefox item"); - - // Search for chrome item - let chrome_items = setup.collections[0] - .search_items(&[("application", "chrome")]) - .await?; - - assert_eq!(chrome_items.len(), 1, "Should find one chrome item"); - - // Search for non-existent item - let nonexistent_items = setup.collections[0] - .search_items(&[("application", "nonexistent")]) - .await?; - - assert_eq!( - nonexistent_items.len(), - 0, - "Should find no nonexistent items" - ); - - Ok(()) -} - -#[tokio::test] -async fn search_items_subset_matching() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Create an item with multiple attributes (url and username) - setup - .create_item( - "Zed Login", - &[("url", "https://zed.dev"), ("username", "alice")], - "my-password", - false, - ) - .await?; - - // Search with only the url attribute (subset of stored attributes) - let results = setup.collections[0] - .search_items(&[("url", "https://zed.dev")]) - .await?; - - assert_eq!( - results.len(), - 1, - "Should find item when searching with subset of its attributes" - ); - - // Search with only the username attribute (another subset) - let results = setup.collections[0] - .search_items(&[("username", "alice")]) - .await?; - - assert_eq!( - results.len(), - 1, - "Should find item when searching with different subset of its attributes" - ); - - // Search with both attributes (exact match) - let results = setup.collections[0] - .search_items(&[("url", "https://zed.dev"), ("username", "alice")]) - .await?; - - assert_eq!( - results.len(), - 1, - "Should find item when searching with all its attributes" - ); - - // Search with superset of attributes (should not match) - let results = setup.collections[0] - .search_items(&[ - ("url", "https://zed.dev"), - ("username", "alice"), - ("extra", "attribute"), - ]) - .await?; - - assert_eq!( - results.len(), - 0, - "Should not find item when searching with superset of its attributes" - ); - - Ok(()) -} - #[tokio::test] async fn create_item_with_replace() -> Result<(), Box> { let setup = TestServiceSetup::plain_session(true).await?; @@ -328,79 +213,6 @@ async fn create_item_with_replace_matches_attributes() -> Result<(), Box Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Get the Login collection via alias (don't rely on collection ordering) - let login_collection = setup - .service_api - .read_alias("default") - .await? - .expect("Default collection should exist"); - - // Get initial label (should be "Login" for default collection) - let label = login_collection.label().await?; - assert_eq!(label, "Login"); - - // Get initial modified timestamp - let initial_modified = login_collection.modified().await?; - - // Wait to ensure timestamp will be different - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; - - // Subscribe to CollectionChanged signal before changing label - let signal_stream = setup.service_api.receive_collection_changed().await?; - tokio::pin!(signal_stream); - - // Set new label - login_collection.set_label("My Custom Collection").await?; - - // Verify CollectionChanged signal was emitted - let signal_collection = assert_next_signal(&mut signal_stream).await; - assert_eq!( - signal_collection.inner().path().as_str(), - login_collection.inner().path().as_str(), - "Signal should contain the changed collection path" - ); - - // Verify new label - let label = login_collection.label().await?; - assert_eq!(label, "My Custom Collection"); - - // Verify modified timestamp was updated - let new_modified = login_collection.modified().await?; - assert!( - new_modified > initial_modified, - "Modified timestamp should be updated after label change" - ); - - Ok(()) -} - -#[tokio::test] -async fn timestamps() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Get created timestamp - let created = setup.collections[0].created().await?; - assert!(created.as_secs() > 0, "Created timestamp should be set"); - - // Get modified timestamp - let modified = setup.collections[0].modified().await?; - assert!(modified.as_secs() > 0, "Modified timestamp should be set"); - - // Created and modified should be close (within a second for new collection) - let diff = if created > modified { - created.as_secs() - modified.as_secs() - } else { - modified.as_secs() - created.as_secs() - }; - assert!(diff <= 1, "Created and modified should be within 1 second"); - - Ok(()) -} - #[tokio::test] async fn create_item_invalid_session() -> Result<(), Box> { let setup = TestServiceSetup::plain_session(true).await?; @@ -462,69 +274,6 @@ async fn item_deleted_signal() -> Result<(), Box> { Ok(()) } -#[tokio::test] -async fn delete_collection() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Create some items in the collection - setup - .create_item("Item 1", &[("app", "test")], "password1", false) - .await?; - - setup - .create_item("Item 2", &[("app", "test")], "password2", false) - .await?; - - // Verify items were created - let items = setup.collections[0].items().await?; - assert_eq!(items.len(), 2, "Should have 2 items before deletion"); - - // Get collection path for later verification - let collection_path = setup.collections[0].inner().path().to_owned(); - - // Verify collection exists in service - let collections_before = setup.service_api.collections().await?; - let initial_count = collections_before.len(); - - // Subscribe to CollectionDeleted signal before deleting - let signal_stream = setup.service_api.receive_collection_deleted().await?; - tokio::pin!(signal_stream); - - // Delete the collection - setup.collections[0].delete(None).await?; - - // Verify CollectionDeleted signal was emitted - let signal_collection = assert_next_signal(&mut signal_stream).await; - assert_eq!( - signal_collection.as_str(), - collection_path.as_str(), - "Signal should contain the deleted collection path" - ); - - // Give the system a moment to process the deletion - tokio::time::sleep(tokio::time::Duration::from_millis(50)).await; - - // Verify collection is no longer in service's collection list - let collections_after = setup.service_api.collections().await?; - assert_eq!( - collections_after.len(), - initial_count - 1, - "Service should have one less collection after deletion" - ); - - // Verify the specific collection is not in the list - let collection_paths: Vec<_> = collections_after - .iter() - .map(|c| c.inner().path().as_str()) - .collect(); - assert!( - !collection_paths.contains(&collection_path.as_str()), - "Deleted collection should not be in service collections list" - ); - - Ok(()) -} - async fn create_item_in_locked_collection_impl( prompter_type: PrompterType, ) -> Result<(), Box> { @@ -586,163 +335,6 @@ async fn create_item_in_locked_collection_plasma() -> Result<(), Box Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - let default_collection = &setup.collections[0]; - - setup.lock_collection(default_collection).await?; - - assert!( - default_collection.is_locked().await?, - "Collection should be locked" - ); - - let collection_path = default_collection.inner().path().to_owned(); - - // Get initial collection count - let collections_before = setup.service_api.collections().await?; - let initial_count = collections_before.len(); - - // Delete the locked collection - default_collection.delete(None).await?; - - // Give the system a moment to process the deletion - tokio::time::sleep(tokio::time::Duration::from_millis(50)).await; - - // Verify collection was deleted - let collections_after = setup.service_api.collections().await?; - assert_eq!( - collections_after.len(), - initial_count - 1, - "Collection should be deleted after prompt" - ); - - // Verify the specific collection is not in the list - let collection_paths: Vec<_> = collections_after - .iter() - .map(|c| c.inner().path().as_str()) - .collect(); - assert!( - !collection_paths.contains(&collection_path.as_str()), - "Deleted collection should not be in service collections list" - ); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn delete_locked_collection_with_prompt_gnome() -> Result<(), Box> { - delete_locked_collection_with_prompt_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn delete_locked_collection_with_prompt_plasma() -> Result<(), Box> { - delete_locked_collection_with_prompt_impl(PrompterType::Plasma).await -} - -async fn unlock_retry_impl(prompter_type: PrompterType) -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - let default_collection = &setup.collections[0]; - - let dbus_secret = setup.create_dbus_secret("test-secret-data")?; - default_collection - .create_item("Test Item", &[("app", "test")], &dbus_secret, false, None) - .await?; - - setup.lock_collection(default_collection).await?; - - assert!( - default_collection.is_locked().await?, - "Collection should be locked" - ); - - setup - .set_password_queue(vec![ - oo7::Secret::from("wrong-password"), - oo7::Secret::from("wrong-password2"), - oo7::Secret::from("test-password-long-enough"), - ]) - .await; - - let unlocked = setup - .service_api - .unlock(&[default_collection.inner().path()], None) - .await?; - - assert_eq!(unlocked.len(), 1, "Should have unlocked 1 collection"); - assert_eq!( - unlocked[0].as_str(), - default_collection.inner().path().as_str(), - "Should return the collection path" - ); - assert!( - !default_collection.is_locked().await?, - "Collection should be unlocked after retry with correct password" - ); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn unlock_retry_gnome() -> Result<(), Box> { - unlock_retry_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn unlock_retry_plasma() -> Result<(), Box> { - unlock_retry_impl(PrompterType::Plasma).await -} - -#[tokio::test] -async fn locked_collection_operations() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Verify collection is unlocked initially - assert!( - !setup.collections[0].is_locked().await?, - "Collection should start unlocked" - ); - - // Lock the collection - setup.lock_collection(&setup.collections[0]).await?; - - // Verify collection is now locked - assert!( - setup.collections[0].is_locked().await?, - "Collection should be locked" - ); - - // Test 1: set_label should fail with IsLocked - let result = setup.collections[0].set_label("New Label").await; - assert!( - matches!(result, Err(oo7::dbus::Error::ZBus(zbus::Error::FDO(_)))), - "set_label should fail with IsLocked error, got: {:?}", - result - ); - - // Verify read-only operations still work on locked collections - assert!( - setup.collections[0].label().await.is_ok(), - "Should be able to read label of locked collection" - ); - - let items = setup.collections[0].items().await?; - assert!( - items.is_empty(), - "Should be able to read items (empty) from locked collection" - ); - - Ok(()) -} - // https://github.com/linux-credentials/oo7/issues/652 #[tokio::test] async fn concurrent_replace_and_lookup() -> Result<(), Box> { @@ -873,14 +465,3 @@ async fn concurrent_replace_and_lookup() -> Result<(), Box Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + let default_collection = &setup.collections[0]; + + let dbus_secret = setup.create_dbus_secret("test-secret-data")?; + default_collection + .create_item("Test Item", &[("app", "test")], &dbus_secret, false, None) + .await?; + + setup.lock_collection(default_collection).await?; + + assert!( + default_collection.is_locked().await?, + "Collection should be locked" + ); + + setup + .set_password_queue(vec![ + oo7::Secret::from("wrong-password"), + oo7::Secret::from("wrong-password2"), + oo7::Secret::from("test-password-long-enough"), + ]) + .await; + + let unlocked = setup + .service_api + .unlock(&[default_collection.inner().path()], None) + .await?; + + assert_eq!(unlocked.len(), 1, "Should have unlocked 1 collection"); + assert_eq!( + unlocked[0].as_str(), + default_collection.inner().path().as_str(), + "Should return the collection path" + ); + assert!( + !default_collection.is_locked().await?, + "Collection should be unlocked after retry with correct password" + ); + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn unlock_retry_gnome() -> Result<(), Box> { + unlock_retry_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn unlock_retry_plasma() -> Result<(), Box> { + unlock_retry_impl(PrompterType::Plasma).await +} + +#[tokio::test] +async fn locked_collection_operations() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Verify collection is unlocked initially + assert!( + !setup.collections[0].is_locked().await?, + "Collection should start unlocked" + ); + + // Lock the collection + setup.lock_collection(&setup.collections[0]).await?; + + // Verify collection is now locked + assert!( + setup.collections[0].is_locked().await?, + "Collection should be locked" + ); + + // Test 1: set_label should fail with IsLocked + let result = setup.collections[0].set_label("New Label").await; + assert!( + matches!(result, Err(oo7::dbus::Error::ZBus(zbus::Error::FDO(_)))), + "set_label should fail with IsLocked error, got: {:?}", + result + ); + + // Verify read-only operations still work on locked collections + assert!( + setup.collections[0].label().await.is_ok(), + "Should be able to read label of locked collection" + ); + + let items = setup.collections[0].items().await?; + assert!( + items.is_empty(), + "Should be able to read items (empty) from locked collection" + ); + + Ok(()) +} diff --git a/server/src/collection/tests/mod.rs b/server/src/collection/tests/mod.rs new file mode 100644 index 00000000..ae473a28 --- /dev/null +++ b/server/src/collection/tests/mod.rs @@ -0,0 +1,5 @@ +mod deletion; +mod items; +mod locking; +mod properties; +mod search; diff --git a/server/src/collection/tests/properties.rs b/server/src/collection/tests/properties.rs new file mode 100644 index 00000000..dfbe4f0a --- /dev/null +++ b/server/src/collection/tests/properties.rs @@ -0,0 +1,85 @@ +use crate::tests::{TestServiceSetup, assert_next_signal}; + +#[tokio::test] +async fn label_property() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Get the Login collection via alias (don't rely on collection ordering) + let login_collection = setup + .service_api + .read_alias("default") + .await? + .expect("Default collection should exist"); + + // Get initial label (should be "Login" for default collection) + let label = login_collection.label().await?; + assert_eq!(label, "Login"); + + // Get initial modified timestamp + let initial_modified = login_collection.modified().await?; + + // Wait to ensure timestamp will be different + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + + // Subscribe to CollectionChanged signal before changing label + let signal_stream = setup.service_api.receive_collection_changed().await?; + tokio::pin!(signal_stream); + + // Set new label + login_collection.set_label("My Custom Collection").await?; + + // Verify CollectionChanged signal was emitted + let signal_collection = assert_next_signal(&mut signal_stream).await; + assert_eq!( + signal_collection.inner().path().as_str(), + login_collection.inner().path().as_str(), + "Signal should contain the changed collection path" + ); + + // Verify new label + let label = login_collection.label().await?; + assert_eq!(label, "My Custom Collection"); + + // Verify modified timestamp was updated + let new_modified = login_collection.modified().await?; + assert!( + new_modified > initial_modified, + "Modified timestamp should be updated after label change" + ); + + Ok(()) +} + +#[tokio::test] +async fn timestamps() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Get created timestamp + let created = setup.collections[0].created().await?; + assert!(created.as_secs() > 0, "Created timestamp should be set"); + + // Get modified timestamp + let modified = setup.collections[0].modified().await?; + assert!(modified.as_secs() > 0, "Modified timestamp should be set"); + + // Created and modified should be close (within a second for new collection) + let diff = if created > modified { + created.as_secs() - modified.as_secs() + } else { + modified.as_secs() - created.as_secs() + }; + assert!(diff <= 1, "Created and modified should be within 1 second"); + + Ok(()) +} + +#[test] +fn test_collection_path() { + use crate::collection::collection_path; + + assert!(collection_path("").is_err()); + assert_eq!( + collection_path("bär").unwrap().as_str(), + "/org/freedesktop/secrets/collection/b_r" + ); +} diff --git a/server/src/collection/tests/search.rs b/server/src/collection/tests/search.rs new file mode 100644 index 00000000..648e480a --- /dev/null +++ b/server/src/collection/tests/search.rs @@ -0,0 +1,116 @@ +use crate::tests::TestServiceSetup; + +#[tokio::test] +async fn search_items_after_creation() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Create two items with different attributes + setup + .create_item( + "Firefox Password", + &[("application", "firefox"), ("username", "user1")], + "password1", + false, + ) + .await?; + + setup + .create_item( + "Chrome Password", + &[("application", "chrome"), ("username", "user2")], + "password2", + false, + ) + .await?; + + // Search for firefox item + let firefox_attrs = &[("application", "firefox")]; + let firefox_items = setup.collections[0].search_items(firefox_attrs).await?; + + assert_eq!(firefox_items.len(), 1, "Should find one firefox item"); + + // Search for chrome item + let chrome_items = setup.collections[0] + .search_items(&[("application", "chrome")]) + .await?; + + assert_eq!(chrome_items.len(), 1, "Should find one chrome item"); + + // Search for non-existent item + let nonexistent_items = setup.collections[0] + .search_items(&[("application", "nonexistent")]) + .await?; + + assert_eq!( + nonexistent_items.len(), + 0, + "Should find no nonexistent items" + ); + + Ok(()) +} + +#[tokio::test] +async fn search_items_subset_matching() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Create an item with multiple attributes (url and username) + setup + .create_item( + "Zed Login", + &[("url", "https://zed.dev"), ("username", "alice")], + "my-password", + false, + ) + .await?; + + // Search with only the url attribute (subset of stored attributes) + let results = setup.collections[0] + .search_items(&[("url", "https://zed.dev")]) + .await?; + + assert_eq!( + results.len(), + 1, + "Should find item when searching with subset of its attributes" + ); + + // Search with only the username attribute (another subset) + let results = setup.collections[0] + .search_items(&[("username", "alice")]) + .await?; + + assert_eq!( + results.len(), + 1, + "Should find item when searching with different subset of its attributes" + ); + + // Search with both attributes (exact match) + let results = setup.collections[0] + .search_items(&[("url", "https://zed.dev"), ("username", "alice")]) + .await?; + + assert_eq!( + results.len(), + 1, + "Should find item when searching with all its attributes" + ); + + // Search with superset of attributes (should not match) + let results = setup.collections[0] + .search_items(&[ + ("url", "https://zed.dev"), + ("username", "alice"), + ("extra", "attribute"), + ]) + .await?; + + assert_eq!( + results.len(), + 0, + "Should not find item when searching with superset of its attributes" + ); + + Ok(()) +} From b89f8cde47d09e1a9f558182bdb6c0126ab53e0f Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Wed, 11 Nov 2026 17:03:43 +0100 Subject: [PATCH 09/12] server: Split item tests into per-area modules --- server/src/item/tests.rs | 627 ---------------------------- server/src/item/tests/locking.rs | 150 +++++++ server/src/item/tests/mod.rs | 3 + server/src/item/tests/properties.rs | 228 ++++++++++ server/src/item/tests/secrets.rs | 248 +++++++++++ 5 files changed, 629 insertions(+), 627 deletions(-) delete mode 100644 server/src/item/tests.rs create mode 100644 server/src/item/tests/locking.rs create mode 100644 server/src/item/tests/mod.rs create mode 100644 server/src/item/tests/properties.rs create mode 100644 server/src/item/tests/secrets.rs diff --git a/server/src/item/tests.rs b/server/src/item/tests.rs deleted file mode 100644 index 153360c4..00000000 --- a/server/src/item/tests.rs +++ /dev/null @@ -1,627 +0,0 @@ -use std::sync::Arc; - -use oo7::dbus; - -use crate::{ - service::PrompterType, - tests::{TestServiceSetup, assert_next_signal}, -}; - -#[tokio::test] -async fn label_property() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - let item = setup - .create_item("Original Label", &[("app", "test")], "test-secret", false) - .await?; - - // Get label - let label = item.label().await?; - assert_eq!(label, "Original Label"); - - // Get initial modified timestamp - let initial_modified = item.modified().await?; - - // Wait to ensure timestamp will be different - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; - - // Set label - item.set_label("New Label").await?; - - // Verify new label - let label = item.label().await?; - assert_eq!(label, "New Label"); - - // Verify modified timestamp was updated - let new_modified = item.modified().await?; - println!("New modified: {:?}", new_modified); - assert!( - new_modified > initial_modified, - "Modified timestamp should be updated after label change (initial: {:?}, new: {:?})", - initial_modified, - new_modified - ); - - Ok(()) -} - -#[tokio::test] -async fn attributes_property() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - let item = setup - .create_item( - "Test Item", - &[("app", "firefox"), ("username", "user@example.com")], - "test-secret", - false, - ) - .await?; - - // Get attributes - let attrs = item.attributes().await?; - assert_eq!(attrs.get("app").unwrap(), "firefox"); - assert_eq!(attrs.get("username").unwrap(), "user@example.com"); - - // Get initial modified timestamp - let initial_modified = item.modified().await?; - - // Wait to ensure timestamp will be different - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; - - // Set new attributes - item.set_attributes(&[("app", "chrome"), ("username", "newuser@example.com")]) - .await?; - - // Verify new attributes - let attrs = item.attributes().await?; - assert_eq!(attrs.get("app").unwrap(), "chrome"); - assert_eq!(attrs.get("username").unwrap(), "newuser@example.com"); - - // Verify modified timestamp was updated - let new_modified = item.modified().await?; - assert!( - new_modified > initial_modified, - "Modified timestamp should be updated after attributes change" - ); - - Ok(()) -} - -#[tokio::test] -async fn timestamps() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - let item = setup - .create_item("Test Item", &[("app", "test")], "test-secret", false) - .await?; - - // Get created timestamp - let created = item.created().await?; - assert!(created.as_secs() > 0, "Created timestamp should be set"); - - // Get modified timestamp - let modified = item.modified().await?; - assert!(modified.as_secs() > 0, "Modified timestamp should be set"); - - // Created and modified should be close (within a second for new item) - let diff = if created > modified { - created.as_secs() - modified.as_secs() - } else { - modified.as_secs() - created.as_secs() - }; - assert!(diff <= 1, "Created and modified should be within 1 second"); - Ok(()) -} - -#[tokio::test] -async fn secret_retrieval_plain() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - let secret = oo7::Secret::blob(b"my-secret-password"); - let item = setup - .create_item("Test Item", &[("app", "test")], secret.clone(), false) - .await?; - - // Retrieve secret - let retrieved_secret = item.secret(&setup.session).await?; - assert_eq!(retrieved_secret.value(), secret.as_bytes()); - - // Verify content-type is preserved - assert_eq!( - retrieved_secret.content_type(), - secret.content_type(), - "Content-type should be preserved" - ); - Ok(()) -} - -#[tokio::test] -async fn secret_retrieval_encrypted() -> Result<(), Box> { - let setup = TestServiceSetup::encrypted_session(true).await?; - - let aes_key = setup.aes_key.as_ref().unwrap(); - let secret = oo7::Secret::text("my-encrypted-secret"); - let item = setup - .create_item("Test Item", &[("app", "test")], secret.clone(), false) - .await?; - - // Retrieve secret - let retrieved_secret = item.secret(&setup.session).await?; - assert_eq!( - retrieved_secret.decrypt(Some(&aes_key.clone()))?.as_bytes(), - secret.as_bytes() - ); - // Verify content-type is preserved - assert_eq!( - retrieved_secret - .decrypt(Some(&aes_key.clone()))? - .content_type(), - secret.content_type(), - "Content-type should be preserved" - ); - - Ok(()) -} - -#[tokio::test] -async fn delete_item() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - let item = setup - .create_item("Test Item", &[("app", "test")], "test-secret", false) - .await?; - - // Verify item exists - let items = setup.collections[0].items().await?; - assert_eq!(items.len(), 1); - - // Delete item - item.delete(None).await?; - - // Verify item is deleted - let items = setup.collections[0].items().await?; - assert_eq!(items.len(), 0, "Item should be deleted from collection"); - Ok(()) -} - -#[tokio::test] -async fn set_secret_plain() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - let original_secret = oo7::Secret::text("original-password"); - let item = setup - .create_item( - "Test Item", - &[("app", "test")], - original_secret.clone(), - false, - ) - .await?; - - // Verify original secret - let retrieved = item.secret(&setup.session).await?; - assert_eq!(retrieved.value(), original_secret.as_bytes()); - assert_eq!( - retrieved.content_type(), - original_secret.content_type(), - "Content-type should be preserved" - ); - - // Get initial modified timestamp - let initial_modified = item.modified().await?; - - // Wait to ensure timestamp will be different - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; - - // Update the secret - let new_secret = oo7::Secret::blob(b"new-password"); - let new_dbus_secret = setup.create_dbus_secret(new_secret.clone())?; - item.set_secret(&new_dbus_secret).await?; - - // Verify updated secret - let retrieved = item.secret(&setup.session).await?; - assert_eq!(retrieved.value(), new_secret.as_bytes()); - assert_eq!( - retrieved.content_type(), - new_secret.content_type(), - "Content-type should be preserved" - ); - - // Verify modified timestamp was updated - let new_modified = item.modified().await?; - assert!( - new_modified > initial_modified, - "Modified timestamp should be updated after secret change" - ); - - Ok(()) -} - -#[tokio::test] -async fn set_secret_encrypted() -> Result<(), Box> { - let setup = TestServiceSetup::encrypted_session(true).await?; - let aes_key = setup.aes_key.as_ref().unwrap().clone(); - - let original_secret = oo7::Secret::text("original-encrypted-password"); - let item = setup - .create_item( - "Test Item", - &[("app", "test")], - original_secret.clone(), - false, - ) - .await?; - - // Verify original secret - let retrieved = item.secret(&setup.session).await?; - assert_eq!( - retrieved.decrypt(Some(&aes_key.clone()))?.as_bytes(), - original_secret.as_bytes() - ); - - // Get initial modified timestamp - let initial_modified = item.modified().await?; - - // Wait to ensure timestamp will be different - tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; - - // Update the secret - let new_secret = oo7::Secret::text("new-encrypted-password"); - let new_dbus_secret = setup.create_dbus_secret(new_secret.clone())?; - item.set_secret(&new_dbus_secret).await?; - - // Verify updated secret - let retrieved = item.secret(&setup.session).await?; - assert_eq!( - retrieved.decrypt(Some(&aes_key.clone()))?.as_bytes(), - new_secret.as_bytes() - ); - - // Verify modified timestamp was updated - let new_modified = item.modified().await?; - assert!( - new_modified > initial_modified, - "Modified timestamp should be updated after secret change" - ); - - Ok(()) -} - -#[tokio::test] -async fn get_secret_invalid_session() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - let item = setup - .create_item("Test Item", &[("app", "test")], "test-secret", false) - .await?; - - // Try to get secret with invalid session path - let invalid_session = - oo7::dbus::api::Session::new(&setup.client_conn, "/invalid/session").await?; - let result = item.secret(&invalid_session).await; - - assert!( - matches!( - result, - Err(oo7::dbus::Error::Service( - oo7::dbus::ServiceError::NoSession(_) - )) - ), - "Should be NoSession error" - ); - - Ok(()) -} - -#[tokio::test] -async fn set_secret_invalid_session() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - let item = setup - .create_item("Test Item", &[("app", "test")], "test-secret", false) - .await?; - - let new_secret = oo7::Secret::text("new-secret"); - let invalid_dbus_secret = dbus::api::DBusSecret::new( - Arc::new(dbus::api::Session::new(&setup.client_conn, "/invalid/session").await?), - new_secret, - ); - - let result = item.set_secret(&invalid_dbus_secret).await; - - // Should return NoSession error - assert!( - matches!( - result, - Err(oo7::dbus::Error::Service( - oo7::dbus::ServiceError::NoSession(_) - )) - ), - "Should be NoSession error" - ); - - Ok(()) -} - -#[tokio::test] -async fn item_changed_signal() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - let item = setup - .create_item("Test Item", &[("app", "test")], "test-secret", false) - .await?; - - // Subscribe to ItemChanged signal - let signal_stream = setup.collections[0].receive_item_changed().await?; - tokio::pin!(signal_stream); - - // Change the label - item.set_label("Updated Label").await?; - - let signal_item = assert_next_signal(&mut signal_stream).await; - assert_eq!( - signal_item.inner().path().as_str(), - item.inner().path().as_str(), - "Signal should contain the changed item path" - ); - - // Change attributes and verify signal again - item.set_attributes(&[("app", "updated-app")]).await?; - assert_next_signal(&mut signal_stream).await; - - // Change secret and verify signal again - let new_dbus_secret = setup.create_dbus_secret("new-secret")?; - item.set_secret(&new_dbus_secret).await?; - assert_next_signal(&mut signal_stream).await; - - Ok(()) -} - -async fn delete_locked_item_with_prompt_impl( - prompter_type: PrompterType, -) -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - setup.server.set_prompter_type(prompter_type).await; - let default_collection = &setup.collections[0]; - - let dbus_secret = setup.create_dbus_secret("test-password")?; - - let item = default_collection - .create_item("Test Item", &[("app", "test")], &dbus_secret, false, None) - .await?; - - let items = default_collection.items().await?; - assert_eq!(items.len(), 1, "Should have one item"); - - setup.lock_collection(default_collection).await?; - - assert!(item.is_locked().await?, "Item should be locked"); - - item.delete(None).await?; - - let items = default_collection.items().await?; - assert_eq!(items.len(), 0, "Item should be deleted after prompt"); - - Ok(()) -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[tokio::test] -async fn delete_locked_item_with_prompt_gnome() -> Result<(), Box> { - delete_locked_item_with_prompt_impl(PrompterType::GNOME).await -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[tokio::test] -async fn delete_locked_item_with_prompt_plasma() -> Result<(), Box> { - delete_locked_item_with_prompt_impl(PrompterType::Plasma).await -} - -#[tokio::test] -async fn locked_item_operations() -> Result<(), Box> { - let setup = TestServiceSetup::plain_session(true).await?; - - // Create an item - let item = setup - .create_item("Test Item", &[("app", "test")], "test-password", false) - .await?; - - // Verify item is unlocked initially - assert!(!item.is_locked().await?, "Item should start unlocked"); - - // Lock the collection (which locks the item) - setup.lock_collection(&setup.collections[0]).await?; - - // Verify item is now locked - assert!( - item.is_locked().await?, - "Item should be locked after locking collection" - ); - - // Test 1: get_secret should fail with IsLocked - let result = item.secret(&setup.session).await; - assert!( - matches!( - result, - Err(oo7::dbus::Error::Service( - oo7::dbus::ServiceError::IsLocked(_) - )) - ), - "get_secret should fail with IsLocked error, got: {:?}", - result - ); - - // Test 2: set_secret should fail with IsLocked - let new_dbus_secret = setup.create_dbus_secret("new-password")?; - let result = item.set_secret(&new_dbus_secret).await; - assert!( - matches!( - result, - Err(oo7::dbus::Error::Service( - oo7::dbus::ServiceError::IsLocked(_) - )) - ), - "set_secret should fail with IsLocked error, got: {:?}", - result - ); - - // Property setters go through org.freedesktop.DBus.Properties.Set, - // so the error is wrapped in FDO rather than deserialized as ServiceError. - let result = item.set_attributes(&[("app", "new-app")]).await; - assert!( - matches!(result, Err(oo7::dbus::Error::ZBus(zbus::Error::FDO(_)))), - "set_attributes should fail with IsLocked error, got: {:?}", - result - ); - - let result = item.set_label("New Label").await; - assert!( - matches!(result, Err(oo7::dbus::Error::ZBus(zbus::Error::FDO(_)))), - "set_label should fail with IsLocked error, got: {:?}", - result - ); - - // Property getters go through org.freedesktop.DBus.Properties.Get, - // arriving as a MethodError with the IsLocked error name. - let result = item.label().await; - assert!( - matches!( - result, - Err(oo7::dbus::Error::ZBus(zbus::Error::MethodError(..))) - ), - "label should fail on locked item, got: {:?}", - result - ); - - let result = item.attributes().await; - assert!( - matches!( - result, - Err(oo7::dbus::Error::ZBus(zbus::Error::MethodError(..))) - ), - "attributes should fail on locked item, got: {:?}", - result - ); - - let result = item.created().await; - assert!( - matches!( - result, - Err(oo7::dbus::Error::ZBus(zbus::Error::MethodError(..))) - ), - "created should fail on locked item, got: {:?}", - result - ); - - let result = item.modified().await; - assert!( - matches!( - result, - Err(oo7::dbus::Error::ZBus(zbus::Error::MethodError(..))) - ), - "modified should fail on locked item, got: {:?}", - result - ); - - Ok(()) -} - -#[tokio::test] -async fn set_label_persists() -> Result<(), Box> { - let setup = - TestServiceSetup::with_login_keyring(oo7::Secret::from("test-password-long-enough")) - .await?; - let collection = &setup.collections[0]; - - // Stored first, with a superset of the changed item's attributes - let other_secret = setup.create_dbus_secret("other-secret")?; - collection - .create_item( - "Other Item", - &[("app", "test"), ("user", "other")], - &other_secret, - false, - None, - ) - .await?; - let secret = setup.create_dbus_secret("test-secret")?; - let item = collection - .create_item("Test Item", &[("app", "test")], &secret, false, None) - .await?; - - item.set_label("New Label").await?; - - let items = setup.login_keyring().await?.items().await?; - let labels = items.iter().map(|i| i.label()).collect::>(); - assert_eq!(labels, ["Other Item", "New Label"]); - - Ok(()) -} - -#[tokio::test] -async fn set_attributes_persists() -> Result<(), Box> { - let setup = - TestServiceSetup::with_login_keyring(oo7::Secret::from("test-password-long-enough")) - .await?; - let collection = &setup.collections[0]; - - // Stored first, with a superset of the changed item's attributes - let other_secret = setup.create_dbus_secret("other-secret")?; - collection - .create_item( - "Other Item", - &[("app", "test"), ("user", "other")], - &other_secret, - false, - None, - ) - .await?; - let secret = setup.create_dbus_secret("test-secret")?; - let item = collection - .create_item("Test Item", &[("app", "test")], &secret, false, None) - .await?; - - item.set_attributes(&[("app", "updated")]).await?; - - let items = setup.login_keyring().await?.items().await?; - assert_eq!(items[0].attributes().get("user").unwrap(), "other"); - assert_eq!(items[1].label(), "Test Item"); - assert_eq!(items[1].attributes().get("app").unwrap(), "updated"); - - Ok(()) -} - -#[tokio::test] -async fn set_secret_persists() -> Result<(), Box> { - let setup = - TestServiceSetup::with_login_keyring(oo7::Secret::from("test-password-long-enough")) - .await?; - let collection = &setup.collections[0]; - - // Stored first, with a superset of the changed item's attributes - let other_secret = setup.create_dbus_secret("other-secret")?; - collection - .create_item( - "Other Item", - &[("app", "test"), ("user", "other")], - &other_secret, - false, - None, - ) - .await?; - let secret = setup.create_dbus_secret("test-secret")?; - let item = collection - .create_item("Test Item", &[("app", "test")], &secret, false, None) - .await?; - - let new_secret = oo7::Secret::text("new-secret"); - item.set_secret(&setup.create_dbus_secret(new_secret.clone())?) - .await?; - - let items = setup.login_keyring().await?.items().await?; - assert_eq!(items[0].secret(), oo7::Secret::text("other-secret")); - assert_eq!(items[1].secret(), new_secret); - - Ok(()) -} diff --git a/server/src/item/tests/locking.rs b/server/src/item/tests/locking.rs new file mode 100644 index 00000000..6684958a --- /dev/null +++ b/server/src/item/tests/locking.rs @@ -0,0 +1,150 @@ +use crate::{service::PrompterType, tests::TestServiceSetup}; + +async fn delete_locked_item_with_prompt_impl( + prompter_type: PrompterType, +) -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + setup.server.set_prompter_type(prompter_type).await; + let default_collection = &setup.collections[0]; + + let dbus_secret = setup.create_dbus_secret("test-password")?; + + let item = default_collection + .create_item("Test Item", &[("app", "test")], &dbus_secret, false, None) + .await?; + + let items = default_collection.items().await?; + assert_eq!(items.len(), 1, "Should have one item"); + + setup.lock_collection(default_collection).await?; + + assert!(item.is_locked().await?, "Item should be locked"); + + item.delete(None).await?; + + let items = default_collection.items().await?; + assert_eq!(items.len(), 0, "Item should be deleted after prompt"); + + Ok(()) +} + +#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] +#[tokio::test] +async fn delete_locked_item_with_prompt_gnome() -> Result<(), Box> { + delete_locked_item_with_prompt_impl(PrompterType::GNOME).await +} + +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +#[tokio::test] +async fn delete_locked_item_with_prompt_plasma() -> Result<(), Box> { + delete_locked_item_with_prompt_impl(PrompterType::Plasma).await +} + +#[tokio::test] +async fn locked_item_operations() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // Create an item + let item = setup + .create_item("Test Item", &[("app", "test")], "test-password", false) + .await?; + + // Verify item is unlocked initially + assert!(!item.is_locked().await?, "Item should start unlocked"); + + // Lock the collection (which locks the item) + setup.lock_collection(&setup.collections[0]).await?; + + // Verify item is now locked + assert!( + item.is_locked().await?, + "Item should be locked after locking collection" + ); + + // Test 1: get_secret should fail with IsLocked + let result = item.secret(&setup.session).await; + assert!( + matches!( + result, + Err(oo7::dbus::Error::Service( + oo7::dbus::ServiceError::IsLocked(_) + )) + ), + "get_secret should fail with IsLocked error, got: {:?}", + result + ); + + // Test 2: set_secret should fail with IsLocked + let new_dbus_secret = setup.create_dbus_secret("new-password")?; + let result = item.set_secret(&new_dbus_secret).await; + assert!( + matches!( + result, + Err(oo7::dbus::Error::Service( + oo7::dbus::ServiceError::IsLocked(_) + )) + ), + "set_secret should fail with IsLocked error, got: {:?}", + result + ); + + // Property setters go through org.freedesktop.DBus.Properties.Set, + // so the error is wrapped in FDO rather than deserialized as ServiceError. + let result = item.set_attributes(&[("app", "new-app")]).await; + assert!( + matches!(result, Err(oo7::dbus::Error::ZBus(zbus::Error::FDO(_)))), + "set_attributes should fail with IsLocked error, got: {:?}", + result + ); + + let result = item.set_label("New Label").await; + assert!( + matches!(result, Err(oo7::dbus::Error::ZBus(zbus::Error::FDO(_)))), + "set_label should fail with IsLocked error, got: {:?}", + result + ); + + // Property getters go through org.freedesktop.DBus.Properties.Get, + // arriving as a MethodError with the IsLocked error name. + let result = item.label().await; + assert!( + matches!( + result, + Err(oo7::dbus::Error::ZBus(zbus::Error::MethodError(..))) + ), + "label should fail on locked item, got: {:?}", + result + ); + + let result = item.attributes().await; + assert!( + matches!( + result, + Err(oo7::dbus::Error::ZBus(zbus::Error::MethodError(..))) + ), + "attributes should fail on locked item, got: {:?}", + result + ); + + let result = item.created().await; + assert!( + matches!( + result, + Err(oo7::dbus::Error::ZBus(zbus::Error::MethodError(..))) + ), + "created should fail on locked item, got: {:?}", + result + ); + + let result = item.modified().await; + assert!( + matches!( + result, + Err(oo7::dbus::Error::ZBus(zbus::Error::MethodError(..))) + ), + "modified should fail on locked item, got: {:?}", + result + ); + + Ok(()) +} diff --git a/server/src/item/tests/mod.rs b/server/src/item/tests/mod.rs new file mode 100644 index 00000000..ff4ab273 --- /dev/null +++ b/server/src/item/tests/mod.rs @@ -0,0 +1,3 @@ +mod locking; +mod properties; +mod secrets; diff --git a/server/src/item/tests/properties.rs b/server/src/item/tests/properties.rs new file mode 100644 index 00000000..f0a4832b --- /dev/null +++ b/server/src/item/tests/properties.rs @@ -0,0 +1,228 @@ +use crate::tests::{TestServiceSetup, assert_next_signal}; + +#[tokio::test] +async fn label_property() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + let item = setup + .create_item("Original Label", &[("app", "test")], "test-secret", false) + .await?; + + // Get label + let label = item.label().await?; + assert_eq!(label, "Original Label"); + + // Get initial modified timestamp + let initial_modified = item.modified().await?; + + // Wait to ensure timestamp will be different + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + + // Set label + item.set_label("New Label").await?; + + // Verify new label + let label = item.label().await?; + assert_eq!(label, "New Label"); + + // Verify modified timestamp was updated + let new_modified = item.modified().await?; + println!("New modified: {:?}", new_modified); + assert!( + new_modified > initial_modified, + "Modified timestamp should be updated after label change (initial: {:?}, new: {:?})", + initial_modified, + new_modified + ); + + Ok(()) +} + +#[tokio::test] +async fn attributes_property() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + let item = setup + .create_item( + "Test Item", + &[("app", "firefox"), ("username", "user@example.com")], + "test-secret", + false, + ) + .await?; + + // Get attributes + let attrs = item.attributes().await?; + assert_eq!(attrs.get("app").unwrap(), "firefox"); + assert_eq!(attrs.get("username").unwrap(), "user@example.com"); + + // Get initial modified timestamp + let initial_modified = item.modified().await?; + + // Wait to ensure timestamp will be different + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + + // Set new attributes + item.set_attributes(&[("app", "chrome"), ("username", "newuser@example.com")]) + .await?; + + // Verify new attributes + let attrs = item.attributes().await?; + assert_eq!(attrs.get("app").unwrap(), "chrome"); + assert_eq!(attrs.get("username").unwrap(), "newuser@example.com"); + + // Verify modified timestamp was updated + let new_modified = item.modified().await?; + assert!( + new_modified > initial_modified, + "Modified timestamp should be updated after attributes change" + ); + + Ok(()) +} + +#[tokio::test] +async fn timestamps() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + let item = setup + .create_item("Test Item", &[("app", "test")], "test-secret", false) + .await?; + + // Get created timestamp + let created = item.created().await?; + assert!(created.as_secs() > 0, "Created timestamp should be set"); + + // Get modified timestamp + let modified = item.modified().await?; + assert!(modified.as_secs() > 0, "Modified timestamp should be set"); + + // Created and modified should be close (within a second for new item) + let diff = if created > modified { + created.as_secs() - modified.as_secs() + } else { + modified.as_secs() - created.as_secs() + }; + assert!(diff <= 1, "Created and modified should be within 1 second"); + Ok(()) +} + +#[tokio::test] +async fn item_changed_signal() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + let item = setup + .create_item("Test Item", &[("app", "test")], "test-secret", false) + .await?; + + // Subscribe to ItemChanged signal + let signal_stream = setup.collections[0].receive_item_changed().await?; + tokio::pin!(signal_stream); + + // Change the label + item.set_label("Updated Label").await?; + + let signal_item = assert_next_signal(&mut signal_stream).await; + assert_eq!( + signal_item.inner().path().as_str(), + item.inner().path().as_str(), + "Signal should contain the changed item path" + ); + + // Change attributes and verify signal again + item.set_attributes(&[("app", "updated-app")]).await?; + assert_next_signal(&mut signal_stream).await; + + // Change secret and verify signal again + let new_dbus_secret = setup.create_dbus_secret("new-secret")?; + item.set_secret(&new_dbus_secret).await?; + assert_next_signal(&mut signal_stream).await; + + Ok(()) +} + +#[tokio::test] +async fn delete_item() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + let item = setup + .create_item("Test Item", &[("app", "test")], "test-secret", false) + .await?; + + // Verify item exists + let items = setup.collections[0].items().await?; + assert_eq!(items.len(), 1); + + // Delete item + item.delete(None).await?; + + // Verify item is deleted + let items = setup.collections[0].items().await?; + assert_eq!(items.len(), 0, "Item should be deleted from collection"); + Ok(()) +} + +#[tokio::test] +async fn set_label_persists() -> Result<(), Box> { + let setup = + TestServiceSetup::with_login_keyring(oo7::Secret::from("test-password-long-enough")) + .await?; + let collection = &setup.collections[0]; + + // Stored first, with a superset of the changed item's attributes + let other_secret = setup.create_dbus_secret("other-secret")?; + collection + .create_item( + "Other Item", + &[("app", "test"), ("user", "other")], + &other_secret, + false, + None, + ) + .await?; + let secret = setup.create_dbus_secret("test-secret")?; + let item = collection + .create_item("Test Item", &[("app", "test")], &secret, false, None) + .await?; + + item.set_label("New Label").await?; + + let items = setup.login_keyring().await?.items().await?; + let labels = items.iter().map(|i| i.label()).collect::>(); + assert_eq!(labels, ["Other Item", "New Label"]); + + Ok(()) +} + +#[tokio::test] +async fn set_attributes_persists() -> Result<(), Box> { + let setup = + TestServiceSetup::with_login_keyring(oo7::Secret::from("test-password-long-enough")) + .await?; + let collection = &setup.collections[0]; + + // Stored first, with a superset of the changed item's attributes + let other_secret = setup.create_dbus_secret("other-secret")?; + collection + .create_item( + "Other Item", + &[("app", "test"), ("user", "other")], + &other_secret, + false, + None, + ) + .await?; + let secret = setup.create_dbus_secret("test-secret")?; + let item = collection + .create_item("Test Item", &[("app", "test")], &secret, false, None) + .await?; + + item.set_attributes(&[("app", "updated")]).await?; + + let items = setup.login_keyring().await?.items().await?; + assert_eq!(items[0].attributes().get("user").unwrap(), "other"); + assert_eq!(items[1].label(), "Test Item"); + assert_eq!(items[1].attributes().get("app").unwrap(), "updated"); + + Ok(()) +} diff --git a/server/src/item/tests/secrets.rs b/server/src/item/tests/secrets.rs new file mode 100644 index 00000000..1bff5e8d --- /dev/null +++ b/server/src/item/tests/secrets.rs @@ -0,0 +1,248 @@ +use std::sync::Arc; + +use oo7::dbus; + +use crate::tests::TestServiceSetup; + +#[tokio::test] +async fn secret_retrieval_plain() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + let secret = oo7::Secret::blob(b"my-secret-password"); + let item = setup + .create_item("Test Item", &[("app", "test")], secret.clone(), false) + .await?; + + // Retrieve secret + let retrieved_secret = item.secret(&setup.session).await?; + assert_eq!(retrieved_secret.value(), secret.as_bytes()); + + // Verify content-type is preserved + assert_eq!( + retrieved_secret.content_type(), + secret.content_type(), + "Content-type should be preserved" + ); + Ok(()) +} + +#[tokio::test] +async fn secret_retrieval_encrypted() -> Result<(), Box> { + let setup = TestServiceSetup::encrypted_session(true).await?; + + let aes_key = setup.aes_key.as_ref().unwrap(); + let secret = oo7::Secret::text("my-encrypted-secret"); + let item = setup + .create_item("Test Item", &[("app", "test")], secret.clone(), false) + .await?; + + // Retrieve secret + let retrieved_secret = item.secret(&setup.session).await?; + assert_eq!( + retrieved_secret.decrypt(Some(&aes_key.clone()))?.as_bytes(), + secret.as_bytes() + ); + // Verify content-type is preserved + assert_eq!( + retrieved_secret + .decrypt(Some(&aes_key.clone()))? + .content_type(), + secret.content_type(), + "Content-type should be preserved" + ); + + Ok(()) +} + +#[tokio::test] +async fn set_secret_plain() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + let original_secret = oo7::Secret::text("original-password"); + let item = setup + .create_item( + "Test Item", + &[("app", "test")], + original_secret.clone(), + false, + ) + .await?; + + // Verify original secret + let retrieved = item.secret(&setup.session).await?; + assert_eq!(retrieved.value(), original_secret.as_bytes()); + assert_eq!( + retrieved.content_type(), + original_secret.content_type(), + "Content-type should be preserved" + ); + + // Get initial modified timestamp + let initial_modified = item.modified().await?; + + // Wait to ensure timestamp will be different + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + + // Update the secret + let new_secret = oo7::Secret::blob(b"new-password"); + let new_dbus_secret = setup.create_dbus_secret(new_secret.clone())?; + item.set_secret(&new_dbus_secret).await?; + + // Verify updated secret + let retrieved = item.secret(&setup.session).await?; + assert_eq!(retrieved.value(), new_secret.as_bytes()); + assert_eq!( + retrieved.content_type(), + new_secret.content_type(), + "Content-type should be preserved" + ); + + // Verify modified timestamp was updated + let new_modified = item.modified().await?; + assert!( + new_modified > initial_modified, + "Modified timestamp should be updated after secret change" + ); + + Ok(()) +} + +#[tokio::test] +async fn set_secret_encrypted() -> Result<(), Box> { + let setup = TestServiceSetup::encrypted_session(true).await?; + let aes_key = setup.aes_key.as_ref().unwrap().clone(); + + let original_secret = oo7::Secret::text("original-encrypted-password"); + let item = setup + .create_item( + "Test Item", + &[("app", "test")], + original_secret.clone(), + false, + ) + .await?; + + // Verify original secret + let retrieved = item.secret(&setup.session).await?; + assert_eq!( + retrieved.decrypt(Some(&aes_key.clone()))?.as_bytes(), + original_secret.as_bytes() + ); + + // Get initial modified timestamp + let initial_modified = item.modified().await?; + + // Wait to ensure timestamp will be different + tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; + + // Update the secret + let new_secret = oo7::Secret::text("new-encrypted-password"); + let new_dbus_secret = setup.create_dbus_secret(new_secret.clone())?; + item.set_secret(&new_dbus_secret).await?; + + // Verify updated secret + let retrieved = item.secret(&setup.session).await?; + assert_eq!( + retrieved.decrypt(Some(&aes_key.clone()))?.as_bytes(), + new_secret.as_bytes() + ); + + // Verify modified timestamp was updated + let new_modified = item.modified().await?; + assert!( + new_modified > initial_modified, + "Modified timestamp should be updated after secret change" + ); + + Ok(()) +} + +#[tokio::test] +async fn get_secret_invalid_session() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + let item = setup + .create_item("Test Item", &[("app", "test")], "test-secret", false) + .await?; + + // Try to get secret with invalid session path + let invalid_session = + oo7::dbus::api::Session::new(&setup.client_conn, "/invalid/session").await?; + let result = item.secret(&invalid_session).await; + + assert!( + matches!( + result, + Err(oo7::dbus::Error::Service( + oo7::dbus::ServiceError::NoSession(_) + )) + ), + "Should be NoSession error" + ); + + Ok(()) +} + +#[tokio::test] +async fn set_secret_invalid_session() -> Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + let item = setup + .create_item("Test Item", &[("app", "test")], "test-secret", false) + .await?; + + let new_secret = oo7::Secret::text("new-secret"); + let invalid_dbus_secret = dbus::api::DBusSecret::new( + Arc::new(dbus::api::Session::new(&setup.client_conn, "/invalid/session").await?), + new_secret, + ); + + let result = item.set_secret(&invalid_dbus_secret).await; + + // Should return NoSession error + assert!( + matches!( + result, + Err(oo7::dbus::Error::Service( + oo7::dbus::ServiceError::NoSession(_) + )) + ), + "Should be NoSession error" + ); + + Ok(()) +} + +#[tokio::test] +async fn set_secret_persists() -> Result<(), Box> { + let setup = + TestServiceSetup::with_login_keyring(oo7::Secret::from("test-password-long-enough")) + .await?; + let collection = &setup.collections[0]; + + // Stored first, with a superset of the changed item's attributes + let other_secret = setup.create_dbus_secret("other-secret")?; + collection + .create_item( + "Other Item", + &[("app", "test"), ("user", "other")], + &other_secret, + false, + None, + ) + .await?; + let secret = setup.create_dbus_secret("test-secret")?; + let item = collection + .create_item("Test Item", &[("app", "test")], &secret, false, None) + .await?; + + let new_secret = oo7::Secret::text("new-secret"); + item.set_secret(&setup.create_dbus_secret(new_secret.clone())?) + .await?; + + let items = setup.login_keyring().await?.items().await?; + assert_eq!(items[0].secret(), oo7::Secret::text("other-secret")); + assert_eq!(items[1].secret(), new_secret); + + Ok(()) +} From e945e822397474c6eb66b5d11167bbb46520c0a4 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Wed, 11 Nov 2026 19:03:21 +0100 Subject: [PATCH 10/12] server: Move mock prompters to their respective modules --- server/src/gnome/mock_prompter.rs | 242 +++++++++++++ server/src/gnome/mod.rs | 2 + server/src/plasma/mock_prompter.rs | 196 +++++++++++ server/src/plasma/mod.rs | 2 + server/src/tests.rs | 526 +++-------------------------- 5 files changed, 491 insertions(+), 477 deletions(-) create mode 100644 server/src/gnome/mock_prompter.rs create mode 100644 server/src/plasma/mock_prompter.rs diff --git a/server/src/gnome/mock_prompter.rs b/server/src/gnome/mock_prompter.rs new file mode 100644 index 00000000..a58818e8 --- /dev/null +++ b/server/src/gnome/mock_prompter.rs @@ -0,0 +1,242 @@ +use std::{collections::HashMap, sync::Arc}; + +use base64::Engine; +use oo7::{Secret, crypto}; +use zbus::wire::{ObjectPath, Optional, Variant}; + +use super::{ + prompter::{PromptType, Properties, Reply}, + secret_exchange, +}; + +/// Mock implementation of org.gnome.keyring.internal.Prompter +/// +/// This simulates the GNOME System Prompter for testing without requiring +/// the actual GNOME keyring prompter service to be running. +#[derive(Clone)] +pub(crate) struct MockPrompterServiceGNOME { + /// The password to use for unlock prompts (simulates user input) + unlock_password: Arc>>, + /// Whether to accept (true) or dismiss (false) prompts + should_accept: Arc>, + /// Queue of passwords to use for for testing retry logic + password_queue: Arc>>, +} + +#[allow(unused)] +impl MockPrompterServiceGNOME { + pub fn new() -> Self { + Self { + unlock_password: Arc::new(tokio::sync::Mutex::new(Some(Secret::from( + "test-password-long-enough", + )))), + should_accept: Arc::new(tokio::sync::Mutex::new(true)), + password_queue: Arc::new(tokio::sync::Mutex::new(Vec::new())), + } + } + + /// Set whether prompts should be accepted or dismissed + pub async fn set_accept(&self, accept: bool) { + *self.should_accept.lock().await = accept; + } + + pub async fn set_password_queue(&self, passwords: Vec) { + *self.password_queue.lock().await = passwords; + } +} + +#[allow(unused)] +#[zbus::interface(name = "org.gnome.keyring.internal.Prompter")] +impl MockPrompterServiceGNOME { + async fn begin_prompting( + &self, + callback: ObjectPath<'_>, + #[zbus(connection)] connection: &zbus::Connection, + ) -> zbus::fdo::Result<()> { + tracing::debug!("MockPrompter: begin_prompting called for {}", callback); + let callback_path = callback.to_owned(); + let connection = connection.clone(); + + // Spawn a task to send the initial prompt_ready call + tokio::spawn(async move { + tracing::debug!("MockPrompter: spawned task starting"); + // Small delay to ensure callback is fully registered + tokio::time::sleep(tokio::time::Duration::from_millis(10)).await; + + // Call PromptReady directly without building a proxy (avoids + // introspection issues in p2p) + tracing::debug!( + "MockPrompter: calling PromptReady with None on {}", + callback_path + ); + let properties: HashMap = HashMap::new(); + let empty_exchange = ""; + + connection + .call_method( + None::<()>, // No destination in p2p + &callback_path, + Some("org.gnome.keyring.internal.Prompter.Callback"), + "PromptReady", + &(Optional::::from(None), properties, empty_exchange), + ) + .await?; + + tracing::debug!("MockPrompter: PromptReady(None) completed"); + Ok::<_, zbus::Error>(()) + }); + + Ok(()) + } + + async fn perform_prompt( + &self, + callback: ObjectPath<'_>, + type_: PromptType, + _properties: Properties, + exchange: &str, + #[zbus(connection)] connection: &zbus::Connection, + ) -> zbus::fdo::Result<()> { + tracing::debug!( + "MockPrompter: perform_prompt called for {}, type={:?}", + callback, + type_ + ); + // This is called by GNOMEPrompterCallback.prompter_init() with the + // server's exchange + let callback_path = callback.to_owned(); + let unlock_password = self.unlock_password.clone(); + let should_accept = self.should_accept.clone(); + let password_queue = self.password_queue.clone(); + let exchange = exchange.to_owned(); + let connection = connection.clone(); + + // Spawn a task to simulate user interaction and send final response + tokio::spawn(async move { + tracing::debug!("MockPrompter: perform_prompt task starting"); + // Small delay to simulate user interaction + tokio::time::sleep(tokio::time::Duration::from_millis(10)).await; + + let accept = *should_accept.lock().await; + let properties: HashMap = HashMap::new(); + + if !accept { + tracing::debug!("MockPrompter: dismissing prompt"); + // Dismiss the prompt + connection + .call_method( + None::<()>, // No destination in p2p + &callback_path, + Some("org.gnome.keyring.internal.Prompter.Callback"), + "PromptReady", + &(Reply::No, properties, ""), + ) + .await?; + tracing::debug!("MockPrompter: PromptReady(no) completed"); + + return Ok(()); + } else if type_ == PromptType::Password { + tracing::debug!("MockPrompter: performing unlock (password prompt)"); + // Unlock prompt - perform secret exchange + + let mut queue = password_queue.lock().await; + let password = if !queue.is_empty() { + let pwd = queue.remove(0); + tracing::debug!( + "MockPrompter: using password from queue (length: {}, queue remaining: {})", + pwd.as_str().unwrap_or(""), + queue.len() + ); + pwd + } else { + let pwd = unlock_password.lock().await.clone().unwrap(); + tracing::debug!( + "MockPrompter: using default password (length: {})", + pwd.as_str().unwrap_or("") + ); + pwd + }; + drop(queue); + + // Generate our own key pair + let private_key = oo7::Key::generate_private_key().unwrap(); + let public_key = super::crypto::generate_public_key(&private_key).unwrap(); + + // Handshake with server's exchange to get AES key + let aes_key = secret_exchange::handshake(&private_key, &exchange).unwrap(); + + // Encrypt the password + let iv = crypto::generate_iv().unwrap(); + let encrypted = crypto::encrypt(password.as_bytes(), &aes_key, &iv).unwrap(); + + // Create final exchange with encrypted secret + let final_exchange = format!( + "[sx-aes-1]\npublic={}\nsecret={}\niv={}", + base64::prelude::BASE64_STANDARD.encode(public_key.as_ref()), + base64::prelude::BASE64_STANDARD.encode(&encrypted), + base64::prelude::BASE64_STANDARD.encode(&iv) + ); + + tracing::debug!("MockPrompter: calling PromptReady with yes"); + connection + .call_method( + None::<()>, // No destination in p2p + &callback_path, + Some("org.gnome.keyring.internal.Prompter.Callback"), + "PromptReady", + &(Reply::Yes, properties, final_exchange.as_str()), + ) + .await?; + tracing::debug!("MockPrompter: PromptReady(yes) with secret exchange completed"); + } else { + tracing::debug!("MockPrompter: accepting confirm prompt"); + // Lock/confirm prompt - just accept + connection + .call_method( + None::<()>, // No destination in p2p + &callback_path, + Some("org.gnome.keyring.internal.Prompter.Callback"), + "PromptReady", + &(Reply::Yes, properties, ""), + ) + .await?; + tracing::debug!("MockPrompter: PromptReady(yes) completed"); + } + + Ok::<_, zbus::Error>(()) + }); + + Ok(()) + } + + async fn stop_prompting( + &self, + callback: ObjectPath<'_>, + #[zbus(connection)] connection: &zbus::Connection, + ) -> zbus::fdo::Result<()> { + tracing::debug!("MockPrompter: stop_prompting called for {}", callback); + let callback_path = callback.to_owned(); + let connection = connection.clone(); + + tokio::spawn(async move { + tracing::debug!("MockPrompter: calling PromptDone for {}", callback_path); + let result = connection + .call_method( + None::<()>, + &callback_path, + Some("org.gnome.keyring.internal.Prompter.Callback"), + "PromptDone", + &(), + ) + .await; + + if let Err(err) = result { + tracing::debug!("MockPrompter: PromptDone failed: {}", err); + } else { + tracing::debug!("MockPrompter: PromptDone completed for {}", callback_path); + } + }); + + Ok(()) + } +} diff --git a/server/src/gnome/mod.rs b/server/src/gnome/mod.rs index a1a1d87a..855d2c7f 100644 --- a/server/src/gnome/mod.rs +++ b/server/src/gnome/mod.rs @@ -2,3 +2,5 @@ pub mod crypto; pub mod internal; pub mod prompter; pub mod secret_exchange; + +pub(crate) mod mock_prompter; diff --git a/server/src/plasma/mock_prompter.rs b/server/src/plasma/mock_prompter.rs new file mode 100644 index 00000000..ee449205 --- /dev/null +++ b/server/src/plasma/mock_prompter.rs @@ -0,0 +1,196 @@ +use std::{io::Write, os::unix::net::UnixStream, sync::Arc}; + +use oo7::Secret; +use tokio_stream::StreamExt; +use zbus::wire::{Fd, ObjectPath}; + +/// Mock implementation of org.kde.secretprompter +/// +/// This simulates the Plasma System Prompter for testing without requiring +/// the actual service to be running. +#[derive(Clone)] +pub(crate) struct MockPrompterServicePlasma { + /// The password to use for unlock prompts (simulates user input) + unlock_password: Arc>>, + /// Whether to accept (true) or dismiss (false) prompts + should_accept: Arc>, + /// Queue of passwords to use for for testing retry logic + password_queue: Arc>>, +} + +#[allow(unused)] +impl MockPrompterServicePlasma { + pub fn new() -> Self { + Self { + unlock_password: Arc::new(tokio::sync::Mutex::new(Some(Secret::from( + "test-password-long-enough", + )))), + should_accept: Arc::new(tokio::sync::Mutex::new(true)), + password_queue: Arc::new(tokio::sync::Mutex::new(Vec::new())), + } + } + + /// Set whether prompts should be accepted or dismissed + pub async fn set_accept(&self, accept: bool) { + *self.should_accept.lock().await = accept; + } + + pub async fn set_password_queue(&self, passwords: Vec) { + *self.password_queue.lock().await = passwords; + } + + pub async fn send_secret( + connection: &zbus::Connection, + callback_path: &ObjectPath<'_>, + secret: &Secret, + ) -> zbus::fdo::Result<()> { + let callback_path = callback_path.to_owned(); + let connection = connection.clone(); + let secret = secret.clone(); + + // Accepted case + tokio::spawn(async move { + tracing::debug!( + "MockPrompterServicePlasma: calling Accepted on {}", + callback_path + ); + + let (read_end, mut write_end) = + UnixStream::pair().expect("Failed to create socketpair"); + read_end.set_nonblocking(true).unwrap(); + write_end.set_nonblocking(true).unwrap(); + write_end.write_all(secret.as_bytes()).unwrap(); + drop(write_end); // Close write end to signal EOF + + connection + .call_method( + None::<()>, // No destination in p2p + &callback_path, + Some("org.kde.secretprompter.request"), + "Accepted", + &(Fd::Owned(read_end.into())), + ) + .await?; + + tracing::debug!( + "MockPrompterServicePlasma: Accepted completed for {}", + callback_path + ); + Ok::<_, zbus::Error>(()) + }); + + Ok(()) + } +} + +#[allow(unused)] +#[zbus::interface(name = "org.kde.secretprompter")] +impl MockPrompterServicePlasma { + async fn unlock_collection_prompt( + &self, + request: ObjectPath<'_>, + _window_id: &str, + _activation_token: &str, + _collection_name: &str, + #[zbus(connection)] connection: &zbus::Connection, + ) -> zbus::fdo::Result<()> { + tracing::debug!( + "MockPrompterServicePlasma: unlock_collection_prompt called for {}", + request + ); + + let callback_path = request.to_owned(); + let connection = connection.clone(); + + // Reject case + if !*self.should_accept.lock().await { + tokio::spawn(async move { + tracing::debug!( + "MockPrompterServicePlasma: dismissing prompt for {}", + callback_path + ); + + connection + .call_method( + None::<()>, // No destination in p2p + &callback_path, + Some("org.kde.secretprompter.request"), + "Rejected", + &(), + ) + .await + .unwrap(); + + tracing::debug!( + "MockPrompterServicePlasma: Dismissed completed for {}", + callback_path + ); + }); + return Ok(()); + } + + let mut queue = self.password_queue.lock().await.clone(); + self.password_queue.lock().await.clear(); + if !queue.is_empty() { + tokio::spawn(async move { + let proxy: zbus::proxy::Proxy<'_> = zbus::proxy::Builder::new(&connection) + .destination("org.kde.client") // apparently unused but still required for p2p + .path(callback_path.clone()) + .interface("org.kde.secretprompter.request") + .build() + .await + .unwrap(); + let mut signal_stream = proxy.receive_signal("Retry").await.unwrap(); + + loop { + let secret = queue.remove(0); + MockPrompterServicePlasma::send_secret(&connection, &callback_path, &secret) + .await + .unwrap(); + + if queue.is_empty() { + break; + } + + // Wait for Retry signal before sending next secret from the + // queue + signal_stream.next().await; + } + }); + } else { + let pwd = self.unlock_password.lock().await.clone().unwrap(); + tracing::debug!( + "MockPrompterServicePlasma: using default password (length: {})", + pwd.as_str().unwrap_or("") + ); + MockPrompterServicePlasma::send_secret(&connection, &callback_path, &pwd).await?; + }; + + Ok(()) + } + + async fn create_collection_prompt( + &self, + request: ObjectPath<'_>, + window_id: &str, + activation_token: &str, + collection_name: &str, + #[zbus(connection)] connection: &zbus::Connection, + ) -> zbus::fdo::Result<()> { + tracing::debug!( + "MockPrompterServicePlasma: create_collection_prompt called for {}", + request + ); + // Behavior is identical for both prompts. Visualization would be + // different. + self.unlock_collection_prompt( + request, + window_id, + activation_token, + collection_name, + connection, + ) + .await?; + Ok(()) + } +} diff --git a/server/src/plasma/mod.rs b/server/src/plasma/mod.rs index 14e66ea7..51280c69 100644 --- a/server/src/plasma/mod.rs +++ b/server/src/plasma/mod.rs @@ -2,3 +2,5 @@ // SPDX-FileCopyrightText: 2025 Harald Sitter pub mod prompter; + +pub(crate) mod mock_prompter; diff --git a/server/src/tests.rs b/server/src/tests.rs index 4bd24162..fd751bb6 100644 --- a/server/src/tests.rs +++ b/server/src/tests.rs @@ -1,16 +1,12 @@ -use std::{collections::HashMap, io::Write, os::unix::net::UnixStream, sync::Arc}; +use std::{os::unix::net::UnixStream, sync::Arc}; -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -use base64::Engine; -use oo7::{Secret, crypto, dbus, file::UnlockedKeyring}; +use oo7::{Secret, dbus, file::UnlockedKeyring}; use tokio_stream::StreamExt; -use zbus::wire::{Fd, ObjectPath, Optional, Variant}; #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -use crate::gnome::{ - prompter::{PromptType, Properties, Reply}, - secret_exchange, -}; +use crate::gnome::mock_prompter::MockPrompterServiceGNOME; +#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] +use crate::plasma::mock_prompter::MockPrompterServicePlasma; use crate::service::{PrompterType, Service}; pub(crate) async fn assert_next_signal( @@ -42,12 +38,48 @@ pub(crate) async fn create_p2p_connection() Ok((server_conn, client_conn)) } +struct MockPrompters { + #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] + gnome: MockPrompterServiceGNOME, + #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] + plasma: MockPrompterServicePlasma, +} + +impl MockPrompters { + async fn register( + conn: &zbus::Connection, + ) -> Result> { + #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] + let gnome = { + let prompter = MockPrompterServiceGNOME::new(); + conn.object_server() + .at("/org/gnome/keyring/Prompter", prompter.clone()) + .await?; + prompter + }; + #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] + let plasma = { + let prompter = MockPrompterServicePlasma::new(); + conn.object_server() + .at("/SecretPrompter", prompter.clone()) + .await?; + prompter + }; + Ok(Self { + #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] + gnome, + #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] + plasma, + }) + } +} + struct ServerSetup { server: Service, client_conn: zbus::Connection, service_api: dbus::api::Service, #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] - mock_prompter: MockPrompterService, + mock_prompter: MockPrompterServiceGNOME, #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] mock_prompter_plasma: MockPrompterServicePlasma, temp_dir: tempfile::TempDir, @@ -63,7 +95,7 @@ pub struct TestServiceSetup { pub keyring_secret: Option, pub aes_key: Option>, #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] - pub(crate) mock_prompter: MockPrompterService, + pub(crate) mock_prompter: MockPrompterServiceGNOME, #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] pub(crate) mock_prompter_plasma: MockPrompterServicePlasma, // Keep temp dir alive for duration of test @@ -94,24 +126,7 @@ impl TestServiceSetup { .await?; server.set_prompter_type(PrompterType::GNOME).await; - #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] - let mock_prompter = { - let mock_prompter = MockPrompterService::new(); - client_conn - .object_server() - .at("/org/gnome/keyring/Prompter", mock_prompter.clone()) - .await?; - mock_prompter - }; - #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] - let mock_prompter_plasma = { - let mock_prompter_plasma = MockPrompterServicePlasma::new(); - client_conn - .object_server() - .at("/SecretPrompter", mock_prompter_plasma.clone()) - .await?; - mock_prompter_plasma - }; + let prompters = MockPrompters::register(&client_conn).await?; tokio::time::sleep(tokio::time::Duration::from_millis(50)).await; @@ -122,9 +137,9 @@ impl TestServiceSetup { client_conn, service_api, #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] - mock_prompter, + mock_prompter: prompters.gnome, #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] - mock_prompter_plasma, + mock_prompter_plasma: prompters.plasma, temp_dir, }) } @@ -266,25 +281,7 @@ impl TestServiceSetup { .await?; service.set_prompter_type(PrompterType::GNOME).await; - #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] - let mock_prompter = { - let mock_prompter = MockPrompterService::new(); - client_conn - .object_server() - .at("/org/gnome/keyring/Prompter", mock_prompter.clone()) - .await?; - mock_prompter - }; - - #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] - let mock_prompter_plasma = { - let mock_prompter_plasma = MockPrompterServicePlasma::new(); - client_conn - .object_server() - .at("/SecretPrompter", mock_prompter_plasma.clone()) - .await?; - mock_prompter_plasma - }; + let prompters = MockPrompters::register(&client_conn).await?; tokio::time::sleep(tokio::time::Duration::from_millis(50)).await; @@ -306,9 +303,9 @@ impl TestServiceSetup { server_public_key, aes_key: None, #[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] - mock_prompter, + mock_prompter: prompters.gnome, #[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] - mock_prompter_plasma, + mock_prompter_plasma: prompters.plasma, temp_dir, }) } @@ -454,428 +451,3 @@ impl TestServiceSetup { Ok(()) } } - -/// Mock implementation of org.gnome.keyring.internal.Prompter -/// -/// This simulates the GNOME System Prompter for testing without requiring -/// the actual GNOME keyring prompter service to be running. -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[derive(Clone)] -pub(crate) struct MockPrompterService { - /// The password to use for unlock prompts (simulates user input) - unlock_password: Arc>>, - /// Whether to accept (true) or dismiss (false) prompts - should_accept: Arc>, - /// Queue of passwords to use for for testing retry logic - password_queue: Arc>>, -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -impl MockPrompterService { - pub fn new() -> Self { - Self { - unlock_password: Arc::new(tokio::sync::Mutex::new(Some(oo7::Secret::from( - "test-password-long-enough", - )))), - should_accept: Arc::new(tokio::sync::Mutex::new(true)), - password_queue: Arc::new(tokio::sync::Mutex::new(Vec::new())), - } - } - - /// Set whether prompts should be accepted or dismissed - pub async fn set_accept(&self, accept: bool) { - *self.should_accept.lock().await = accept; - } - - pub async fn set_password_queue(&self, passwords: Vec) { - *self.password_queue.lock().await = passwords; - } -} - -#[cfg(any(feature = "gnome_native_crypto", feature = "gnome_openssl_crypto"))] -#[zbus::interface(name = "org.gnome.keyring.internal.Prompter")] -impl MockPrompterService { - async fn begin_prompting( - &self, - callback: ObjectPath<'_>, - #[zbus(connection)] connection: &zbus::Connection, - ) -> zbus::fdo::Result<()> { - tracing::debug!("MockPrompter: begin_prompting called for {}", callback); - let callback_path = callback.to_owned(); - let connection = connection.clone(); - - // Spawn a task to send the initial prompt_ready call - tokio::spawn(async move { - tracing::debug!("MockPrompter: spawned task starting"); - // Small delay to ensure callback is fully registered - tokio::time::sleep(tokio::time::Duration::from_millis(10)).await; - - // Call PromptReady directly without building a proxy (avoids - // introspection issues in p2p) - tracing::debug!( - "MockPrompter: calling PromptReady with None on {}", - callback_path - ); - let properties: HashMap = HashMap::new(); - let empty_exchange = ""; - - connection - .call_method( - None::<()>, // No destination in p2p - &callback_path, - Some("org.gnome.keyring.internal.Prompter.Callback"), - "PromptReady", - &(Optional::::from(None), properties, empty_exchange), - ) - .await?; - - tracing::debug!("MockPrompter: PromptReady(None) completed"); - Ok::<_, zbus::Error>(()) - }); - - Ok(()) - } - - async fn perform_prompt( - &self, - callback: ObjectPath<'_>, - type_: PromptType, - _properties: Properties, - exchange: &str, - #[zbus(connection)] connection: &zbus::Connection, - ) -> zbus::fdo::Result<()> { - tracing::debug!( - "MockPrompter: perform_prompt called for {}, type={:?}", - callback, - type_ - ); - // This is called by GNOMEPrompterCallback.prompter_init() with the - // server's exchange - let callback_path = callback.to_owned(); - let unlock_password = self.unlock_password.clone(); - let should_accept = self.should_accept.clone(); - let password_queue = self.password_queue.clone(); - let exchange = exchange.to_owned(); - let connection = connection.clone(); - - // Spawn a task to simulate user interaction and send final response - tokio::spawn(async move { - tracing::debug!("MockPrompter: perform_prompt task starting"); - // Small delay to simulate user interaction - tokio::time::sleep(tokio::time::Duration::from_millis(10)).await; - - let accept = *should_accept.lock().await; - let properties: HashMap = HashMap::new(); - - if !accept { - tracing::debug!("MockPrompter: dismissing prompt"); - // Dismiss the prompt - connection - .call_method( - None::<()>, // No destination in p2p - &callback_path, - Some("org.gnome.keyring.internal.Prompter.Callback"), - "PromptReady", - &(Reply::No, properties, ""), - ) - .await?; - tracing::debug!("MockPrompter: PromptReady(no) completed"); - - return Ok(()); - } else if type_ == PromptType::Password { - tracing::debug!("MockPrompter: performing unlock (password prompt)"); - // Unlock prompt - perform secret exchange - - let mut queue = password_queue.lock().await; - let password = if !queue.is_empty() { - let pwd = queue.remove(0); - tracing::debug!( - "MockPrompter: using password from queue (length: {}, queue remaining: {})", - pwd.as_str().unwrap_or(""), - queue.len() - ); - pwd - } else { - let pwd = unlock_password.lock().await.clone().unwrap(); - tracing::debug!( - "MockPrompter: using default password (length: {})", - pwd.as_str().unwrap_or("") - ); - pwd - }; - drop(queue); - - // Generate our own key pair - let private_key = oo7::Key::generate_private_key().unwrap(); - let public_key = crate::gnome::crypto::generate_public_key(&private_key).unwrap(); - - // Handshake with server's exchange to get AES key - let aes_key = secret_exchange::handshake(&private_key, &exchange).unwrap(); - - // Encrypt the password - let iv = crypto::generate_iv().unwrap(); - let encrypted = crypto::encrypt(password.as_bytes(), &aes_key, &iv).unwrap(); - - // Create final exchange with encrypted secret - let final_exchange = format!( - "[sx-aes-1]\npublic={}\nsecret={}\niv={}", - base64::prelude::BASE64_STANDARD.encode(public_key.as_ref()), - base64::prelude::BASE64_STANDARD.encode(&encrypted), - base64::prelude::BASE64_STANDARD.encode(&iv) - ); - - tracing::debug!("MockPrompter: calling PromptReady with yes"); - connection - .call_method( - None::<()>, // No destination in p2p - &callback_path, - Some("org.gnome.keyring.internal.Prompter.Callback"), - "PromptReady", - &(Reply::Yes, properties, final_exchange.as_str()), - ) - .await?; - tracing::debug!("MockPrompter: PromptReady(yes) with secret exchange completed"); - } else { - tracing::debug!("MockPrompter: accepting confirm prompt"); - // Lock/confirm prompt - just accept - connection - .call_method( - None::<()>, // No destination in p2p - &callback_path, - Some("org.gnome.keyring.internal.Prompter.Callback"), - "PromptReady", - &(Reply::Yes, properties, ""), - ) - .await?; - tracing::debug!("MockPrompter: PromptReady(yes) completed"); - } - - Ok::<_, zbus::Error>(()) - }); - - Ok(()) - } - - async fn stop_prompting( - &self, - callback: ObjectPath<'_>, - #[zbus(connection)] connection: &zbus::Connection, - ) -> zbus::fdo::Result<()> { - tracing::debug!("MockPrompter: stop_prompting called for {}", callback); - let callback_path = callback.to_owned(); - let connection = connection.clone(); - - tokio::spawn(async move { - tracing::debug!("MockPrompter: calling PromptDone for {}", callback_path); - let result = connection - .call_method( - None::<()>, - &callback_path, - Some("org.gnome.keyring.internal.Prompter.Callback"), - "PromptDone", - &(), - ) - .await; - - if let Err(err) = result { - tracing::debug!("MockPrompter: PromptDone failed: {}", err); - } else { - tracing::debug!("MockPrompter: PromptDone completed for {}", callback_path); - } - }); - - Ok(()) - } -} - -/// Mock implementation of org.kde.secretprompter -/// -/// This simulates the Plasma System Prompter for testing without requiring -/// the actual service to be running. -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[derive(Clone)] -pub(crate) struct MockPrompterServicePlasma { - /// The password to use for unlock prompts (simulates user input) - unlock_password: Arc>>, - /// Whether to accept (true) or dismiss (false) prompts - should_accept: Arc>, - /// Queue of passwords to use for for testing retry logic - password_queue: Arc>>, -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -impl MockPrompterServicePlasma { - pub fn new() -> Self { - Self { - unlock_password: Arc::new(tokio::sync::Mutex::new(Some(oo7::Secret::from( - "test-password-long-enough", - )))), - should_accept: Arc::new(tokio::sync::Mutex::new(true)), - password_queue: Arc::new(tokio::sync::Mutex::new(Vec::new())), - } - } - - /// Set whether prompts should be accepted or dismissed - pub async fn set_accept(&self, accept: bool) { - *self.should_accept.lock().await = accept; - } - - pub async fn set_password_queue(&self, passwords: Vec) { - *self.password_queue.lock().await = passwords; - } - - pub async fn send_secret( - connection: &zbus::Connection, - callback_path: &ObjectPath<'_>, - secret: &oo7::Secret, - ) -> zbus::fdo::Result<()> { - let callback_path = callback_path.to_owned(); - let connection = connection.clone(); - let secret = secret.clone(); - - // Accepted case - tokio::spawn(async move { - tracing::debug!( - "MockPrompterServicePlasma: calling Accepted on {}", - callback_path - ); - - let (read_end, mut write_end) = - UnixStream::pair().expect("Failed to create socketpair"); - read_end.set_nonblocking(true).unwrap(); - write_end.set_nonblocking(true).unwrap(); - write_end.write_all(secret.as_bytes()).unwrap(); - drop(write_end); // Close write end to signal EOF - - connection - .call_method( - None::<()>, // No destination in p2p - &callback_path, - Some("org.kde.secretprompter.request"), - "Accepted", - &(Fd::Owned(read_end.into())), - ) - .await?; - - tracing::debug!( - "MockPrompterServicePlasma: Accepted completed for {}", - callback_path - ); - Ok::<_, zbus::Error>(()) - }); - - Ok(()) - } -} - -#[cfg(any(feature = "plasma_native_crypto", feature = "plasma_openssl_crypto"))] -#[zbus::interface(name = "org.kde.secretprompter")] -impl MockPrompterServicePlasma { - async fn unlock_collection_prompt( - &self, - request: ObjectPath<'_>, - _window_id: &str, - _activation_token: &str, - _collection_name: &str, - #[zbus(connection)] connection: &zbus::Connection, - ) -> zbus::fdo::Result<()> { - tracing::debug!( - "MockPrompterServicePlasma: unlock_collection_prompt called for {}", - request - ); - - let callback_path = request.to_owned(); - let connection = connection.clone(); - - // Reject case - if !*self.should_accept.lock().await { - tokio::spawn(async move { - tracing::debug!( - "MockPrompterServicePlasma: dismissing prompt for {}", - callback_path - ); - - connection - .call_method( - None::<()>, // No destination in p2p - &callback_path, - Some("org.kde.secretprompter.request"), - "Rejected", - &(), - ) - .await - .unwrap(); - - tracing::debug!( - "MockPrompterServicePlasma: Dismissed completed for {}", - callback_path - ); - }); - return Ok(()); - } - - let mut queue = self.password_queue.lock().await.clone(); - self.password_queue.lock().await.clear(); - if !queue.is_empty() { - tokio::spawn(async move { - let proxy: zbus::proxy::Proxy<'_> = zbus::proxy::Builder::new(&connection) - .destination("org.kde.client") // apparently unused but still required for p2p - .path(callback_path.clone()) - .interface("org.kde.secretprompter.request") - .build() - .await - .unwrap(); - let mut signal_stream = proxy.receive_signal("Retry").await.unwrap(); - - loop { - let secret = queue.remove(0); - MockPrompterServicePlasma::send_secret(&connection, &callback_path, &secret) - .await - .unwrap(); - - if queue.is_empty() { - break; - } - - // Wait for Retry signal before sending next secret from the - // queue - signal_stream.next().await; - } - }); - } else { - let pwd = self.unlock_password.lock().await.clone().unwrap(); - tracing::debug!( - "MockPrompterServicePlasma: using default password (length: {})", - pwd.as_str().unwrap_or("") - ); - MockPrompterServicePlasma::send_secret(&connection, &callback_path, &pwd).await?; - }; - - Ok(()) - } - - async fn create_collection_prompt( - &self, - request: ObjectPath<'_>, - window_id: &str, - activation_token: &str, - collection_name: &str, - #[zbus(connection)] connection: &zbus::Connection, - ) -> zbus::fdo::Result<()> { - tracing::debug!( - "MockPrompterServicePlasma: create_collection_prompt called for {}", - request - ); - // Behavior is identical for both prompts. Visualization would be - // different. - self.unlock_collection_prompt( - request, - window_id, - activation_token, - collection_name, - connection, - ) - .await?; - Ok(()) - } -} From cba618b2f9e0a72711657ae86eab0ef852c9e882 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Wed, 11 Nov 2026 20:23:12 +0100 Subject: [PATCH 11/12] client: Remove redundant file keyring tests --- client/tests/file_unlocked_keyring.rs | 96 +-------------------------- 1 file changed, 1 insertion(+), 95 deletions(-) diff --git a/client/tests/file_unlocked_keyring.rs b/client/tests/file_unlocked_keyring.rs index 4796a3d1..33950c7a 100644 --- a/client/tests/file_unlocked_keyring.rs +++ b/client/tests/file_unlocked_keyring.rs @@ -343,21 +343,6 @@ async fn write_with_short_password() -> Result<(), Error> { Ok(()) } -#[tokio::test] -async fn write_with_strong_key() -> Result<(), Error> { - let temp_dir = tempdir()?; - let path = temp_dir.path().join("write_with_strong_key.keyring"); - - let keyring = UnlockedKeyring::load(&path, Some(strong_key())).await?; - let attributes: HashMap<&str, &str> = HashMap::default(); - - keyring - .create_item("label", &attributes, "my-password", false) - .await?; - - Ok(()) -} - #[tokio::test] async fn concurrent_writes() -> Result<(), Error> { let temp_dir = tempdir()?; @@ -666,40 +651,6 @@ async fn change_secret() -> Result<(), Error> { Ok(()) } -#[tokio::test] -async fn content_type() -> Result<(), Error> { - let keyring = UnlockedKeyring::temporary(Secret::blob("test_password")).await?; - - // Add items with different MIME types - keyring - .create_item( - "Text", - &[("type", "text")], - Secret::text("Hello, World!"), - false, - ) - .await?; - - keyring - .create_item( - "Password", - &[("type", "password")], - Secret::blob("super_secret_password"), - false, - ) - .await?; - - let items = keyring.search_items(&[("type", "text")]).await?; - assert_eq!(items.len(), 1); - assert_eq!(items[0].secret().content_type(), oo7::ContentType::Text); - - let items = keyring.search_items(&[("type", "password")]).await?; - assert_eq!(items.len(), 1); - assert_eq!(items[0].secret().content_type(), oo7::ContentType::Blob); - - Ok(()) -} - #[tokio::test] async fn wrong_password_error_type() -> Result<(), Error> { let temp_dir = tempdir().unwrap(); @@ -1160,6 +1111,7 @@ async fn item_attribute_operations() -> Result<(), Error> { updated_attrs.get("new_attr").unwrap().to_string(), "new_value" ); + assert_eq!(updated_items[0].secret(), Secret::text("test-secret")); Ok(()) } @@ -1364,52 +1316,6 @@ async fn replace_item_index_invalid() -> Result<(), Error> { Ok(()) } -#[tokio::test] -async fn set_attributes() -> Result<(), Error> { - let data_dir = tempdir().unwrap(); - let dir = data_dir.path().join("keyrings"); - fs::create_dir_all(&dir).await.unwrap(); - let path = dir.join("default.keyring"); - - let keyring = UnlockedKeyring::load(&path, Some(strong_key())).await?; - - let items = keyring.items().await?; - assert_eq!(items.len(), 0); - - keyring - .create_item("my item", &vec![("key", "value")], "my_secret", false) - .await?; - - let mut items = keyring.items().await?; - assert_eq!(items.len(), 1); - let mut item = items.remove(0); - assert_eq!(item.label(), "my item"); - assert_eq!(item.secret(), Secret::text("my_secret")); - let attrs = item.attributes(); - assert_eq!(attrs.len(), 2); - assert_eq!(attrs.get("key").unwrap(), "value"); - - // Update attributes on the item - item.set_attributes(&vec![("key", "changed_value"), ("new_key", "new_value")]); - - // Write the updated item back to the keyring at index 0 - keyring.replace_item_index(0, &item).await?; - - // Now retrieve the item again from the keyring to verify the changes - // persisted - let mut items = keyring.items().await?; - assert_eq!(items.len(), 1); - let item = items.remove(0); - assert_eq!(item.label(), "my item"); - assert_eq!(item.secret(), Secret::text("my_secret")); - let attrs = item.attributes(); - assert_eq!(attrs.len(), 3); - assert_eq!(attrs.get("key").unwrap(), "changed_value"); - assert_eq!(attrs.get("new_key").unwrap(), "new_value"); - - Ok(()) -} - #[tokio::test] async fn replace_item_without_schema() -> Result<(), Error> { let keyring = UnlockedKeyring::temporary(Secret::blob("test_password")).await?; From e6198fe5d1f2db97eabd666328d41ee9ea58c058 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Wed, 11 Nov 2026 21:21:45 +0100 Subject: [PATCH 12/12] client: Split file keyring tests into per-area modules --- client/tests/file_unlocked_keyring.rs | 1357 ----------------- client/tests/file_unlocked_keyring/errors.rs | 167 ++ client/tests/file_unlocked_keyring/items.rs | 588 +++++++ .../tests/file_unlocked_keyring/lifecycle.rs | 449 ++++++ client/tests/file_unlocked_keyring/main.rs | 27 + .../tests/file_unlocked_keyring/migration.rs | 100 ++ .../file_unlocked_keyring/persistence.rs | 62 + 7 files changed, 1393 insertions(+), 1357 deletions(-) delete mode 100644 client/tests/file_unlocked_keyring.rs create mode 100644 client/tests/file_unlocked_keyring/errors.rs create mode 100644 client/tests/file_unlocked_keyring/items.rs create mode 100644 client/tests/file_unlocked_keyring/lifecycle.rs create mode 100644 client/tests/file_unlocked_keyring/main.rs create mode 100644 client/tests/file_unlocked_keyring/migration.rs create mode 100644 client/tests/file_unlocked_keyring/persistence.rs diff --git a/client/tests/file_unlocked_keyring.rs b/client/tests/file_unlocked_keyring.rs deleted file mode 100644 index 33950c7a..00000000 --- a/client/tests/file_unlocked_keyring.rs +++ /dev/null @@ -1,1357 +0,0 @@ -use std::{collections::HashMap, path::PathBuf, sync::Arc}; - -#[cfg(feature = "async-std")] -use async_std::fs; -use oo7::{Key, Secret, XDG_SCHEMA_ATTRIBUTE, file::*}; -use tempfile::tempdir; -#[cfg(feature = "tokio")] -use tokio::fs; - -fn strong_key() -> Secret { - Secret::from([1, 2].into_iter().cycle().take(64).collect::>()) -} - -#[tokio::test] -async fn validate_and_unlock_with_key() -> Result<(), Error> { - let temp_dir = tempdir()?; - let path = temp_dir.path().join("key-unlock.keyring"); - let keyring = UnlockedKeyring::load(&path, Some(strong_key())).await?; - keyring - .create_item("Item", &[("account", "alice")], "secret", false) - .await?; - let key = keyring.key().await?.unwrap(); - let key = key.as_ref().as_ref().to_vec(); - drop(keyring); - - let locked = LockedKeyring::load(&path).await?; - assert!(!locked.validate_key(&Key::new(vec![9; 16])).await?); - assert!(locked.validate_key(&Key::new(key.clone())).await?); - - let locked_with_wrong_key = LockedKeyring::load(&path).await?; - assert!(matches!( - locked_with_wrong_key - .unlock_with_key(Key::new(vec![9; 16])) - .await, - Err(Error::IncorrectSecret) - )); - - let keyring = locked.unlock_with_key(Key::new(key.clone())).await?; - let cached_key = keyring.key().await?.unwrap(); - assert_eq!(cached_key.as_ref().as_ref(), key); - let item = keyring.lookup_item(&[("account", "alice")]).await?.unwrap(); - assert_eq!(item.secret(), Secret::text("secret")); - - Ok(()) -} - -#[tokio::test] -async fn malformed_file_keys_are_rejected() -> Result<(), Error> { - let temp_dir = tempdir()?; - let path = temp_dir.path().join("invalid-key-length.keyring"); - let keyring = UnlockedKeyring::load(&path, Some(strong_key())).await?; - keyring - .create_item("Item", &[("account", "alice")], "secret", false) - .await?; - drop(keyring); - - for actual in [0, 15, 17, 32] { - let locked = LockedKeyring::load(&path).await?; - assert!(matches!( - locked.validate_key(&Key::new(vec![0; actual])).await, - Err(Error::InvalidKeyLength { - expected: 16, - actual: error_actual, - }) if error_actual == actual - )); - - let locked = LockedKeyring::load(&path).await?; - assert!(matches!( - locked.unlock_with_key(Key::new(vec![0; actual])).await, - Err(Error::InvalidKeyLength { - expected: 16, - actual: error_actual, - }) if error_actual == actual - )); - } - - Ok(()) -} - -#[tokio::test] -async fn key_only_lifecycle_and_password_change() -> Result<(), Error> { - let temp_dir = tempdir()?; - let path = temp_dir.path().join("key-lifecycle.keyring"); - let original_secret = strong_key(); - let keyring = UnlockedKeyring::load(&path, Some(original_secret.clone())).await?; - keyring - .create_item("Original", &[("id", "original")], "before", false) - .await?; - let key = keyring.key().await?.unwrap(); - let key = key.as_ref().as_ref().to_vec(); - drop(keyring); - - let keyring = UnlockedKeyring::load_with_key(&path, Key::new(key.clone())).await?; - let cached_key = keyring.key().await?.unwrap(); - assert_eq!(cached_key.as_ref().as_ref(), key); - let mut original = keyring.lookup_item(&[("id", "original")]).await?.unwrap(); - original.set_secret("after"); - keyring.replace_item_index(0, &original).await?; - keyring - .create_item("Added", &[("id", "added")], "created", false) - .await?; - drop(keyring); - - let locked = LockedKeyring::load(&path).await?; - assert!(locked.validate_key(&Key::new(key.clone())).await?); - let keyring = UnlockedKeyring::load_with_key(&path, Key::new(key)).await?; - assert_eq!( - keyring - .lookup_item(&[("id", "original")]) - .await? - .unwrap() - .secret(), - Secret::text("after") - ); - assert_eq!( - keyring - .lookup_item(&[("id", "added")]) - .await? - .unwrap() - .secret(), - Secret::text("created") - ); - - let replacement_secret = Secret::blob(vec![3; 64]); - keyring.change_secret(replacement_secret.clone()).await?; - drop(keyring); - - assert!( - UnlockedKeyring::load(&path, Some(original_secret)) - .await - .is_err() - ); - let keyring = UnlockedKeyring::load(&path, Some(replacement_secret)).await?; - assert_eq!(keyring.n_items().await, 2); - - Ok(()) -} - -#[tokio::test] -async fn empty_keyring_cannot_authenticate_key() -> Result<(), Error> { - let temp_dir = tempdir()?; - let path = temp_dir.path().join("empty-key.keyring"); - let keyring = UnlockedKeyring::load(&path, Some(strong_key())).await?; - assert!(keyring.key().await?.is_some()); - keyring.write().await?; - drop(keyring); - - let locked = LockedKeyring::load(&path).await?; - assert!(locked.validate_key(&Key::new(vec![9; 16])).await?); - let keyring = locked.unlock_with_key(Key::new(vec![9; 16])).await?; - keyring - .create_item("Rebound", &[("id", "rebound")], "secret", false) - .await?; - drop(keyring); - - assert!( - UnlockedKeyring::load(&path, Some(strong_key())) - .await - .is_err() - ); - let keyring = UnlockedKeyring::load_with_key(&path, Key::new(vec![9; 16])).await?; - assert_eq!(keyring.n_items().await, 1); - - Ok(()) -} - -#[tokio::test] -async fn unencrypted_keyring_requires_no_key() -> Result<(), Error> { - let temp_dir = tempdir()?; - let path = temp_dir.path().join("unencrypted-key.keyring"); - let keyring = UnlockedKeyring::load(&path, None).await?; - keyring - .create_item("Plain", &[("id", "plain")], "secret", false) - .await?; - drop(keyring); - - let locked = LockedKeyring::load(&path).await?; - assert!(!locked.validate_key(&Key::new(vec![1; 16])).await?); - assert!(matches!( - locked.unlock_with_key(Key::new(vec![1; 16])).await, - Err(Error::IncorrectSecret) - )); - - let keyring = LockedKeyring::load(&path) - .await? - .unlock_unencrypted() - .await?; - assert!(keyring.key().await?.is_none()); - assert_eq!(keyring.n_items().await, 1); - - Ok(()) -} - -#[tokio::test] -async fn open_at_with_key_uses_named_current_keyring() -> Result<(), Error> { - let data_dir = tempdir()?; - let keyring = UnlockedKeyring::open_at(data_dir.path(), "named", Some(strong_key())).await?; - keyring - .create_item("Named", &[("id", "named")], "secret", false) - .await?; - let key = keyring.key().await?.unwrap(); - let key = key.as_ref().as_ref().to_vec(); - drop(keyring); - - let keyring = - UnlockedKeyring::open_at_with_key(data_dir.path(), "named", Key::new(key)).await?; - assert_eq!( - keyring - .lookup_item(&[("id", "named")]) - .await? - .unwrap() - .secret(), - Secret::text("secret") - ); - - let direct_key = vec![4; 16]; - let direct = UnlockedKeyring::open_at_with_key( - data_dir.path(), - "new-with-key", - Key::new(direct_key.clone()), - ) - .await?; - direct - .create_item("Direct", &[("id", "direct")], "secret", false) - .await?; - drop(direct); - let direct = - UnlockedKeyring::open_at_with_key(data_dir.path(), "new-with-key", Key::new(direct_key)) - .await?; - assert_eq!(direct.n_items().await, 1); - - Ok(()) -} - -#[tokio::test] -async fn open_at_with_key_ignores_legacy_keyring() -> Result<(), Error> { - let data_dir = tempdir()?; - let keyrings_dir = data_dir.path().join("keyrings"); - fs::create_dir_all(&keyrings_dir).await?; - let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("default.keyring"); - let v0_path = keyrings_dir.join("named.keyring"); - let v1_path = keyrings_dir.join("v1").join("named.keyring"); - fs::copy(fixture, &v0_path).await?; - let v0_bytes = fs::read(&v0_path).await?; - let v0_metadata = fs::metadata(&v0_path).await?; - assert!(!v1_path.exists()); - - let key = vec![1; 16]; - let keyring = - UnlockedKeyring::open_at_with_key(data_dir.path(), "named", Key::new(key.clone())).await?; - assert_eq!(keyring.n_items().await, 0); - assert!(!v1_path.exists()); - assert_eq!(fs::read(&v0_path).await?, v0_bytes); - assert_eq!(fs::metadata(&v0_path).await?.len(), v0_metadata.len()); - assert_eq!( - fs::metadata(&v0_path).await?.modified()?, - v0_metadata.modified()? - ); - - keyring - .create_item("Direct", &[("id", "direct")], "secret", false) - .await?; - drop(keyring); - assert!(v1_path.exists()); - assert_eq!(fs::read(&v0_path).await?, v0_bytes); - - let keyring = - UnlockedKeyring::open_at_with_key(data_dir.path(), "named", Key::new(key)).await?; - assert_eq!( - keyring - .lookup_item(&[("id", "direct")]) - .await? - .unwrap() - .secret(), - Secret::text("secret") - ); - drop(keyring); - assert!(matches!( - UnlockedKeyring::open_at_with_key(data_dir.path(), "named", Key::new(vec![2; 16])).await, - Err(Error::IncorrectSecret) - )); - - Ok(()) -} - -#[tokio::test] -async fn repeated_write() -> Result<(), Error> { - let temp_dir = tempdir()?; - let path = temp_dir.path().join("test.keyring"); - - let secret = Secret::from(vec![1, 2]); - let keyring = UnlockedKeyring::load(&path, Some(secret)).await?; - - keyring.write().await?; - keyring.write().await?; - - Ok(()) -} - -#[tokio::test] -async fn delete() -> Result<(), Error> { - let temp_dir = tempdir()?; - let path = temp_dir.path().join("test-delete.keyring"); - - let keyring = UnlockedKeyring::load(&path, Some(strong_key())).await?; - let attributes: HashMap<&str, &str> = HashMap::default(); - keyring - .create_item("Label", &attributes, "secret", false) - .await?; - - keyring.delete_item_index(0).await?; - - let result = keyring.delete_item_index(100).await; - - assert!(matches!(result, Err(Error::InvalidItemIndex(100)))); - - Ok(()) -} - -#[tokio::test] -async fn write_with_short_password() -> Result<(), Error> { - let temp_dir = tempdir()?; - let path = temp_dir.path().join("write_with_short_password.keyring"); - - // Password policy is up to the caller, e.g. keyrings migrated from - // gnome-keyring can have any password. - let secret = Secret::from(vec![1]); - let keyring = UnlockedKeyring::load(&path, Some(secret.clone())).await?; - let attributes: HashMap<&str, &str> = HashMap::default(); - - keyring - .create_item("label", &attributes, "my-password", false) - .await?; - keyring.write().await?; - - let keyring = UnlockedKeyring::load(&path, Some(secret)).await?; - let items = keyring.items().await?; - assert_eq!(items.len(), 1); - assert_eq!(items[0].secret(), Secret::text("my-password")); - - Ok(()) -} - -#[tokio::test] -async fn concurrent_writes() -> Result<(), Error> { - let temp_dir = tempdir()?; - let path = temp_dir.path().join("concurrent_writes.keyring"); - - let keyring = Arc::new(UnlockedKeyring::load(&path, Some(strong_key())).await?); - - let keyring_clone = keyring.clone(); - let handle_1 = tokio::task::spawn(async move { keyring_clone.write().await }); - let handle_2 = tokio::task::spawn(async move { keyring.write().await }); - - let (res_1, res_2) = futures_util::future::join(handle_1, handle_2).await; - res_1.unwrap()?; - res_2.unwrap()?; - - Ok(()) -} - -async fn check_items(keyring: &UnlockedKeyring) -> Result<(), Error> { - assert_eq!(keyring.n_items().await, 1); - let items = keyring.items().await?; - assert_eq!(items.len(), 1); - assert_eq!(items[0].label(), "foo"); - assert_eq!(items[0].secret(), Secret::blob("foo")); - let attributes = items[0].attributes(); - assert_eq!(attributes.len(), 2); - assert_eq!( - attributes - .get(crate::XDG_SCHEMA_ATTRIBUTE) - .map(|v| v.as_ref()), - Some("org.gnome.keyring.Note") - ); - - Ok(()) -} - -#[tokio::test] -async fn migrate_from_legacy() -> Result<(), Error> { - let data_dir = tempdir()?; - let v0_dir = data_dir.path().join("keyrings"); - let v1_dir = v0_dir.join("v1"); - fs::create_dir_all(&v1_dir).await?; - - let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("legacy.keyring"); - fs::copy(&fixture_path, &v0_dir.join("default.keyring")).await?; - - assert!(!v1_dir.join("default.keyring").exists()); - - let secret = Secret::blob("test"); - let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await?; - - check_items(&keyring).await?; - - keyring.write().await?; - assert!(v1_dir.join("default.keyring").exists()); - - Ok(()) -} - -async fn migrate_from_plain_legacy(secret: Option) -> Result<(), Error> { - let data_dir = tempdir()?; - let v0_dir = data_dir.path().join("keyrings"); - let v1_dir = v0_dir.join("v1"); - fs::create_dir_all(&v1_dir).await?; - - let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("plain.keyring"); - fs::copy(&fixture_path, &v0_dir.join("login.keyring")).await?; - - let keyring = UnlockedKeyring::open_at(data_dir.path(), "login", secret.clone()).await?; - keyring.write().await?; - assert!(v1_dir.join("login.keyring").exists()); - - let keyring = UnlockedKeyring::open_at(data_dir.path(), "login", secret).await?; - let items = keyring - .search_items(&[(XDG_SCHEMA_ATTRIBUTE, "org.remmina.Password")]) - .await?; - assert_eq!(items.len(), 1); - assert_eq!(items[0].label(), "Remmina: Shore - password"); - assert_eq!(items[0].secret(), Secret::text("some password")); - assert_eq!(keyring.n_items().await, 3); - - Ok(()) -} - -#[tokio::test] -async fn migrate_from_plain_legacy_without_secret() -> Result<(), Error> { - migrate_from_plain_legacy(None).await -} - -#[tokio::test] -async fn migrate_from_plain_legacy_with_secret() -> Result<(), Error> { - migrate_from_plain_legacy(Some(Secret::blob("test"))).await -} - -#[tokio::test] -async fn migrate_from_plain_legacy_with_short_secret() -> Result<(), Error> { - migrate_from_plain_legacy(Some(Secret::from(vec![1]))).await -} - -#[tokio::test] -async fn migrate() -> Result<(), Error> { - let data_dir = tempdir()?; - let v0_dir = data_dir.path().join("keyrings"); - let v1_dir = v0_dir.join("v1"); - fs::create_dir_all(&v1_dir).await?; - - let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("default.keyring"); - fs::copy(&fixture_path, &v0_dir.join("default.keyring")).await?; - - let secret = Secret::blob("test"); - let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await?; - - assert!(!v1_dir.join("default.keyring").exists()); - - check_items(&keyring).await?; - - keyring.write().await?; - assert!(v1_dir.join("default.keyring").exists()); - - Ok(()) -} - -#[tokio::test] -async fn open_wrong_password() -> Result<(), Error> { - let data_dir = tempdir()?; - let v0_dir = data_dir.path().join("keyrings"); - let v1_dir = v0_dir.join("v1"); - fs::create_dir_all(&v1_dir).await?; - - let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("default.keyring"); - fs::copy(&fixture_path, &v1_dir.join("default.keyring")).await?; - - let secret = Secret::blob("wrong"); - let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await; - - assert!(keyring.is_err()); - assert!(matches!(keyring.unwrap_err(), Error::IncorrectSecret)); - - let secret = Secret::blob("test"); - let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await; - - assert!(keyring.is_ok()); - - Ok(()) -} - -#[tokio::test] -async fn open() -> Result<(), Error> { - let data_dir = tempdir()?; - let v0_dir = data_dir.path().join("keyrings"); - let v1_dir = v0_dir.join("v1"); - fs::create_dir_all(&v1_dir).await?; - - let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("default.keyring"); - fs::copy(&fixture_path, &v1_dir.join("default.keyring")).await?; - - let secret = Secret::blob("test"); - let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await?; - - assert!(v1_dir.join("default.keyring").exists()); - - check_items(&keyring).await?; - - keyring.write().await?; - assert!(v1_dir.join("default.keyring").exists()); - - Ok(()) -} - -#[tokio::test] -async fn open_nonexistent() -> Result<(), Error> { - let data_dir = tempdir()?; - let v0_dir = data_dir.path().join("keyrings"); - let v1_dir = v0_dir.join("v1"); - fs::create_dir_all(&v1_dir).await?; - - let secret = Secret::blob("test"); - let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await?; - - assert!(!v1_dir.join("default.keyring").exists()); - - keyring - .create_item( - "foo", - &[(crate::XDG_SCHEMA_ATTRIBUTE, "org.gnome.keyring.Note")], - "foo", - false, - ) - .await?; - keyring.write().await?; - - assert!(v1_dir.join("default.keyring").exists()); - - Ok(()) -} - -#[tokio::test] -async fn delete_broken_items() -> Result<(), Error> { - const VALID_TO_ADD: usize = 5; - const BROKEN_TO_ADD: usize = 3; - - let data_dir = tempdir()?; - let v0_dir = data_dir.path().join("keyrings"); - let v1_dir = v0_dir.join("v1"); - fs::create_dir_all(&v1_dir).await?; - - let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("default.keyring"); - let keyring_path = v1_dir.join("default.keyring"); - fs::copy(&fixture_path, &keyring_path).await?; - - // 1) Load with the correct password and add several valid items. - // This ensures valid_items > broken_items that we'll add later. - let keyring = UnlockedKeyring::load(&keyring_path, Some(Secret::blob("test"))).await?; - for i in 0..VALID_TO_ADD { - keyring - .create_item( - &format!("valid {}", i), - &[("attr_valid", "value")], - format!("password_valid_{}", i), - false, - ) - .await?; - } - drop(keyring); - - // 2) Load_unchecked with the wrong password and add a few "broken" items. - let keyring = unsafe { - UnlockedKeyring::load_unchecked(&keyring_path, Secret::blob("wrong_password")).await? - }; - for i in 0..BROKEN_TO_ADD { - keyring - .create_item( - &format!("bad{}", i), - &[("attr_bad", "value_bad")], - format!("pw_bad{}", i), - false, - ) - .await?; - } - drop(keyring); - - // 3) Load with the correct password and run the deletion. - let keyring = UnlockedKeyring::load(&keyring_path, Some(Secret::blob("test"))).await?; - let removed = keyring.delete_broken_items().await?; - assert!( - removed >= BROKEN_TO_ADD, - "expected at least {} broken items removed, got {}", - BROKEN_TO_ADD, - removed - ); - - // Second call should find nothing left to clean up. - assert_eq!(keyring.delete_broken_items().await?, 0); - - fs::remove_file(keyring_path).await?; - Ok(()) -} - -#[tokio::test] -async fn change_secret() -> Result<(), Error> { - let data_dir = tempdir()?; - let v0_dir = data_dir.path().join("keyrings"); - let v1_dir = v0_dir.join("v1"); - fs::create_dir_all(&v1_dir).await?; - - let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("fixtures") - .join("default.keyring"); - let keyring_path = v1_dir.join("default.keyring"); - fs::copy(&fixture_path, &keyring_path).await?; - - let keyring = UnlockedKeyring::load(&keyring_path, Some(Secret::blob("test"))).await?; - let attributes = &[("attr", "value")]; - let item_before = keyring - .create_item("test", attributes, "password", false) - .await?; - - let secret = Secret::blob("new_secret"); - keyring.change_secret(secret).await?; - - let secret = Secret::blob("new_secret"); - let keyring = UnlockedKeyring::load(&keyring_path, Some(secret)).await?; - let item_now = keyring.lookup_item(attributes).await?.unwrap(); - - assert_eq!(item_before.label(), item_now.label()); - assert_eq!(item_before.secret(), item_now.secret()); - assert_eq!(item_before.attributes(), item_now.attributes()); - - // No items were broken during the secret change - assert_eq!(keyring.delete_broken_items().await?, 0); - - fs::remove_file(keyring_path).await?; - - Ok(()) -} - -#[tokio::test] -async fn wrong_password_error_type() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("wrong_password_test.keyring"); - let correct_secret = Secret::from("correct-password-that-is-long-enough".as_bytes()); - let wrong_secret = Secret::from("wrong-password-that-is-long-enough".as_bytes()); - - // Create a keyring with the correct password - let keyring = UnlockedKeyring::load(&keyring_path, Some(correct_secret)).await?; - keyring - .create_item("Test Item", &[("app", "test")], "my-secret", false) - .await?; - - // Try to load with wrong password - let result = UnlockedKeyring::load(&keyring_path, Some(wrong_secret)).await; - - // Verify this returns IncorrectSecret, not ChecksumMismatch - assert!(matches!(result, Err(Error::IncorrectSecret))); - - Ok(()) -} - -#[tokio::test] -async fn comprehensive_search_patterns() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("search_test.keyring"); - let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; - - // Create diverse test data - let test_items = [ - ( - "Email Password", - vec![ - ("app", "email"), - ("user", "alice@example.com"), - ("type", "password"), - ], - ), - ( - "Email Token", - vec![ - ("app", "email"), - ("user", "alice@example.com"), - ("type", "token"), - ], - ), - ( - "SSH Key", - vec![("app", "ssh"), ("user", "alice"), ("type", "key")], - ), - ( - "Database Password", - vec![ - ("app", "database"), - ("env", "production"), - ("type", "password"), - ], - ), - ( - "API Key", - vec![("app", "api"), ("service", "github"), ("type", "key")], - ), - ]; - - for (i, (label, attrs)) in test_items.iter().enumerate() { - let attrs_map: HashMap<&str, &str> = attrs.iter().cloned().collect(); - keyring - .create_item(label, &attrs_map, format!("secret{}", i), false) - .await?; - } - - // Test exact match - let exact = keyring - .search_items(&[ - ("app", "email"), - ("user", "alice@example.com"), - ("type", "password"), - ]) - .await?; - assert_eq!(exact.len(), 1); - assert_eq!(exact[0].label(), "Email Password"); - - // Test partial match - by app - let email_items = keyring.search_items(&[("app", "email")]).await?; - assert_eq!(email_items.len(), 2); - - // Test partial match - by type - let passwords = keyring.search_items(&[("type", "password")]).await?; - assert_eq!(passwords.len(), 2); - - let keys = keyring.search_items(&[("type", "key")]).await?; - assert_eq!(keys.len(), 2); - - // Test no match - let nonexistent = keyring.search_items(&[("app", "nonexistent")]).await?; - assert_eq!(nonexistent.len(), 0); - - Ok(()) -} - -#[tokio::test] -async fn item_replacement_behavior() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("replace_test.keyring"); - let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; - - let attrs = &[("app", "test"), ("user", "alice")]; - - // Create initial item - keyring - .create_item("Original", attrs, "secret1", false) - .await?; - - // Verify initial state - let items = keyring.search_items(attrs).await?; - assert_eq!(items.len(), 1); - assert_eq!(items[0].label(), "Original"); - assert_eq!(items[0].secret(), Secret::text("secret1")); - - // With replace=false, allows duplicates (discovered behavior) - keyring - .create_item("Duplicate", attrs, "secret2", false) - .await?; - - // Verify we now have 2 items with same attributes - let items = keyring.search_items(attrs).await?; - assert_eq!(items.len(), 2); - - // Verify both items exist with different content - let labels: Vec<_> = items.iter().map(|i| i.label()).collect(); - assert!(labels.contains(&"Original")); - assert!(labels.contains(&"Duplicate")); - - // Now test replace=true behavior - should remove existing items with same - // attributes - keyring - .create_item("Replacement", attrs, "secret3", true) - .await?; - - // After replace=true, should only have the new item - let items = keyring.search_items(attrs).await?; - assert_eq!(items.len(), 1); - assert_eq!(items[0].label(), "Replacement"); - assert_eq!(items[0].secret(), Secret::text("secret3")); - - // Test replace=true on empty attributes (should just add) - let unique_attrs = &[("app", "unique"), ("user", "bob")]; - keyring - .create_item("Unique Item", unique_attrs, "unique_secret", true) - .await?; - - let unique_items = keyring.search_items(unique_attrs).await?; - assert_eq!(unique_items.len(), 1); - assert_eq!(unique_items[0].label(), "Unique Item"); - - // Test replace=true again on the unique item - should replace it - keyring - .create_item("Updated Unique", unique_attrs, "updated_secret", true) - .await?; - - let unique_items = keyring.search_items(unique_attrs).await?; - assert_eq!(unique_items.len(), 1); - assert_eq!(unique_items[0].label(), "Updated Unique"); - assert_eq!(unique_items[0].secret(), Secret::text("updated_secret")); - - Ok(()) -} - -#[tokio::test] -async fn item_replacement_ignores_secret_content_type() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("replace_content_type.keyring"); - let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; - let attrs = &[("app", "browser"), ("account", "alice")]; - - keyring - .create_item("Imported", attrs, Secret::blob(b"old"), false) - .await?; - keyring - .create_item("Updated", attrs, Secret::text("new"), true) - .await?; - - let items = keyring.search_items(attrs).await?; - assert_eq!(items.len(), 1); - assert_eq!(items[0].secret(), Secret::text("new")); - Ok(()) -} - -#[tokio::test] -async fn item_replacement_matches_attributes() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("replace_attributes_test.keyring"); - let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; - - keyring - .create_item( - "Alice", - &[("app", "test"), ("user", "alice")], - "alice-secret", - false, - ) - .await?; - keyring - .create_item( - "Bob", - &[("app", "test"), ("user", "bob")], - "bob-secret", - false, - ) - .await?; - - // A coarser attribute set must not replace either item. - keyring - .create_item("Coarse", &[("app", "test")], "coarse-secret", true) - .await?; - - let items = keyring.search_items(&[("app", "test")]).await?; - assert_eq!(items.len(), 3); - assert_eq!( - keyring - .search_items(&[("app", "test"), ("user", "alice")]) - .await? - .len(), - 1 - ); - assert_eq!( - keyring - .search_items(&[("app", "test"), ("user", "bob")]) - .await? - .len(), - 1 - ); - - // Replacing the coarse item must not add a duplicate. - keyring - .create_item( - "Updated Coarse", - &[("app", "test")], - "updated-coarse-secret", - true, - ) - .await?; - - let items = keyring.search_items(&[("app", "test")]).await?; - assert_eq!(items.len(), 3); - assert_eq!( - items - .iter() - .filter(|item| item.attributes().get("user").is_none()) - .map(|item| item.label()) - .collect::>(), - vec!["Updated Coarse"] - ); - - Ok(()) -} - -#[tokio::test] -async fn empty_keyring_operations() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("empty_test.keyring"); - let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; - - // Test operations on empty keyring - let items = keyring.items().await?; - assert_eq!(items.len(), 0); - - let search_results = keyring.search_items(&[("any", "thing")]).await?; - assert_eq!(search_results.len(), 0); - - // Delete on empty keyring should succeed - keyring.delete(&[("nonexistent", "key")]).await?; - - // Verify still empty after delete - assert_eq!(keyring.n_items().await, 0); - - // Test lookup on empty keyring - let lookup_result = keyring.lookup_item(&[("test", "value")]).await?; - assert!(lookup_result.is_none()); - - Ok(()) -} - -#[tokio::test] -async fn secret_types_handling() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("secret_types_test.keyring"); - let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; - - // Test text secret - keyring - .create_item( - "Text Secret", - &[("type", "text")], - Secret::text("Hello, World!"), - false, - ) - .await?; - - // Test binary secret - keyring - .create_item( - "Binary Secret", - &[("type", "binary")], - Secret::blob([0x00, 0x01, 0x02, 0xFF]), - false, - ) - .await?; - - // Test large secret - let large_data = vec![42u8; 10000]; - keyring - .create_item( - "Large Secret", - &[("type", "large")], - Secret::blob(&large_data), - false, - ) - .await?; - - // Test empty secret - keyring - .create_item( - "Empty Secret", - &[("type", "empty")], - Secret::text(""), - false, - ) - .await?; - - // Verify all secrets can be retrieved correctly - let text_items = keyring.search_items(&[("type", "text")]).await?; - assert_eq!(text_items.len(), 1); - assert_eq!(text_items[0].secret(), Secret::text("Hello, World!")); - assert_eq!( - text_items[0].secret().content_type(), - oo7::ContentType::Text - ); - - let binary_items = keyring.search_items(&[("type", "binary")]).await?; - assert_eq!(binary_items.len(), 1); - assert_eq!(&*binary_items[0].secret(), &[0x00, 0x01, 0x02, 0xFF]); - assert_eq!( - binary_items[0].secret().content_type(), - oo7::ContentType::Blob - ); - - let large_items = keyring.search_items(&[("type", "large")]).await?; - assert_eq!(large_items.len(), 1); - assert_eq!(&*large_items[0].secret(), &large_data); - - let empty_items = keyring.search_items(&[("type", "empty")]).await?; - assert_eq!(empty_items.len(), 1); - assert_eq!(empty_items[0].secret(), Secret::text("")); - - Ok(()) -} - -#[tokio::test] -async fn item_lifecycle_operations() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("lifecycle_test.keyring"); - let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; - - // Test creating multiple items - keyring - .create_item( - "Test Item 1", - &[("app", "myapp"), ("user", "alice")], - "secret1", - false, - ) - .await?; - - keyring - .create_item( - "Test Item 2", - &[("app", "myapp"), ("user", "bob")], - "secret2", - false, - ) - .await?; - - // Test retrieving all items - let items = keyring.items().await?; - assert_eq!(items.len(), 2); - - // Test searching by user - let alice_items = keyring.search_items(&[("user", "alice")]).await?; - assert_eq!(alice_items.len(), 1); - assert_eq!(alice_items[0].label(), "Test Item 1"); - assert_eq!(alice_items[0].secret(), Secret::text("secret1")); - - // Test searching by app (should find both) - let app_items = keyring.search_items(&[("app", "myapp")]).await?; - assert_eq!(app_items.len(), 2); - - // Test deleting items - keyring.delete(&[("user", "alice")]).await?; - let remaining_items = keyring.items().await?; - assert_eq!(remaining_items.len(), 1); - assert_eq!(remaining_items[0].label(), "Test Item 2"); - - Ok(()) -} - -#[tokio::test] -async fn item_attribute_operations() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("attr_test.keyring"); - let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; - - // Create item with initial attributes - keyring - .create_item( - "Attribute Test", - &[("app", "testapp"), ("version", "1.0"), ("env", "test")], - "test-secret", - false, - ) - .await?; - - let items = keyring.search_items(&[("app", "testapp")]).await?; - assert_eq!(items.len(), 1); - let item = &items[0]; - - // Test reading attributes - let attrs = item.attributes(); - assert_eq!(attrs.len(), 4); // 3 + xdg:schema - assert_eq!(attrs.get("app").unwrap().to_string(), "testapp"); - assert_eq!(attrs.get("version").unwrap().to_string(), "1.0"); - assert_eq!(attrs.get("env").unwrap().to_string(), "test"); - - // Test updating attributes - let index = keyring - .lookup_item_index(&[("app", "testapp")]) - .await? - .unwrap(); - - let items = keyring.items().await?; - let mut item_to_replace = items.into_iter().next().unwrap(); - - item_to_replace.set_attributes(&[ - ("app", "testapp"), - ("version", "2.0"), // updated - ("env", "production"), // updated - ("new_attr", "new_value"), // added - ]); - - keyring.replace_item_index(index, &item_to_replace).await?; - - let updated_items = keyring.search_items(&[("app", "testapp")]).await?; - assert_eq!(updated_items.len(), 1); - let updated_attrs = updated_items[0].attributes(); - assert_eq!(updated_attrs.get("version").unwrap().to_string(), "2.0"); - assert_eq!(updated_attrs.get("env").unwrap().to_string(), "production"); - assert_eq!( - updated_attrs.get("new_attr").unwrap().to_string(), - "new_value" - ); - assert_eq!(updated_items[0].secret(), Secret::text("test-secret")); - - Ok(()) -} - -#[tokio::test] -async fn bulk_create_items() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("bulk_create_test.keyring"); - let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; - - // Prepare multiple items to create at once - let items_to_create = vec![ - ( - "Bulk Item 1".to_string(), - HashMap::from([ - ("app".to_string(), "bulk-app".to_string()), - ("user".to_string(), "user1".to_string()), - ]), - Secret::text("secret1"), - false, - ), - ( - "Bulk Item 2".to_string(), - HashMap::from([ - ("app".to_string(), "bulk-app".to_string()), - ("user".to_string(), "user2".to_string()), - ]), - Secret::text("secret2"), - false, - ), - ( - "Bulk Item 3".to_string(), - HashMap::from([ - ("app".to_string(), "bulk-app".to_string()), - ("user".to_string(), "user3".to_string()), - ]), - Secret::text("secret3"), - false, - ), - ]; - - // Create all items in bulk - keyring.create_items(items_to_create).await?; - // Verify all items were created - let all_items = keyring.search_items(&[("app", "bulk-app")]).await?; - assert_eq!(all_items.len(), 3); - - // Test replace=true in bulk create - let replace_items = vec![( - "Replaced Item".to_string(), - HashMap::from([ - ("app".to_string(), "bulk-app".to_string()), - ("user".to_string(), "user1".to_string()), - ]), - Secret::text("new_secret1"), - true, // replace=true should remove existing item with same attributes - )]; - - keyring.create_items(replace_items).await?; - - // Verify the item was replaced - should still have 3 items total - let all_items_after = keyring.search_items(&[("app", "bulk-app")]).await?; - assert_eq!(all_items_after.len(), 3); - - // A coarse replacement must preserve the three specific items. - keyring - .create_items(vec![( - "Coarse Item".to_string(), - HashMap::from([("app".to_string(), "bulk-app".to_string())]), - Secret::text("coarse-secret"), - true, - )]) - .await?; - assert_eq!(keyring.search_items(&[("app", "bulk-app")]).await?.len(), 4); - - // Replacing the coarse item removes only its predecessor. - keyring - .create_items(vec![( - "Updated Coarse Item".to_string(), - HashMap::from([("app".to_string(), "bulk-app".to_string())]), - Secret::text("updated-coarse-secret"), - true, - )]) - .await?; - assert_eq!(keyring.search_items(&[("app", "bulk-app")]).await?.len(), 4); - Ok(()) -} - -#[tokio::test] -async fn partially_corrupted_keyring_error() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("partially_corrupted.keyring"); - - // Create keyring with correct password and add 2 valid items - let correct_secret = Secret::from("correct-password-long-enough".as_bytes()); - let keyring = UnlockedKeyring::load(&keyring_path, Some(correct_secret.clone())).await?; - keyring - .create_item("valid1", &[("attr", "value1")], "password1", false) - .await?; - keyring - .create_item("valid2", &[("attr", "value2")], "password2", false) - .await?; - let key = keyring.key().await?.unwrap(); - let key = key.as_ref().as_ref().to_vec(); - drop(keyring); - - // Load_unchecked with wrong password and add 3 broken items (more than - // valid) - let wrong_secret = Secret::from("wrong-password-long-enough".as_bytes()); - let keyring = unsafe { UnlockedKeyring::load_unchecked(&keyring_path, wrong_secret).await? }; - keyring - .create_item("broken1", &[("bad", "value1")], "bad_password1", false) - .await?; - keyring - .create_item("broken2", &[("bad", "value2")], "bad_password2", false) - .await?; - keyring - .create_item("broken3", &[("bad", "value3")], "bad_password3", false) - .await?; - drop(keyring); - - let locked = LockedKeyring::load(&keyring_path).await?; - assert!(locked.validate_key(&Key::new(key.clone())).await?); - assert!(matches!( - locked.unlock_with_key(Key::new(key)).await, - Err(Error::PartiallyCorruptedKeyring { - valid_items: 2, - broken_items: 3, - }) - )); - - let result = UnlockedKeyring::load(&keyring_path, Some(correct_secret)).await; - assert!(result.is_err()); - match result.unwrap_err() { - Error::PartiallyCorruptedKeyring { - valid_items, - broken_items, - } => { - assert_eq!(valid_items, 2); - assert_eq!(broken_items, 3); - assert!(broken_items > valid_items); - } - other => panic!("Expected PartiallyCorruptedKeyring, got: {:?}", other), - } - - Ok(()) -} - -#[tokio::test] -async fn invalid_item_error_on_decrypt_failure() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("invalid_item_test.keyring"); - - // 1) Create keyring with correct password and add 2 items - let correct_secret = Secret::from("correct-password-long-enough".as_bytes()); - let keyring = UnlockedKeyring::load(&keyring_path, Some(correct_secret)).await?; - keyring - .create_item("item1", &[("app", "test1")], "password1", false) - .await?; - keyring - .create_item("item2", &[("app", "test2")], "password2", false) - .await?; - drop(keyring); - - // 2) Load_unchecked with wrong password - items won't decrypt - let wrong_secret = Secret::from("wrong-password-long-enough".as_bytes()); - let keyring = unsafe { UnlockedKeyring::load_unchecked(&keyring_path, wrong_secret).await? }; - - let items_result = keyring.all_items().await?; - assert_eq!(items_result.len(), 2); - - assert!(matches!( - items_result[0].as_ref().unwrap_err(), - InvalidItemError { .. } - )); - assert!(matches!( - items_result[1].as_ref().unwrap_err(), - InvalidItemError { .. } - )); - - Ok(()) -} - -#[tokio::test] -async fn replace_item_index_invalid() -> Result<(), Error> { - let temp_dir = tempdir().unwrap(); - let keyring_path = temp_dir.path().join("replace_invalid_index.keyring"); - let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; - - // Create one item - keyring - .create_item("Test Item", &[("app", "test")], "secret", false) - .await?; - - // Try to replace at invalid index - let items = keyring.items().await?; - let existing_item = items.into_iter().next().unwrap(); - let result = keyring.replace_item_index(100, &existing_item).await; - - assert!(matches!(result, Err(Error::InvalidItemIndex(100)))); - - Ok(()) -} - -#[tokio::test] -async fn replace_item_without_schema() -> Result<(), Error> { - let keyring = UnlockedKeyring::temporary(Secret::blob("test_password")).await?; - let unique = ("unique", "ssh-store:/home/user/.ssh/id_rsa"); - keyring - .create_item("Migrated", &[unique], "old", false) - .await?; - - // Another schema doesn't replace it - keyring - .create_item( - "Other", - &[unique, (XDG_SCHEMA_ATTRIBUTE, "org.example.Other")], - "other", - true, - ) - .await?; - assert_eq!(keyring.n_items().await, 2); - - // Items without a schema are implicitly generic - keyring - .create_item( - "New", - &[unique, (XDG_SCHEMA_ATTRIBUTE, oo7::GENERIC_SCHEMA)], - "new", - true, - ) - .await?; - let labels = keyring - .items() - .await? - .iter() - .map(|item| item.label().to_owned()) - .collect::>(); - assert_eq!(labels.len(), 2); - assert!(labels.contains(&"New".to_owned()) && labels.contains(&"Other".to_owned())); - - Ok(()) -} diff --git a/client/tests/file_unlocked_keyring/errors.rs b/client/tests/file_unlocked_keyring/errors.rs new file mode 100644 index 00000000..c0c8ec39 --- /dev/null +++ b/client/tests/file_unlocked_keyring/errors.rs @@ -0,0 +1,167 @@ +use std::path::PathBuf; + +#[cfg(feature = "async-std")] +use async_std::fs; +use oo7::{Key, Secret, file::*}; +use tempfile::tempdir; +#[cfg(feature = "tokio")] +use tokio::fs; + +#[tokio::test] +async fn delete_broken_items() -> Result<(), Error> { + const VALID_TO_ADD: usize = 5; + const BROKEN_TO_ADD: usize = 3; + + let data_dir = tempdir()?; + let v0_dir = data_dir.path().join("keyrings"); + let v1_dir = v0_dir.join("v1"); + fs::create_dir_all(&v1_dir).await?; + + let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("default.keyring"); + let keyring_path = v1_dir.join("default.keyring"); + fs::copy(&fixture_path, &keyring_path).await?; + + // 1) Load with the correct password and add several valid items. + // This ensures valid_items > broken_items that we'll add later. + let keyring = UnlockedKeyring::load(&keyring_path, Some(Secret::blob("test"))).await?; + for i in 0..VALID_TO_ADD { + keyring + .create_item( + &format!("valid {}", i), + &[("attr_valid", "value")], + format!("password_valid_{}", i), + false, + ) + .await?; + } + drop(keyring); + + // 2) Load_unchecked with the wrong password and add a few "broken" items. + let keyring = unsafe { + UnlockedKeyring::load_unchecked(&keyring_path, Secret::blob("wrong_password")).await? + }; + for i in 0..BROKEN_TO_ADD { + keyring + .create_item( + &format!("bad{}", i), + &[("attr_bad", "value_bad")], + format!("pw_bad{}", i), + false, + ) + .await?; + } + drop(keyring); + + // 3) Load with the correct password and run the deletion. + let keyring = UnlockedKeyring::load(&keyring_path, Some(Secret::blob("test"))).await?; + let removed = keyring.delete_broken_items().await?; + assert!( + removed >= BROKEN_TO_ADD, + "expected at least {} broken items removed, got {}", + BROKEN_TO_ADD, + removed + ); + + // Second call should find nothing left to clean up. + assert_eq!(keyring.delete_broken_items().await?, 0); + + fs::remove_file(keyring_path).await?; + Ok(()) +} + +#[tokio::test] +async fn partially_corrupted_keyring_error() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("partially_corrupted.keyring"); + + // Create keyring with correct password and add 2 valid items + let correct_secret = Secret::from("correct-password-long-enough".as_bytes()); + let keyring = UnlockedKeyring::load(&keyring_path, Some(correct_secret.clone())).await?; + keyring + .create_item("valid1", &[("attr", "value1")], "password1", false) + .await?; + keyring + .create_item("valid2", &[("attr", "value2")], "password2", false) + .await?; + let key = keyring.key().await?.unwrap(); + let key = key.as_ref().as_ref().to_vec(); + drop(keyring); + + // Load_unchecked with wrong password and add 3 broken items (more than + // valid) + let wrong_secret = Secret::from("wrong-password-long-enough".as_bytes()); + let keyring = unsafe { UnlockedKeyring::load_unchecked(&keyring_path, wrong_secret).await? }; + keyring + .create_item("broken1", &[("bad", "value1")], "bad_password1", false) + .await?; + keyring + .create_item("broken2", &[("bad", "value2")], "bad_password2", false) + .await?; + keyring + .create_item("broken3", &[("bad", "value3")], "bad_password3", false) + .await?; + drop(keyring); + + let locked = LockedKeyring::load(&keyring_path).await?; + assert!(locked.validate_key(&Key::new(key.clone())).await?); + assert!(matches!( + locked.unlock_with_key(Key::new(key)).await, + Err(Error::PartiallyCorruptedKeyring { + valid_items: 2, + broken_items: 3, + }) + )); + + let result = UnlockedKeyring::load(&keyring_path, Some(correct_secret)).await; + assert!(result.is_err()); + match result.unwrap_err() { + Error::PartiallyCorruptedKeyring { + valid_items, + broken_items, + } => { + assert_eq!(valid_items, 2); + assert_eq!(broken_items, 3); + assert!(broken_items > valid_items); + } + other => panic!("Expected PartiallyCorruptedKeyring, got: {:?}", other), + } + + Ok(()) +} + +#[tokio::test] +async fn invalid_item_error_on_decrypt_failure() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("invalid_item_test.keyring"); + + // 1) Create keyring with correct password and add 2 items + let correct_secret = Secret::from("correct-password-long-enough".as_bytes()); + let keyring = UnlockedKeyring::load(&keyring_path, Some(correct_secret)).await?; + keyring + .create_item("item1", &[("app", "test1")], "password1", false) + .await?; + keyring + .create_item("item2", &[("app", "test2")], "password2", false) + .await?; + drop(keyring); + + // 2) Load_unchecked with wrong password - items won't decrypt + let wrong_secret = Secret::from("wrong-password-long-enough".as_bytes()); + let keyring = unsafe { UnlockedKeyring::load_unchecked(&keyring_path, wrong_secret).await? }; + + let items_result = keyring.all_items().await?; + assert_eq!(items_result.len(), 2); + + assert!(matches!( + items_result[0].as_ref().unwrap_err(), + InvalidItemError { .. } + )); + assert!(matches!( + items_result[1].as_ref().unwrap_err(), + InvalidItemError { .. } + )); + + Ok(()) +} diff --git a/client/tests/file_unlocked_keyring/items.rs b/client/tests/file_unlocked_keyring/items.rs new file mode 100644 index 00000000..0837f611 --- /dev/null +++ b/client/tests/file_unlocked_keyring/items.rs @@ -0,0 +1,588 @@ +use std::collections::HashMap; + +use oo7::{Secret, XDG_SCHEMA_ATTRIBUTE, file::*}; +use tempfile::tempdir; + +use super::strong_key; + +#[tokio::test] +async fn delete() -> Result<(), Error> { + let temp_dir = tempdir()?; + let path = temp_dir.path().join("test-delete.keyring"); + + let keyring = UnlockedKeyring::load(&path, Some(strong_key())).await?; + let attributes: HashMap<&str, &str> = HashMap::default(); + keyring + .create_item("Label", &attributes, "secret", false) + .await?; + + keyring.delete_item_index(0).await?; + + let result = keyring.delete_item_index(100).await; + + assert!(matches!(result, Err(Error::InvalidItemIndex(100)))); + + Ok(()) +} + +#[tokio::test] +async fn comprehensive_search_patterns() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("search_test.keyring"); + let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; + + // Create diverse test data + let test_items = [ + ( + "Email Password", + vec![ + ("app", "email"), + ("user", "alice@example.com"), + ("type", "password"), + ], + ), + ( + "Email Token", + vec![ + ("app", "email"), + ("user", "alice@example.com"), + ("type", "token"), + ], + ), + ( + "SSH Key", + vec![("app", "ssh"), ("user", "alice"), ("type", "key")], + ), + ( + "Database Password", + vec![ + ("app", "database"), + ("env", "production"), + ("type", "password"), + ], + ), + ( + "API Key", + vec![("app", "api"), ("service", "github"), ("type", "key")], + ), + ]; + + for (i, (label, attrs)) in test_items.iter().enumerate() { + let attrs_map: HashMap<&str, &str> = attrs.iter().cloned().collect(); + keyring + .create_item(label, &attrs_map, format!("secret{}", i), false) + .await?; + } + + // Test exact match + let exact = keyring + .search_items(&[ + ("app", "email"), + ("user", "alice@example.com"), + ("type", "password"), + ]) + .await?; + assert_eq!(exact.len(), 1); + assert_eq!(exact[0].label(), "Email Password"); + + // Test partial match - by app + let email_items = keyring.search_items(&[("app", "email")]).await?; + assert_eq!(email_items.len(), 2); + + // Test partial match - by type + let passwords = keyring.search_items(&[("type", "password")]).await?; + assert_eq!(passwords.len(), 2); + + let keys = keyring.search_items(&[("type", "key")]).await?; + assert_eq!(keys.len(), 2); + + // Test no match + let nonexistent = keyring.search_items(&[("app", "nonexistent")]).await?; + assert_eq!(nonexistent.len(), 0); + + Ok(()) +} + +#[tokio::test] +async fn item_replacement_behavior() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("replace_test.keyring"); + let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; + + let attrs = &[("app", "test"), ("user", "alice")]; + + // Create initial item + keyring + .create_item("Original", attrs, "secret1", false) + .await?; + + // Verify initial state + let items = keyring.search_items(attrs).await?; + assert_eq!(items.len(), 1); + assert_eq!(items[0].label(), "Original"); + assert_eq!(items[0].secret(), Secret::text("secret1")); + + // With replace=false, allows duplicates (discovered behavior) + keyring + .create_item("Duplicate", attrs, "secret2", false) + .await?; + + // Verify we now have 2 items with same attributes + let items = keyring.search_items(attrs).await?; + assert_eq!(items.len(), 2); + + // Verify both items exist with different content + let labels: Vec<_> = items.iter().map(|i| i.label()).collect(); + assert!(labels.contains(&"Original")); + assert!(labels.contains(&"Duplicate")); + + // Now test replace=true behavior - should remove existing items with same + // attributes + keyring + .create_item("Replacement", attrs, "secret3", true) + .await?; + + // After replace=true, should only have the new item + let items = keyring.search_items(attrs).await?; + assert_eq!(items.len(), 1); + assert_eq!(items[0].label(), "Replacement"); + assert_eq!(items[0].secret(), Secret::text("secret3")); + + // Test replace=true on empty attributes (should just add) + let unique_attrs = &[("app", "unique"), ("user", "bob")]; + keyring + .create_item("Unique Item", unique_attrs, "unique_secret", true) + .await?; + + let unique_items = keyring.search_items(unique_attrs).await?; + assert_eq!(unique_items.len(), 1); + assert_eq!(unique_items[0].label(), "Unique Item"); + + // Test replace=true again on the unique item - should replace it + keyring + .create_item("Updated Unique", unique_attrs, "updated_secret", true) + .await?; + + let unique_items = keyring.search_items(unique_attrs).await?; + assert_eq!(unique_items.len(), 1); + assert_eq!(unique_items[0].label(), "Updated Unique"); + assert_eq!(unique_items[0].secret(), Secret::text("updated_secret")); + + Ok(()) +} + +#[tokio::test] +async fn item_replacement_ignores_secret_content_type() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("replace_content_type.keyring"); + let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; + let attrs = &[("app", "browser"), ("account", "alice")]; + + keyring + .create_item("Imported", attrs, Secret::blob(b"old"), false) + .await?; + keyring + .create_item("Updated", attrs, Secret::text("new"), true) + .await?; + + let items = keyring.search_items(attrs).await?; + assert_eq!(items.len(), 1); + assert_eq!(items[0].secret(), Secret::text("new")); + Ok(()) +} + +#[tokio::test] +async fn item_replacement_matches_attributes() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("replace_attributes_test.keyring"); + let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; + + keyring + .create_item( + "Alice", + &[("app", "test"), ("user", "alice")], + "alice-secret", + false, + ) + .await?; + keyring + .create_item( + "Bob", + &[("app", "test"), ("user", "bob")], + "bob-secret", + false, + ) + .await?; + + // A coarser attribute set must not replace either item. + keyring + .create_item("Coarse", &[("app", "test")], "coarse-secret", true) + .await?; + + let items = keyring.search_items(&[("app", "test")]).await?; + assert_eq!(items.len(), 3); + assert_eq!( + keyring + .search_items(&[("app", "test"), ("user", "alice")]) + .await? + .len(), + 1 + ); + assert_eq!( + keyring + .search_items(&[("app", "test"), ("user", "bob")]) + .await? + .len(), + 1 + ); + + // Replacing the coarse item must not add a duplicate. + keyring + .create_item( + "Updated Coarse", + &[("app", "test")], + "updated-coarse-secret", + true, + ) + .await?; + + let items = keyring.search_items(&[("app", "test")]).await?; + assert_eq!(items.len(), 3); + assert_eq!( + items + .iter() + .filter(|item| item.attributes().get("user").is_none()) + .map(|item| item.label()) + .collect::>(), + vec!["Updated Coarse"] + ); + + Ok(()) +} + +#[tokio::test] +async fn secret_types_handling() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("secret_types_test.keyring"); + let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; + + // Test text secret + keyring + .create_item( + "Text Secret", + &[("type", "text")], + Secret::text("Hello, World!"), + false, + ) + .await?; + + // Test binary secret + keyring + .create_item( + "Binary Secret", + &[("type", "binary")], + Secret::blob([0x00, 0x01, 0x02, 0xFF]), + false, + ) + .await?; + + // Test large secret + let large_data = vec![42u8; 10000]; + keyring + .create_item( + "Large Secret", + &[("type", "large")], + Secret::blob(&large_data), + false, + ) + .await?; + + // Test empty secret + keyring + .create_item( + "Empty Secret", + &[("type", "empty")], + Secret::text(""), + false, + ) + .await?; + + // Verify all secrets can be retrieved correctly + let text_items = keyring.search_items(&[("type", "text")]).await?; + assert_eq!(text_items.len(), 1); + assert_eq!(text_items[0].secret(), Secret::text("Hello, World!")); + assert_eq!( + text_items[0].secret().content_type(), + oo7::ContentType::Text + ); + + let binary_items = keyring.search_items(&[("type", "binary")]).await?; + assert_eq!(binary_items.len(), 1); + assert_eq!(&*binary_items[0].secret(), &[0x00, 0x01, 0x02, 0xFF]); + assert_eq!( + binary_items[0].secret().content_type(), + oo7::ContentType::Blob + ); + + let large_items = keyring.search_items(&[("type", "large")]).await?; + assert_eq!(large_items.len(), 1); + assert_eq!(&*large_items[0].secret(), &large_data); + + let empty_items = keyring.search_items(&[("type", "empty")]).await?; + assert_eq!(empty_items.len(), 1); + assert_eq!(empty_items[0].secret(), Secret::text("")); + + Ok(()) +} + +#[tokio::test] +async fn item_lifecycle_operations() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("lifecycle_test.keyring"); + let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; + + // Test creating multiple items + keyring + .create_item( + "Test Item 1", + &[("app", "myapp"), ("user", "alice")], + "secret1", + false, + ) + .await?; + + keyring + .create_item( + "Test Item 2", + &[("app", "myapp"), ("user", "bob")], + "secret2", + false, + ) + .await?; + + // Test retrieving all items + let items = keyring.items().await?; + assert_eq!(items.len(), 2); + + // Test searching by user + let alice_items = keyring.search_items(&[("user", "alice")]).await?; + assert_eq!(alice_items.len(), 1); + assert_eq!(alice_items[0].label(), "Test Item 1"); + assert_eq!(alice_items[0].secret(), Secret::text("secret1")); + + // Test searching by app (should find both) + let app_items = keyring.search_items(&[("app", "myapp")]).await?; + assert_eq!(app_items.len(), 2); + + // Test deleting items + keyring.delete(&[("user", "alice")]).await?; + let remaining_items = keyring.items().await?; + assert_eq!(remaining_items.len(), 1); + assert_eq!(remaining_items[0].label(), "Test Item 2"); + + Ok(()) +} + +#[tokio::test] +async fn item_attribute_operations() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("attr_test.keyring"); + let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; + + // Create item with initial attributes + keyring + .create_item( + "Attribute Test", + &[("app", "testapp"), ("version", "1.0"), ("env", "test")], + "test-secret", + false, + ) + .await?; + + let items = keyring.search_items(&[("app", "testapp")]).await?; + assert_eq!(items.len(), 1); + let item = &items[0]; + + // Test reading attributes + let attrs = item.attributes(); + assert_eq!(attrs.len(), 4); // 3 + xdg:schema + assert_eq!(attrs.get("app").unwrap().to_string(), "testapp"); + assert_eq!(attrs.get("version").unwrap().to_string(), "1.0"); + assert_eq!(attrs.get("env").unwrap().to_string(), "test"); + + // Test updating attributes + let index = keyring + .lookup_item_index(&[("app", "testapp")]) + .await? + .unwrap(); + + let items = keyring.items().await?; + let mut item_to_replace = items.into_iter().next().unwrap(); + + item_to_replace.set_attributes(&[ + ("app", "testapp"), + ("version", "2.0"), // updated + ("env", "production"), // updated + ("new_attr", "new_value"), // added + ]); + + keyring.replace_item_index(index, &item_to_replace).await?; + + let updated_items = keyring.search_items(&[("app", "testapp")]).await?; + assert_eq!(updated_items.len(), 1); + let updated_attrs = updated_items[0].attributes(); + assert_eq!(updated_attrs.get("version").unwrap().to_string(), "2.0"); + assert_eq!(updated_attrs.get("env").unwrap().to_string(), "production"); + assert_eq!( + updated_attrs.get("new_attr").unwrap().to_string(), + "new_value" + ); + assert_eq!(updated_items[0].secret(), Secret::text("test-secret")); + + Ok(()) +} + +#[tokio::test] +async fn bulk_create_items() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("bulk_create_test.keyring"); + let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; + + // Prepare multiple items to create at once + let items_to_create = vec![ + ( + "Bulk Item 1".to_string(), + HashMap::from([ + ("app".to_string(), "bulk-app".to_string()), + ("user".to_string(), "user1".to_string()), + ]), + Secret::text("secret1"), + false, + ), + ( + "Bulk Item 2".to_string(), + HashMap::from([ + ("app".to_string(), "bulk-app".to_string()), + ("user".to_string(), "user2".to_string()), + ]), + Secret::text("secret2"), + false, + ), + ( + "Bulk Item 3".to_string(), + HashMap::from([ + ("app".to_string(), "bulk-app".to_string()), + ("user".to_string(), "user3".to_string()), + ]), + Secret::text("secret3"), + false, + ), + ]; + + // Create all items in bulk + keyring.create_items(items_to_create).await?; + // Verify all items were created + let all_items = keyring.search_items(&[("app", "bulk-app")]).await?; + assert_eq!(all_items.len(), 3); + + // Test replace=true in bulk create + let replace_items = vec![( + "Replaced Item".to_string(), + HashMap::from([ + ("app".to_string(), "bulk-app".to_string()), + ("user".to_string(), "user1".to_string()), + ]), + Secret::text("new_secret1"), + true, // replace=true should remove existing item with same attributes + )]; + + keyring.create_items(replace_items).await?; + + // Verify the item was replaced - should still have 3 items total + let all_items_after = keyring.search_items(&[("app", "bulk-app")]).await?; + assert_eq!(all_items_after.len(), 3); + + // A coarse replacement must preserve the three specific items. + keyring + .create_items(vec![( + "Coarse Item".to_string(), + HashMap::from([("app".to_string(), "bulk-app".to_string())]), + Secret::text("coarse-secret"), + true, + )]) + .await?; + assert_eq!(keyring.search_items(&[("app", "bulk-app")]).await?.len(), 4); + + // Replacing the coarse item removes only its predecessor. + keyring + .create_items(vec![( + "Updated Coarse Item".to_string(), + HashMap::from([("app".to_string(), "bulk-app".to_string())]), + Secret::text("updated-coarse-secret"), + true, + )]) + .await?; + assert_eq!(keyring.search_items(&[("app", "bulk-app")]).await?.len(), 4); + Ok(()) +} + +#[tokio::test] +async fn replace_item_index_invalid() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("replace_invalid_index.keyring"); + let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; + + // Create one item + keyring + .create_item("Test Item", &[("app", "test")], "secret", false) + .await?; + + // Try to replace at invalid index + let items = keyring.items().await?; + let existing_item = items.into_iter().next().unwrap(); + let result = keyring.replace_item_index(100, &existing_item).await; + + assert!(matches!(result, Err(Error::InvalidItemIndex(100)))); + + Ok(()) +} + +#[tokio::test] +async fn replace_item_without_schema() -> Result<(), Error> { + let keyring = UnlockedKeyring::temporary(Secret::blob("test_password")).await?; + let unique = ("unique", "ssh-store:/home/user/.ssh/id_rsa"); + keyring + .create_item("Migrated", &[unique], "old", false) + .await?; + + // Another schema doesn't replace it + keyring + .create_item( + "Other", + &[unique, (XDG_SCHEMA_ATTRIBUTE, "org.example.Other")], + "other", + true, + ) + .await?; + assert_eq!(keyring.n_items().await, 2); + + // Items without a schema are implicitly generic + keyring + .create_item( + "New", + &[unique, (XDG_SCHEMA_ATTRIBUTE, oo7::GENERIC_SCHEMA)], + "new", + true, + ) + .await?; + let labels = keyring + .items() + .await? + .iter() + .map(|item| item.label().to_owned()) + .collect::>(); + assert_eq!(labels.len(), 2); + assert!(labels.contains(&"New".to_owned()) && labels.contains(&"Other".to_owned())); + + Ok(()) +} diff --git a/client/tests/file_unlocked_keyring/lifecycle.rs b/client/tests/file_unlocked_keyring/lifecycle.rs new file mode 100644 index 00000000..a3c12e6e --- /dev/null +++ b/client/tests/file_unlocked_keyring/lifecycle.rs @@ -0,0 +1,449 @@ +use oo7::{Key, Secret, file::*}; +use tempfile::tempdir; + +#[cfg(feature = "async-std")] +use async_std::fs; +#[cfg(feature = "tokio")] +use tokio::fs; + +use std::path::PathBuf; + +use super::strong_key; + +#[tokio::test] +async fn validate_and_unlock_with_key() -> Result<(), Error> { + let temp_dir = tempdir()?; + let path = temp_dir.path().join("key-unlock.keyring"); + let keyring = UnlockedKeyring::load(&path, Some(strong_key())).await?; + keyring + .create_item("Item", &[("account", "alice")], "secret", false) + .await?; + let key = keyring.key().await?.unwrap(); + let key = key.as_ref().as_ref().to_vec(); + drop(keyring); + + let locked = LockedKeyring::load(&path).await?; + assert!(!locked.validate_key(&Key::new(vec![9; 16])).await?); + assert!(locked.validate_key(&Key::new(key.clone())).await?); + + let locked_with_wrong_key = LockedKeyring::load(&path).await?; + assert!(matches!( + locked_with_wrong_key + .unlock_with_key(Key::new(vec![9; 16])) + .await, + Err(Error::IncorrectSecret) + )); + + let keyring = locked.unlock_with_key(Key::new(key.clone())).await?; + let cached_key = keyring.key().await?.unwrap(); + assert_eq!(cached_key.as_ref().as_ref(), key); + let item = keyring.lookup_item(&[("account", "alice")]).await?.unwrap(); + assert_eq!(item.secret(), Secret::text("secret")); + + Ok(()) +} + +#[tokio::test] +async fn malformed_file_keys_are_rejected() -> Result<(), Error> { + let temp_dir = tempdir()?; + let path = temp_dir.path().join("invalid-key-length.keyring"); + let keyring = UnlockedKeyring::load(&path, Some(strong_key())).await?; + keyring + .create_item("Item", &[("account", "alice")], "secret", false) + .await?; + drop(keyring); + + for actual in [0, 15, 17, 32] { + let locked = LockedKeyring::load(&path).await?; + assert!(matches!( + locked.validate_key(&Key::new(vec![0; actual])).await, + Err(Error::InvalidKeyLength { + expected: 16, + actual: error_actual, + }) if error_actual == actual + )); + + let locked = LockedKeyring::load(&path).await?; + assert!(matches!( + locked.unlock_with_key(Key::new(vec![0; actual])).await, + Err(Error::InvalidKeyLength { + expected: 16, + actual: error_actual, + }) if error_actual == actual + )); + } + + Ok(()) +} + +#[tokio::test] +async fn key_only_lifecycle_and_password_change() -> Result<(), Error> { + let temp_dir = tempdir()?; + let path = temp_dir.path().join("key-lifecycle.keyring"); + let original_secret = strong_key(); + let keyring = UnlockedKeyring::load(&path, Some(original_secret.clone())).await?; + keyring + .create_item("Original", &[("id", "original")], "before", false) + .await?; + let key = keyring.key().await?.unwrap(); + let key = key.as_ref().as_ref().to_vec(); + drop(keyring); + + let keyring = UnlockedKeyring::load_with_key(&path, Key::new(key.clone())).await?; + let cached_key = keyring.key().await?.unwrap(); + assert_eq!(cached_key.as_ref().as_ref(), key); + let mut original = keyring.lookup_item(&[("id", "original")]).await?.unwrap(); + original.set_secret("after"); + keyring.replace_item_index(0, &original).await?; + keyring + .create_item("Added", &[("id", "added")], "created", false) + .await?; + drop(keyring); + + let locked = LockedKeyring::load(&path).await?; + assert!(locked.validate_key(&Key::new(key.clone())).await?); + let keyring = UnlockedKeyring::load_with_key(&path, Key::new(key)).await?; + assert_eq!( + keyring + .lookup_item(&[("id", "original")]) + .await? + .unwrap() + .secret(), + Secret::text("after") + ); + assert_eq!( + keyring + .lookup_item(&[("id", "added")]) + .await? + .unwrap() + .secret(), + Secret::text("created") + ); + + let replacement_secret = Secret::blob(vec![3; 64]); + keyring.change_secret(replacement_secret.clone()).await?; + drop(keyring); + + assert!( + UnlockedKeyring::load(&path, Some(original_secret)) + .await + .is_err() + ); + let keyring = UnlockedKeyring::load(&path, Some(replacement_secret)).await?; + assert_eq!(keyring.n_items().await, 2); + + Ok(()) +} + +#[tokio::test] +async fn empty_keyring_cannot_authenticate_key() -> Result<(), Error> { + let temp_dir = tempdir()?; + let path = temp_dir.path().join("empty-key.keyring"); + let keyring = UnlockedKeyring::load(&path, Some(strong_key())).await?; + assert!(keyring.key().await?.is_some()); + keyring.write().await?; + drop(keyring); + + let locked = LockedKeyring::load(&path).await?; + assert!(locked.validate_key(&Key::new(vec![9; 16])).await?); + let keyring = locked.unlock_with_key(Key::new(vec![9; 16])).await?; + keyring + .create_item("Rebound", &[("id", "rebound")], "secret", false) + .await?; + drop(keyring); + + assert!( + UnlockedKeyring::load(&path, Some(strong_key())) + .await + .is_err() + ); + let keyring = UnlockedKeyring::load_with_key(&path, Key::new(vec![9; 16])).await?; + assert_eq!(keyring.n_items().await, 1); + + Ok(()) +} + +#[tokio::test] +async fn unencrypted_keyring_requires_no_key() -> Result<(), Error> { + let temp_dir = tempdir()?; + let path = temp_dir.path().join("unencrypted-key.keyring"); + let keyring = UnlockedKeyring::load(&path, None).await?; + keyring + .create_item("Plain", &[("id", "plain")], "secret", false) + .await?; + drop(keyring); + + let locked = LockedKeyring::load(&path).await?; + assert!(!locked.validate_key(&Key::new(vec![1; 16])).await?); + assert!(matches!( + locked.unlock_with_key(Key::new(vec![1; 16])).await, + Err(Error::IncorrectSecret) + )); + + let keyring = LockedKeyring::load(&path) + .await? + .unlock_unencrypted() + .await?; + assert!(keyring.key().await?.is_none()); + assert_eq!(keyring.n_items().await, 1); + + Ok(()) +} + +#[tokio::test] +async fn open_at_with_key_uses_named_current_keyring() -> Result<(), Error> { + let data_dir = tempdir()?; + let keyring = UnlockedKeyring::open_at(data_dir.path(), "named", Some(strong_key())).await?; + keyring + .create_item("Named", &[("id", "named")], "secret", false) + .await?; + let key = keyring.key().await?.unwrap(); + let key = key.as_ref().as_ref().to_vec(); + drop(keyring); + + let keyring = + UnlockedKeyring::open_at_with_key(data_dir.path(), "named", Key::new(key)).await?; + assert_eq!( + keyring + .lookup_item(&[("id", "named")]) + .await? + .unwrap() + .secret(), + Secret::text("secret") + ); + + let direct_key = vec![4; 16]; + let direct = UnlockedKeyring::open_at_with_key( + data_dir.path(), + "new-with-key", + Key::new(direct_key.clone()), + ) + .await?; + direct + .create_item("Direct", &[("id", "direct")], "secret", false) + .await?; + drop(direct); + let direct = + UnlockedKeyring::open_at_with_key(data_dir.path(), "new-with-key", Key::new(direct_key)) + .await?; + assert_eq!(direct.n_items().await, 1); + + Ok(()) +} + +#[tokio::test] +async fn open_at_with_key_ignores_legacy_keyring() -> Result<(), Error> { + let data_dir = tempdir()?; + let keyrings_dir = data_dir.path().join("keyrings"); + fs::create_dir_all(&keyrings_dir).await?; + let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("default.keyring"); + let v0_path = keyrings_dir.join("named.keyring"); + let v1_path = keyrings_dir.join("v1").join("named.keyring"); + fs::copy(fixture, &v0_path).await?; + let v0_bytes = fs::read(&v0_path).await?; + let v0_metadata = fs::metadata(&v0_path).await?; + assert!(!v1_path.exists()); + + let key = vec![1; 16]; + let keyring = + UnlockedKeyring::open_at_with_key(data_dir.path(), "named", Key::new(key.clone())).await?; + assert_eq!(keyring.n_items().await, 0); + assert!(!v1_path.exists()); + assert_eq!(fs::read(&v0_path).await?, v0_bytes); + assert_eq!(fs::metadata(&v0_path).await?.len(), v0_metadata.len()); + assert_eq!( + fs::metadata(&v0_path).await?.modified()?, + v0_metadata.modified()? + ); + + keyring + .create_item("Direct", &[("id", "direct")], "secret", false) + .await?; + drop(keyring); + assert!(v1_path.exists()); + assert_eq!(fs::read(&v0_path).await?, v0_bytes); + + let keyring = + UnlockedKeyring::open_at_with_key(data_dir.path(), "named", Key::new(key)).await?; + assert_eq!( + keyring + .lookup_item(&[("id", "direct")]) + .await? + .unwrap() + .secret(), + Secret::text("secret") + ); + drop(keyring); + assert!(matches!( + UnlockedKeyring::open_at_with_key(data_dir.path(), "named", Key::new(vec![2; 16])).await, + Err(Error::IncorrectSecret) + )); + + Ok(()) +} + +#[tokio::test] +async fn open_wrong_password() -> Result<(), Error> { + let data_dir = tempdir()?; + let v0_dir = data_dir.path().join("keyrings"); + let v1_dir = v0_dir.join("v1"); + fs::create_dir_all(&v1_dir).await?; + + let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("default.keyring"); + fs::copy(&fixture_path, &v1_dir.join("default.keyring")).await?; + + let secret = Secret::blob("wrong"); + let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await; + + assert!(keyring.is_err()); + assert!(matches!(keyring.unwrap_err(), Error::IncorrectSecret)); + + let secret = Secret::blob("test"); + let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await; + + assert!(keyring.is_ok()); + + Ok(()) +} + +#[tokio::test] +async fn open() -> Result<(), Error> { + let data_dir = tempdir()?; + let v0_dir = data_dir.path().join("keyrings"); + let v1_dir = v0_dir.join("v1"); + fs::create_dir_all(&v1_dir).await?; + + let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("default.keyring"); + fs::copy(&fixture_path, &v1_dir.join("default.keyring")).await?; + + let secret = Secret::blob("test"); + let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await?; + + assert!(v1_dir.join("default.keyring").exists()); + + super::check_items(&keyring).await?; + + keyring.write().await?; + assert!(v1_dir.join("default.keyring").exists()); + + Ok(()) +} + +#[tokio::test] +async fn open_nonexistent() -> Result<(), Error> { + let data_dir = tempdir()?; + let v0_dir = data_dir.path().join("keyrings"); + let v1_dir = v0_dir.join("v1"); + fs::create_dir_all(&v1_dir).await?; + + let secret = Secret::blob("test"); + let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await?; + + assert!(!v1_dir.join("default.keyring").exists()); + + keyring + .create_item( + "foo", + &[(oo7::XDG_SCHEMA_ATTRIBUTE, "org.gnome.keyring.Note")], + "foo", + false, + ) + .await?; + keyring.write().await?; + + assert!(v1_dir.join("default.keyring").exists()); + + Ok(()) +} + +#[tokio::test] +async fn change_secret() -> Result<(), Error> { + let data_dir = tempdir()?; + let v0_dir = data_dir.path().join("keyrings"); + let v1_dir = v0_dir.join("v1"); + fs::create_dir_all(&v1_dir).await?; + + let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("default.keyring"); + let keyring_path = v1_dir.join("default.keyring"); + fs::copy(&fixture_path, &keyring_path).await?; + + let keyring = UnlockedKeyring::load(&keyring_path, Some(Secret::blob("test"))).await?; + let attributes = &[("attr", "value")]; + let item_before = keyring + .create_item("test", attributes, "password", false) + .await?; + + let secret = Secret::blob("new_secret"); + keyring.change_secret(secret).await?; + + let secret = Secret::blob("new_secret"); + let keyring = UnlockedKeyring::load(&keyring_path, Some(secret)).await?; + let item_now = keyring.lookup_item(attributes).await?.unwrap(); + + assert_eq!(item_before.label(), item_now.label()); + assert_eq!(item_before.secret(), item_now.secret()); + assert_eq!(item_before.attributes(), item_now.attributes()); + + // No items were broken during the secret change + assert_eq!(keyring.delete_broken_items().await?, 0); + + fs::remove_file(keyring_path).await?; + + Ok(()) +} + +#[tokio::test] +async fn wrong_password_error_type() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("wrong_password_test.keyring"); + let correct_secret = Secret::from("correct-password-that-is-long-enough".as_bytes()); + let wrong_secret = Secret::from("wrong-password-that-is-long-enough".as_bytes()); + + // Create a keyring with the correct password + let keyring = UnlockedKeyring::load(&keyring_path, Some(correct_secret)).await?; + keyring + .create_item("Test Item", &[("app", "test")], "my-secret", false) + .await?; + + // Try to load with wrong password + let result = UnlockedKeyring::load(&keyring_path, Some(wrong_secret)).await; + + // Verify this returns IncorrectSecret, not ChecksumMismatch + assert!(matches!(result, Err(Error::IncorrectSecret))); + + Ok(()) +} + +#[tokio::test] +async fn empty_keyring_operations() -> Result<(), Error> { + let temp_dir = tempdir().unwrap(); + let keyring_path = temp_dir.path().join("empty_test.keyring"); + let keyring = UnlockedKeyring::load(&keyring_path, Some(strong_key())).await?; + + // Test operations on empty keyring + let items = keyring.items().await?; + assert_eq!(items.len(), 0); + + let search_results = keyring.search_items(&[("any", "thing")]).await?; + assert_eq!(search_results.len(), 0); + + // Delete on empty keyring should succeed + keyring.delete(&[("nonexistent", "key")]).await?; + + // Verify still empty after delete + assert_eq!(keyring.n_items().await, 0); + + // Test lookup on empty keyring + let lookup_result = keyring.lookup_item(&[("test", "value")]).await?; + assert!(lookup_result.is_none()); + + Ok(()) +} diff --git a/client/tests/file_unlocked_keyring/main.rs b/client/tests/file_unlocked_keyring/main.rs new file mode 100644 index 00000000..b4f0f41d --- /dev/null +++ b/client/tests/file_unlocked_keyring/main.rs @@ -0,0 +1,27 @@ +use oo7::{Secret, XDG_SCHEMA_ATTRIBUTE, file::*}; + +fn strong_key() -> Secret { + Secret::from([1, 2].into_iter().cycle().take(64).collect::>()) +} + +async fn check_items(keyring: &UnlockedKeyring) -> Result<(), Error> { + assert_eq!(keyring.n_items().await, 1); + let items = keyring.items().await?; + assert_eq!(items.len(), 1); + assert_eq!(items[0].label(), "foo"); + assert_eq!(items[0].secret(), Secret::blob("foo")); + let attributes = items[0].attributes(); + assert_eq!(attributes.len(), 2); + assert_eq!( + attributes.get(XDG_SCHEMA_ATTRIBUTE).map(|v| v.as_ref()), + Some("org.gnome.keyring.Note") + ); + + Ok(()) +} + +mod errors; +mod items; +mod lifecycle; +mod migration; +mod persistence; diff --git a/client/tests/file_unlocked_keyring/migration.rs b/client/tests/file_unlocked_keyring/migration.rs new file mode 100644 index 00000000..15928d19 --- /dev/null +++ b/client/tests/file_unlocked_keyring/migration.rs @@ -0,0 +1,100 @@ +use std::path::PathBuf; + +#[cfg(feature = "async-std")] +use async_std::fs; +use oo7::{Secret, XDG_SCHEMA_ATTRIBUTE, file::*}; +use tempfile::tempdir; +#[cfg(feature = "tokio")] +use tokio::fs; + +#[tokio::test] +async fn migrate_from_legacy() -> Result<(), Error> { + let data_dir = tempdir()?; + let v0_dir = data_dir.path().join("keyrings"); + let v1_dir = v0_dir.join("v1"); + fs::create_dir_all(&v1_dir).await?; + + let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("legacy.keyring"); + fs::copy(&fixture_path, &v0_dir.join("default.keyring")).await?; + + assert!(!v1_dir.join("default.keyring").exists()); + + let secret = Secret::blob("test"); + let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await?; + + super::check_items(&keyring).await?; + + keyring.write().await?; + assert!(v1_dir.join("default.keyring").exists()); + + Ok(()) +} + +async fn migrate_from_plain_legacy(secret: Option) -> Result<(), Error> { + let data_dir = tempdir()?; + let v0_dir = data_dir.path().join("keyrings"); + let v1_dir = v0_dir.join("v1"); + fs::create_dir_all(&v1_dir).await?; + + let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("plain.keyring"); + fs::copy(&fixture_path, &v0_dir.join("login.keyring")).await?; + + let keyring = UnlockedKeyring::open_at(data_dir.path(), "login", secret.clone()).await?; + keyring.write().await?; + assert!(v1_dir.join("login.keyring").exists()); + + let keyring = UnlockedKeyring::open_at(data_dir.path(), "login", secret).await?; + let items = keyring + .search_items(&[(XDG_SCHEMA_ATTRIBUTE, "org.remmina.Password")]) + .await?; + assert_eq!(items.len(), 1); + assert_eq!(items[0].label(), "Remmina: Shore - password"); + assert_eq!(items[0].secret(), Secret::text("some password")); + assert_eq!(keyring.n_items().await, 3); + + Ok(()) +} + +#[tokio::test] +async fn migrate_from_plain_legacy_without_secret() -> Result<(), Error> { + migrate_from_plain_legacy(None).await +} + +#[tokio::test] +async fn migrate_from_plain_legacy_with_secret() -> Result<(), Error> { + migrate_from_plain_legacy(Some(Secret::blob("test"))).await +} + +#[tokio::test] +async fn migrate_from_plain_legacy_with_short_secret() -> Result<(), Error> { + migrate_from_plain_legacy(Some(Secret::from(vec![1]))).await +} + +#[tokio::test] +async fn migrate() -> Result<(), Error> { + let data_dir = tempdir()?; + let v0_dir = data_dir.path().join("keyrings"); + let v1_dir = v0_dir.join("v1"); + fs::create_dir_all(&v1_dir).await?; + + let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join("default.keyring"); + fs::copy(&fixture_path, &v0_dir.join("default.keyring")).await?; + + let secret = Secret::blob("test"); + let keyring = UnlockedKeyring::open_at(data_dir.path(), "default", Some(secret)).await?; + + assert!(!v1_dir.join("default.keyring").exists()); + + super::check_items(&keyring).await?; + + keyring.write().await?; + assert!(v1_dir.join("default.keyring").exists()); + + Ok(()) +} diff --git a/client/tests/file_unlocked_keyring/persistence.rs b/client/tests/file_unlocked_keyring/persistence.rs new file mode 100644 index 00000000..0c2343e5 --- /dev/null +++ b/client/tests/file_unlocked_keyring/persistence.rs @@ -0,0 +1,62 @@ +use std::{collections::HashMap, sync::Arc}; + +use oo7::{Secret, file::*}; +use tempfile::tempdir; + +use super::strong_key; + +#[tokio::test] +async fn repeated_write() -> Result<(), Error> { + let temp_dir = tempdir()?; + let path = temp_dir.path().join("test.keyring"); + + let secret = Secret::from(vec![1, 2]); + let keyring = UnlockedKeyring::load(&path, Some(secret)).await?; + + keyring.write().await?; + keyring.write().await?; + + Ok(()) +} + +#[tokio::test] +async fn write_with_short_password() -> Result<(), Error> { + let temp_dir = tempdir()?; + let path = temp_dir.path().join("write_with_short_password.keyring"); + + // Password policy is up to the caller, e.g. keyrings migrated from + // gnome-keyring can have any password. + let secret = Secret::from(vec![1]); + let keyring = UnlockedKeyring::load(&path, Some(secret.clone())).await?; + let attributes: HashMap<&str, &str> = HashMap::default(); + + keyring + .create_item("label", &attributes, "my-password", false) + .await?; + keyring.write().await?; + + let keyring = UnlockedKeyring::load(&path, Some(secret)).await?; + let items = keyring.items().await?; + assert_eq!(items.len(), 1); + assert_eq!(items[0].secret(), Secret::text("my-password")); + + Ok(()) +} + +#[tokio::test] +async fn concurrent_writes() -> Result<(), Error> { + let temp_dir = tempdir()?; + let path = temp_dir.path().join("concurrent_writes.keyring"); + + let keyring = Arc::new(UnlockedKeyring::load(&path, Some(strong_key())).await?); + + let keyring_clone = keyring.clone(); + let handle_1 = tokio::task::spawn(async move { keyring_clone.write().await }); + let handle_2 = tokio::task::spawn(async move { keyring.write().await }); + + let (res_1, res_2) = futures_util::future::join(handle_1, handle_2).await; + res_1.unwrap()?; + res_2.unwrap()?; + + Ok(()) +}