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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 38 additions & 92 deletions server/src/collection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use oo7::{
ServiceError,
api::{DBusSecretInner, Properties},
},
file::Keyring,
};
use tokio::sync::{Mutex, RwLock};
use wire::{ObjectPath, OwnedObjectPath};
Expand All @@ -22,6 +21,7 @@ use crate::{
Service,
error::{Error, custom_service_error},
item,
storage::{ItemQuery, Keyring, Record},
};

#[derive(Clone)]
Expand Down Expand Up @@ -117,7 +117,7 @@ impl Collection {
let keyring_path = {
let keyring_guard = self.keyring.read().await;
let keyring = match keyring_guard.as_ref() {
Some(k) if !k.is_locked() => k.as_unlocked(),
Some(k) if !k.is_locked() => k,
_ => return Err(ServiceError::IsLocked("Collection is locked".to_owned())),
};
keyring.path().map(|p| p.to_path_buf())
Expand Down Expand Up @@ -262,7 +262,7 @@ impl Collection {
) -> Result<OwnedObjectPath, ServiceError> {
let keyring_guard = self.keyring.read().await;
let keyring = match keyring_guard.as_ref() {
Some(k) if !k.is_locked() => k.as_unlocked(),
Some(k) if !k.is_locked() => k,
_ => return Err(ServiceError::IsLocked("Collection is locked".to_owned())),
};

Expand Down Expand Up @@ -296,18 +296,16 @@ impl Collection {
);
}

let key = keyring
.key()
let query = keyring
.query(&attributes, true)
.await
.map_err(|err| custom_service_error(&format!("Failed to derive key: {err}")))?;

// When replacing, find existing items that match so we can update the
// first one in place, keeping its D-Bus object path valid for any
// concurrent GetSecret callers.
let existing_items = if replace {
let items = self
.search_items_with_key(&attributes, key.as_deref(), true)
.await?;
let items = self.matching_items(&query).await;
if items.is_empty() { None } else { Some(items) }
} else {
None
Expand All @@ -317,15 +315,14 @@ impl Collection {
.create_item(label, &attributes, secret, existing_items.is_some())
.await
.map_err(|err| custom_service_error(&format!("Failed to create a new item {err}.")))?;
drop(keyring_guard);

let signal_emitter = self.service.signal_emitter(&self.path)?;
let object_server = self.service.object_server();

let item_path = if let Some(existing_items) = existing_items {
let kept = &existing_items[0];
let kept_path: OwnedObjectPath = kept.path().to_owned().into();
*kept.inner.lock().await = Some(new_file_item.into());
*kept.inner.lock().await = new_file_item;

// Remove any duplicate matches beyond the first.
if existing_items.len() > 1 {
Expand All @@ -345,7 +342,7 @@ impl Collection {
let new_path = OwnedObjectPath::try_from(format!("{}/{n_items}", self.path)).unwrap();

let item = item::Item::new(
new_file_item.into(),
new_file_item,
self.service.clone(),
self.path.clone(),
new_path.clone(),
Expand All @@ -359,6 +356,7 @@ impl Collection {
new_path
};

drop(keyring_guard);
self.update_modified().await?;
self.items_changed(&signal_emitter).await?;

Expand Down Expand Up @@ -480,15 +478,14 @@ pub(crate) fn collection_path(label: &str) -> Result<OwnedObjectPath, wire::Erro
}

impl Collection {
pub async fn new(
pub(crate) async fn new(
name: &str,
label: &str,
alias: &str,
service: Service,
keyring: Keyring,
) -> Self {
let modified = keyring.modified_time().await;
let created = keyring.created_time().await.unwrap_or(modified);
let (created, modified) = keyring.timestamps().await;

Self {
items: Default::default(),
Expand Down Expand Up @@ -562,64 +559,26 @@ impl Collection {
let Some(keyring) = keyring_guard.as_ref() else {
return Ok(Vec::new());
};
if keyring.is_locked() {
drop(keyring_guard);

// The placeholder items of a pending migration store their
// attribute values as MD5 digests; hash the searched values
// to match them. The generic schema fallback is compared
// as-is.
let hashed: HashMap<String, String> = attributes
.iter()
.map(|(key, value)| {
if key.as_str() == oo7::XDG_SCHEMA_ATTRIBUTE
&& value.as_str() == oo7::GENERIC_SCHEMA
{
(key.clone(), value.clone())
} else {
(key.clone(), oo7::crypto::md5_hex(value))
}
})
.collect();
return self.search_items_with_key(&hashed, None, false).await;
}
let key = keyring
.as_unlocked()
.key()
let query = keyring
.query(attributes, false)
.await
.map_err(|err| custom_service_error(&format!("Failed to derive key: {err}")))?;
drop(keyring_guard);

self.search_items_with_key(attributes, key.as_deref(), false)
.await
Ok(self.matching_items(&query).await)
}

async fn search_items_with_key(
&self,
attributes: &HashMap<String, String>,
key: Option<&oo7::Key>,
exact: bool,
) -> Result<Vec<item::Item>, ServiceError> {
async fn matching_items(&self, query: &ItemQuery<'_>) -> Vec<item::Item> {
let mut matching_items = Vec::new();
let items = self.items.lock().await;

for item_wrapper in items.iter() {
let inner = item_wrapper.inner.lock().await;
let Some(file_item) = inner.as_ref() else {
continue;
};

let matches = if exact {
file_item.matches_attributes_exact(attributes, key)
} else {
file_item.matches_attributes(attributes, key)
};
if matches {
let record = item_wrapper.inner.lock().await;
if record.matches(query) {
matching_items.push(item_wrapper.clone());
}
}

Ok(matching_items)
matching_items
}

pub async fn item_from_path(&self, path: &ObjectPath<'_>) -> Option<item::Item> {
Expand All @@ -638,20 +597,14 @@ impl Collection {
if let Some(keyring) = keyring_guard.as_ref()
&& keyring.is_locked() != locked
{
let unlocked = match keyring {
Keyring::Locked(keyring) => Some(
if let Some(secret) = secret {
keyring.try_unlock(secret).await
} else {
keyring.try_unlock_unencrypted().await
}
.map_err(|err| {
custom_service_error(&format!("Failed to unlock keyring: {err}"))
})?,
),
Keyring::Unlocked(_) => None,
let unlocked = if locked {
None
} else {
Some(keyring.try_unlock(secret).await.map_err(|err| {
custom_service_error(&format!("Failed to unlock keyring: {err}"))
})?)
};
let item_keyring = unlocked.as_ref().unwrap_or_else(|| keyring.as_unlocked());
let item_keyring = unlocked.as_ref().unwrap_or(keyring);
let items = self.items.lock().await;
let mut changes = Vec::with_capacity(items.len());
for item in items.iter() {
Expand All @@ -660,15 +613,11 @@ impl Collection {
}
}

// All conversions succeeded. Commit the keyring and cached items
// before emitting any lock-state notifications.
if let Some(unlocked) = unlocked {
*keyring_guard = Some(Keyring::Unlocked(unlocked));
} else if let Some(Keyring::Unlocked(keyring)) = keyring_guard.take() {
*keyring_guard = Some(Keyring::Locked(keyring.lock()));
}
// Commit all prepared records and the keyring before sending any
// signals.
*keyring_guard = unlocked.or_else(|| keyring_guard.take().map(Keyring::lock));
for (mut current, next) in changes {
*current = Some(next);
*current = next;
}
for item in items.iter() {
item.notify_lock_state(locked).await?;
Expand All @@ -695,23 +644,20 @@ impl Collection {
}

pub async fn dispatch_items(&self) -> Result<(), Error> {
let keyring_items = {
let records = {
let keyring_guard = self.keyring.read().await;
let keyring = keyring_guard.as_ref().unwrap();
keyring.items().await?
};
self.dispatch_file_items(keyring_items).await
self.dispatch_records(records).await
}

/// Register the given file items on the object server and notify
/// Register the given records on the object server and notify
/// clients.
pub async fn dispatch_file_items(
&self,
keyring_items: Vec<oo7::file::Item>,
) -> Result<(), Error> {
pub(crate) async fn dispatch_records(&self, records: Vec<Record>) -> Result<(), Error> {
tracing::debug!(
"Dispatching {} items for collection `{}`.",
keyring_items.len(),
records.len(),
self.path
);

Expand All @@ -721,11 +667,11 @@ impl Collection {
let object_server = self.service.object_server();
let mut n_items = 1;

for keyring_item in keyring_items {
for record in records {
let item_path =
OwnedObjectPath::try_from(format!("{}/{n_items}", self.path)).unwrap();
let item = item::Item::new(
keyring_item,
record,
self.service.clone(),
self.path.clone(),
item_path.clone(),
Expand Down Expand Up @@ -763,7 +709,7 @@ impl Collection {

/// Replace the keyring with a just-migrated one, dispatch its items
/// and emit the corresponding change signals.
pub async fn apply_migrated_keyring(&self, keyring: Keyring) -> Result<(), Error> {
pub(crate) async fn apply_migrated_keyring(&self, keyring: Keyring) -> Result<(), Error> {
*self.keyring.write().await = Some(keyring);

// Drop the placeholder items, the migrated items take their paths
Expand Down Expand Up @@ -801,7 +747,7 @@ impl Collection {

let keyring_guard = self.keyring.read().await;
let keyring = match keyring_guard.as_ref() {
Some(k) if !k.is_locked() => k.as_unlocked(),
Some(k) if !k.is_locked() => k,
_ => {
return Err(ServiceError::IsLocked(format!(
"Cannot delete an item `{path}` in a locked collection"
Expand Down
2 changes: 1 addition & 1 deletion server/src/collection/tests/locking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ async fn failed_item_unlock_preserves_collection_state() -> Result<(), Box<dyn s
let collection_changes = setup.service_api.receive_collection_changed().await?;
tokio::pin!(item_changes, collection_changes);

let original = last.inner.lock().await.replace(foreign);
let original = std::mem::replace(&mut *last.inner.lock().await, foreign.into());
assert!(
collection
.set_locked(false, setup.keyring_secret.clone())
Expand Down
5 changes: 2 additions & 3 deletions server/src/gnome/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use oo7::{
ServiceError,
api::{DBusSecret, DBusSecretInner, Properties},
},
file::Keyring,
};
use zbus::wire::{ObjectPath, OwnedObjectPath, OwnedVariant};

Expand Down Expand Up @@ -123,7 +122,7 @@ impl InternalInterface {
.await?;

let keyring_guard = collection_obj.keyring.read().await;
if let Some(Keyring::Unlocked(unlocked)) = keyring_guard.as_ref() {
if let Some(unlocked) = keyring_guard.as_ref().filter(|k| !k.is_locked()) {
unlocked
.change_secret(new_secret)
.await
Expand Down Expand Up @@ -175,7 +174,7 @@ impl InternalInterface {
.ok_or_else(|| ServiceError::NoSuchObject(collection_path.to_string()))?;

let keyring_guard = collection.keyring.read().await;
if let Some(Keyring::Unlocked(unlocked)) = keyring_guard.as_ref() {
if let Some(unlocked) = keyring_guard.as_ref().filter(|k| !k.is_locked()) {
if let Some(new_secret) = new_secret {
unlocked.change_secret(new_secret).await.map_err(|err| {
custom_service_error(&format!("Failed to change secret: {err}"))
Expand Down
Loading
Loading