From 5bbb61900ad2b4c95e4d92bcfdc458073b709e58 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Fri, 20 Nov 2026 09:35:00 +0100 Subject: [PATCH 1/4] server: Make collection iteration deterministic SearchItems, GetSecrets and alias resolution iterated the collections HashMap, whose order changes between daemon restarts. With items sharing attributes across collections, clients taking the first match got a different secret after every restart. Iterate the collections sorted by path, with the default collection first, where new items are stored. https://github.com/linux-credentials/oo7/issues/703 --- server/src/service/locking.rs | 8 ++-- server/src/service/mod.rs | 42 ++++++++++++++------- server/src/service/tests/search.rs | 59 ++++++++++++++++++++++++++++++ 3 files changed, 91 insertions(+), 18 deletions(-) diff --git a/server/src/service/locking.rs b/server/src/service/locking.rs index e4f1133b..b555bc60 100644 --- a/server/src/service/locking.rs +++ b/server/src/service/locking.rs @@ -1,5 +1,3 @@ -use std::collections::HashMap; - use oo7::{Secret, dbus::ServiceError, file::Keyring}; use zbus::{ proxy::Defaults, @@ -17,16 +15,16 @@ impl Service { ) -> Result<(Vec, Vec), ServiceError> { let mut without_prompt = Vec::new(); let mut with_prompt = Vec::new(); - let snapshot: HashMap = self.collections.lock().await.clone(); + let snapshot = self.sorted_collections().await; for object in objects { let resolved = Self::resolve_alias(&snapshot, object) .await .unwrap_or_else(|| object.clone()); let mut found = false; - for (path, collection) in snapshot.iter() { + for collection in &snapshot { let collection_locked = collection.is_locked().await; - if resolved == *path { + if resolved.as_str() == collection.path().as_str() { found = true; if collection_locked == locked { tracing::debug!( diff --git a/server/src/service/mod.rs b/server/src/service/mod.rs index 59e0e5a4..ab03e15d 100644 --- a/server/src/service/mod.rs +++ b/server/src/service/mod.rs @@ -213,7 +213,7 @@ impl Service { ) -> Result<(Vec, Vec), ServiceError> { let mut unlocked = Vec::new(); let mut locked = Vec::new(); - let snapshot: Vec = self.collections.lock().await.values().cloned().collect(); + let snapshot = self.sorted_collections().await; for collection in &snapshot { let items = collection.search_inner_items(&attributes).await?; @@ -339,7 +339,7 @@ impl Service { session ); let mut secrets = HashMap::new(); - let snapshot: Vec = self.collections.lock().await.values().cloned().collect(); + let snapshot = self.sorted_collections().await; 'outer: for collection in &snapshot { for item in &items { @@ -376,7 +376,7 @@ impl Service { #[zbus(out_args("collection"))] pub async fn read_alias(&self, name: &str) -> Result { - let collections = self.collections.lock().await; + let collections = self.sorted_collections().await; if let Some(path) = Self::find_by_alias(&collections, name).await { tracing::debug!("Collection: {} found for alias: {}.", path, name); Ok(path) @@ -511,25 +511,22 @@ impl Service { } async fn resolve_alias( - collections: &HashMap, + collections: &[Collection], path: &ObjectPath<'_>, ) -> Option { let alias = path.strip_prefix("/org/freedesktop/secrets/aliases/")?; Self::find_by_alias(collections, alias).await } - async fn find_by_alias( - collections: &HashMap, - alias: &str, - ) -> Option { + async fn find_by_alias(collections: &[Collection], alias: &str) -> Option { let alias_to_find = if alias == Self::LOGIN_ALIAS { oo7::dbus::Service::DEFAULT_COLLECTION } else { alias }; - for (path, collection) in collections.iter() { + for collection in collections { if collection.alias().await == alias_to_find { - return Some(path.clone()); + return Some(collection.path().to_owned().into()); } } None @@ -546,13 +543,32 @@ impl Service { None } + /// The collections sorted by path, with the default collection first, + /// so lookups and searches are deterministic across daemon restarts. + pub(crate) async fn sorted_collections(&self) -> Vec { + let collections: Vec = + self.collections.lock().await.values().cloned().collect(); + let mut sorted: Vec<(bool, Collection)> = Vec::with_capacity(collections.len()); + for collection in collections { + let is_default = collection.alias().await == oo7::dbus::Service::DEFAULT_COLLECTION; + sorted.push((!is_default, collection)); + } + sorted.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.path().cmp(b.1.path()))); + sorted + .into_iter() + .map(|(_, collection)| collection) + .collect() + } + pub async fn collection_from_path(&self, path: &ObjectPath<'_>) -> Option { - let collections = self.collections.lock().await; - if let Some(collection) = collections.get(path).cloned() { + if let Some(collection) = self.collections.lock().await.get(path).cloned() { return Some(collection); } + let collections = self.sorted_collections().await; let resolved = Self::resolve_alias(&collections, path).await?; - collections.get(&resolved).cloned() + collections + .into_iter() + .find(|c| c.path().as_str() == resolved.as_str()) } pub fn session_index(&self) -> u32 { diff --git a/server/src/service/tests/search.rs b/server/src/service/tests/search.rs index 85510b58..b8084fd6 100644 --- a/server/src/service/tests/search.rs +++ b/server/src/service/tests/search.rs @@ -195,3 +195,62 @@ async fn replace_item_missing_xdg_schema() -> Result<(), Box Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + + // An item in the default collection + let login_item = setup + .create_item("Login Item", &[("shared", "attr")], "login-secret", false) + .await?; + + // The same attributes in a few other collections + let mut other_items = Vec::new(); + for index in 0..4 { + let collection = setup + .service_api + .create_collection(&format!("Extra{index}"), None, None) + .await?; + let dbus_secret = setup.create_dbus_secret(format!("secret-{index}"))?; + other_items.push( + collection + .create_item( + &format!("Extra Item {index}"), + &[("shared", "attr")], + &dbus_secret, + false, + None, + ) + .await?, + ); + } + + let (unlocked, _) = setup + .service_api + .search_items(&[("shared", "attr")]) + .await?; + assert_eq!(unlocked.len(), 5); + + // The default collection's item comes first, the rest in path order + assert_eq!( + unlocked[0].inner().path().as_str(), + login_item.inner().path().as_str() + ); + let mut sorted_others: Vec<_> = other_items + .iter() + .map(|item| item.inner().path().as_str()) + .collect(); + sorted_others.sort_unstable(); + let result_others: Vec<_> = unlocked[1..] + .iter() + .map(|i| i.inner().path().as_str()) + .collect(); + assert_eq!(result_others, sorted_others); + + Ok(()) +} From acd7ea3bd82d98d6d1a51467b9a5944f76d74e77 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Fri, 20 Nov 2026 09:37:12 +0100 Subject: [PATCH 2/4] server: Clear the previous holder when setting an alias SetAlias left the alias on the collection previously holding it, so two collections claimed the same alias and ReadAlias depended on the HashMap iteration order again. https://github.com/linux-credentials/oo7/issues/703 --- server/src/service/mod.rs | 8 ++++++ server/src/service/tests/alias.rs | 42 +++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/server/src/service/mod.rs b/server/src/service/mod.rs index ab03e15d..e56bef00 100644 --- a/server/src/service/mod.rs +++ b/server/src/service/mod.rs @@ -391,6 +391,14 @@ impl Service { name: &str, collection: OwnedObjectPath, ) -> Result<(), ServiceError> { + // An alias points at a single collection, clear it from any other + // holder so resolving it stays deterministic + for other in self.sorted_collections().await { + if other.path().as_str() != collection.as_str() && other.alias().await == name { + other.set_alias("").await; + } + } + let collections = self.collections.lock().await; for (path, other_collection) in collections.iter() { diff --git a/server/src/service/tests/alias.rs b/server/src/service/tests/alias.rs index fb7fb179..4a9035fa 100644 --- a/server/src/service/tests/alias.rs +++ b/server/src/service/tests/alias.rs @@ -260,3 +260,45 @@ async fn duplicate_default_alias_resolved() -> Result<(), Box Result<(), Box> { + let setup = TestServiceSetup::plain_session(true).await?; + let login_path = setup.collections[0].inner().path().to_owned(); + + let other = setup + .service_api + .create_collection("Other", None, None) + .await?; + + // Move the default alias to the new collection + setup.service_api.set_alias("default", &other).await?; + + let aliased = setup + .service_api + .read_alias("default") + .await? + .expect("alias should resolve"); + assert_eq!( + aliased.inner().path(), + other.inner().path(), + "The alias should point to the new collection" + ); + + // The previous holder no longer claims it + let login = setup + .server + .collection_from_path(&login_path) + .await + .expect("login collection should exist"); + assert_eq!( + login.alias().await, + "", + "The previous holder must be cleared" + ); + + Ok(()) +} From 3287351ccec28628a99c140f1a8978d074ea6a43 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Fri, 20 Nov 2026 10:09:00 +0100 Subject: [PATCH 3/4] cli: Add a merge command Merge the items of a keyring or collection into another, resolving each side as a keyring file or a collection by alias, name or label. New items are copied over, identical ones skipped, and conflicting ones shown as a diff asking whether to override or skip, with --on-conflict for non-interactive use. The remedy for the collections left behind by the duplicate alias fixes, https://github.com/linux-credentials/oo7/issues/703 --- cli/src/main.rs | 61 ++++++++- cli/src/merge.rs | 343 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 400 insertions(+), 4 deletions(-) create mode 100644 cli/src/merge.rs diff --git a/cli/src/main.rs b/cli/src/main.rs index 3f2c4634..b63ec00a 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -1,5 +1,7 @@ #![deny(unsafe_code)] +mod merge; + use std::{ collections::HashMap, fmt, @@ -10,6 +12,7 @@ use std::{ }; use clap::{Args, Parser, Subcommand}; +use merge::OnConflict; use oo7::dbus::Service; use serde::Serialize; use time::{OffsetDateTime, UtcOffset}; @@ -17,7 +20,7 @@ use time::{OffsetDateTime, UtcOffset}; const BINARY_NAME: &str = env!("CARGO_BIN_NAME"); const H_STYLE: anstyle::Style = anstyle::Style::new().bold().underline(); -struct CliPrompter; +pub(crate) struct CliPrompter; #[zbus::interface(name = "org.freedesktop.secrets.CliPrompter")] impl CliPrompter { @@ -63,7 +66,7 @@ trait InternalInterface { ) -> zbus::Result; } -enum Error { +pub(crate) enum Error { Owned(String), Borrowed(&'static str), } @@ -429,6 +432,36 @@ enum Commands { #[arg(short, long, default_value_t, help = "Format of the legacy keyring")] format: MigrateFormat, }, + + #[command( + name = "merge", + about = "Merge the items of a keyring or collection into another", + after_help = format!("Each side is a keyring file path, or a collection of the running\n service by alias, name or label.\n\n{H_STYLE}Example:{H_STYLE:#}\n {} merge default2 default\n {0} merge ~/.local/share/keyrings/old.keyring default --origin-secret -", BINARY_NAME) + )] + Merge { + #[arg(help = "The keyring file, collection alias, name or label to merge from")] + origin: String, + #[arg(help = "The keyring file, collection alias, name or label to merge into")] + destination: String, + #[arg( + long, + value_name = "SECRET", + help = "The secret of the origin keyring file, use '-' to read it from stdin" + )] + origin_secret: Option, + #[arg( + long, + value_name = "SECRET", + help = "The secret of the destination keyring file, use '-' to read it from stdin" + )] + destination_secret: Option, + #[arg( + long, + value_enum, + help = "What to do when an item exists on both sides, defaults to asking" + )] + on_conflict: Option, + }, } #[derive(Clone, Default, clap::ValueEnum, fmt::Debug)] @@ -451,6 +484,24 @@ impl fmt::Display for MigrateFormat { impl Commands { async fn execute(self, mut args: Arguments) -> Result<(), Error> { + if let Commands::Merge { + origin, + destination, + origin_secret, + destination_secret, + on_conflict, + } = self + { + return merge::run( + &origin, + &destination, + origin_secret, + destination_secret, + on_conflict, + ) + .await; + } + // A secret of "-" is read from stdin let secret = resolve_secret(args.secret.take())?; @@ -560,7 +611,9 @@ impl Commands { }; let output = match self { - Commands::Migrate { .. } | Commands::ListCollections { .. } => unreachable!(), + Commands::Migrate { .. } + | Commands::Merge { .. } + | Commands::ListCollections { .. } => unreachable!(), Commands::Delete { attributes } => { match keyring { Keyring::Collection(collection) => { @@ -1005,7 +1058,7 @@ fn read_secret_from_stdin() -> Result { } /// Resolve a secret argument, reading it from stdin when set to "-". -fn resolve_secret(secret: Option) -> Result, Error> { +pub(crate) fn resolve_secret(secret: Option) -> Result, Error> { match secret { Some(s) if s == "-" => Ok(Some(read_secret_from_stdin()?)), Some(s) => Ok(Some(s.into())), diff --git a/cli/src/merge.rs b/cli/src/merge.rs new file mode 100644 index 00000000..0b1684c3 --- /dev/null +++ b/cli/src/merge.rs @@ -0,0 +1,343 @@ +//! The `merge` command: combine the items of two keyrings or collections. + +use std::{ + collections::HashMap, + io::{IsTerminal as _, Write as _}, +}; + +use oo7::dbus::Service; + +use crate::{CliPrompter, Error, resolve_secret}; + +/// What to do with an item that exists on both sides of a merge +#[derive(Clone, Copy, clap::ValueEnum)] +pub(crate) enum OnConflict { + /// Replace the destination item with the origin one + Override, + /// Keep the destination item + Skip, +} + +/// A side of a merge, either a keyring file or a collection of the +/// running service +enum MergeSource { + File(oo7::file::UnlockedKeyring), + Collection(oo7::dbus::Collection), +} + +/// The parts of an item needed for a merge +struct MergeItem { + label: String, + attributes: HashMap, + secret: oo7::Secret, +} + +/// The user's answer to a conflicting item +enum ConflictChoice { + Override, + Skip, + OverrideAll, + Quit, +} + +pub(crate) async fn run( + origin: &str, + destination: &str, + origin_secret: Option, + destination_secret: Option, + on_conflict: Option, +) -> Result<(), Error> { + let needs_service = + !std::path::Path::new(origin).is_file() || !std::path::Path::new(destination).is_file(); + let service = if needs_service { + Some(Service::new().await?) + } else { + None + }; + // Register the prompter so the daemon can ask for collection + // secrets + let prompter_conn = if needs_service { + let conn = zbus::Connection::session().await?; + conn.object_server() + .at("/org/freedesktop/secrets/CliPrompter", CliPrompter) + .await?; + conn.request_name("org.freedesktop.secrets.CliPrompter") + .await?; + Some(conn) + } else { + None + }; + + let origin = merge_source(origin, origin_secret, service.as_ref()).await?; + let destination = merge_source(destination, destination_secret, service.as_ref()).await?; + + // A locked collection can't be read from or written to, unlock it + // through the daemon, which prompts for its secret + for source in [&origin, &destination] { + if let MergeSource::Collection(collection) = source + && collection.is_locked().await? + { + let raw_service = oo7::dbus::api::Service::new(prompter_conn.as_ref().unwrap()).await?; + raw_service + .unlock(&[collection.path().to_owned()], None) + .await?; + } + } + + let origin_items = origin.items().await?; + let destination_items = destination.items().await?; + let mut created = 0; + let mut overridden = 0; + let mut skipped = 0; + let mut identical = 0; + let mut conflict_action = on_conflict; + + 'items: for item in &origin_items { + let Some(conflict) = find_conflict(&destination_items, item) else { + destination.create_item(item, false).await?; + created += 1; + continue; + }; + + if conflict.secret == item.secret && conflict.label == item.label { + identical += 1; + continue; + } + + let choice = match conflict_action { + Some(OnConflict::Override) => ConflictChoice::Override, + Some(OnConflict::Skip) => ConflictChoice::Skip, + None => prompt_conflict(item, conflict)?, + }; + match choice { + ConflictChoice::Override => { + destination.create_item(item, true).await?; + overridden += 1; + } + ConflictChoice::Skip => skipped += 1, + ConflictChoice::OverrideAll => { + conflict_action = Some(OnConflict::Override); + destination.create_item(item, true).await?; + overridden += 1; + } + ConflictChoice::Quit => { + println!("Quitting, keeping the items merged so far."); + break 'items; + } + } + } + + if let MergeSource::File(keyring) = &destination { + keyring.write().await?; + } + + println!( + "Merged {created} new item(s), overrode {overridden}, skipped {skipped}, {identical} already identical." + ); + + Ok(()) +} + +async fn merge_source( + spec: &str, + secret: Option, + service: Option<&Service>, +) -> Result { + let path = std::path::Path::new(spec); + if path.is_file() { + let secret = match resolve_secret(secret)? { + Some(secret) => Some(secret), + None if std::io::stdin().is_terminal() => { + let password = rpassword::prompt_password(format!("'{spec}' secret: ")) + .map_err(|_| Error::new("Can't read secret"))?; + Some(password.into()) + } + None => None, + }; + // Same loading semantics as the other keyring file commands + #[allow(unsafe_code)] + let keyring = unsafe { + match secret { + Some(secret) => oo7::file::UnlockedKeyring::load_unchecked(path, secret).await?, + None => oo7::file::UnlockedKeyring::load(path, None).await?, + } + }; + Ok(MergeSource::File(keyring)) + } else { + let service = service.ok_or_else(|| Error::new("No service"))?; + let collection = match service.with_alias(spec).await? { + Some(collection) => collection, + // Not an alias, look the collection up by name or label + None => { + let mut found = None; + for collection in service.collections().await? { + if collection.path().rsplit('/').next() == Some(spec) + || collection + .label() + .await + .is_ok_and(|label| label.eq_ignore_ascii_case(spec)) + { + found = Some(collection); + break; + } + } + found.ok_or_else(|| { + Error::Owned(format!( + "'{spec}' is neither a keyring file nor a collection" + )) + })? + } + }; + Ok(MergeSource::Collection(collection)) + } +} + +impl MergeSource { + async fn items(&self) -> Result, Error> { + match self { + Self::File(keyring) => Ok(keyring + .items() + .await? + .into_iter() + .map(|item| MergeItem { + label: item.label().to_owned(), + attributes: item.attributes().clone(), + secret: item.secret(), + }) + .collect()), + Self::Collection(collection) => { + let mut items = Vec::new(); + for item in collection.items().await? { + items.push(MergeItem { + label: item.label().await?, + attributes: item.attributes().await?, + secret: item.secret().await?, + }); + } + Ok(items) + } + } + } + + async fn create_item(&self, item: &MergeItem, replace: bool) -> Result<(), Error> { + match self { + Self::File(keyring) => { + keyring + .create_item(&item.label, &item.attributes, item.secret.clone(), replace) + .await?; + } + Self::Collection(collection) => { + collection + .create_item( + &item.label, + &item.attributes, + item.secret.clone(), + replace, + None, + ) + .await?; + } + } + Ok(()) + } +} + +/// The destination item an origin item would replace, if any +fn find_conflict<'a>(destination: &'a [MergeItem], origin: &MergeItem) -> Option<&'a MergeItem> { + destination.iter().find(|dest| { + origin.attributes.iter().all(|(key, value)| { + dest.attributes.get(key).map(String::as_str) == Some(value.as_str()) + }) + }) +} + +fn prompt_conflict(origin: &MergeItem, destination: &MergeItem) -> Result { + print_conflict(origin, destination); + + if !std::io::stdin().is_terminal() { + println!("Not a terminal, skipping the item. Use --on-conflict to decide."); + return Ok(ConflictChoice::Skip); + } + + loop { + print!("[o]verride, [s]kip, override [a]ll, [q]uit: "); + std::io::stdout() + .flush() + .map_err(|_| Error::new("Could not flush stdout"))?; + let mut answer = String::new(); + std::io::stdin() + .read_line(&mut answer) + .map_err(|_| Error::new("Can't read the answer"))?; + match answer.trim().to_lowercase().as_str() { + "o" | "override" => return Ok(ConflictChoice::Override), + "s" | "skip" => return Ok(ConflictChoice::Skip), + "a" | "all" => return Ok(ConflictChoice::OverrideAll), + "q" | "quit" => return Ok(ConflictChoice::Quit), + "" => { + println!("No answer, skipping the item."); + return Ok(ConflictChoice::Skip); + } + _ => println!("Please answer o, s, a or q."), + } + } +} + +fn print_conflict(origin: &MergeItem, destination: &MergeItem) { + let minus = anstyle::AnsiColor::Red.on_default(); + let plus = anstyle::AnsiColor::Green.on_default(); + + println!("Item \"{}\"", origin.label); + let mut keys: Vec = origin.attributes.keys().cloned().collect(); + keys.sort(); + for key in &keys { + if destination.attributes.get(key) == origin.attributes.get(key) { + println!(" {key} = {}", origin.attributes[key]); + } + } + if origin.label != destination.label { + println!( + "{}-{} destination label: {}", + minus.render(), + minus.render_reset(), + destination.label + ); + println!( + "{}+{} origin label: {}", + plus.render(), + plus.render_reset(), + origin.label + ); + } + for key in &keys { + if destination.attributes.get(key) != origin.attributes.get(key) { + println!( + "{}-{} destination {key} = {}", + minus.render(), + minus.render_reset(), + destination + .attributes + .get(key) + .map(String::as_str) + .unwrap_or("") + ); + println!( + "{}+{} origin {key} = {}", + plus.render(), + plus.render_reset(), + origin.attributes[key] + ); + } + } + println!( + "{}-{} destination secret: {}", + minus.render(), + minus.render_reset(), + String::from_utf8_lossy(destination.secret.as_bytes()) + ); + println!( + "{}+{} origin secret: {}", + plus.render(), + plus.render_reset(), + String::from_utf8_lossy(origin.secret.as_bytes()) + ); +} From 99b8bcc102cb0050e3d924748bd7dddee5807015 Mon Sep 17 00:00:00 2001 From: Bilal Elmoussaoui Date: Fri, 20 Nov 2026 10:25:25 +0100 Subject: [PATCH 4/4] cli: Only accept the shared options where they apply The collection, keyring, secret and app-id options were global, showing up in the help of commands that ignore them. Move them to the commands using them; --verbose stays global. Passing them before the subcommand now errors, the after-subcommand form is unchanged. --- cli/src/main.rs | 98 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 66 insertions(+), 32 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index b63ec00a..a66e0575 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -326,6 +326,8 @@ enum Commands { required = true, num_args = 1 )] attributes: Vec<(String, String)>, + #[command(flatten)] + arguments: Arguments, }, #[command( @@ -347,6 +349,8 @@ enum Commands { hex: bool, #[arg(long, help = "Format the output as json.")] json: bool, + #[command(flatten)] + arguments: Arguments, }, #[command( @@ -372,6 +376,8 @@ enum Commands { hex: bool, #[arg(long, help = "Format the output as json.")] json: bool, + #[command(flatten)] + arguments: Arguments, }, #[command( @@ -388,6 +394,8 @@ enum Commands { required = true, num_args = 1 )] attributes: Vec<(String, String)>, + #[command(flatten)] + arguments: Arguments, }, #[command(name = "list", about = "List all the items in the keyring")] @@ -396,6 +404,8 @@ enum Commands { hex: bool, #[arg(long, help = "Format the output as json.")] json: bool, + #[command(flatten)] + arguments: Arguments, }, #[command(name = "list-collections", about = "List available collections")] @@ -405,13 +415,22 @@ enum Commands { }, #[command(name = "lock", about = "Lock the keyring")] - Lock, + Lock { + #[command(flatten)] + arguments: Arguments, + }, #[command(name = "unlock", about = "Unlock the keyring")] - Unlock, + Unlock { + #[command(flatten)] + arguments: Arguments, + }, #[command(name = "repair", about = "Repair the keyring")] - Repair, + Repair { + #[command(flatten)] + arguments: Arguments, + }, #[command(name = "change-secret", about = "Change the keyring secret")] ChangeSecret { @@ -419,6 +438,8 @@ enum Commands { help = "The new secret. If not provided, it will be read from the terminal. Use '-' to read it from stdin" )] new_secret: Option, + #[command(flatten)] + arguments: Arguments, }, #[command( @@ -483,7 +504,26 @@ impl fmt::Display for MigrateFormat { } impl Commands { - async fn execute(self, mut args: Arguments) -> Result<(), Error> { + fn arguments(&self) -> Arguments { + match self { + Self::Delete { arguments, .. } + | Self::Lookup { arguments, .. } + | Self::Search { arguments, .. } + | Self::Store { arguments, .. } + | Self::List { arguments, .. } + | Self::Lock { arguments } + | Self::Unlock { arguments } + | Self::Repair { arguments } + | Self::ChangeSecret { arguments, .. } => arguments.clone(), + Self::ListCollections { .. } | Self::Migrate { .. } | Self::Merge { .. } => { + Arguments::default() + } + } + } + + async fn execute(self) -> Result<(), Error> { + let mut args = self.arguments(); + if let Commands::Merge { origin, destination, @@ -614,7 +654,7 @@ impl Commands { Commands::Migrate { .. } | Commands::Merge { .. } | Commands::ListCollections { .. } => unreachable!(), - Commands::Delete { attributes } => { + Commands::Delete { attributes, .. } => { match keyring { Keyring::Collection(collection) => { let items = collection.search_items(&attributes).await?; @@ -633,6 +673,7 @@ impl Commands { secret_only, hex, json, + .. } => match keyring { Keyring::Collection(collection) => { let items = collection.search_items(&attributes).await?; @@ -665,6 +706,7 @@ impl Commands { secret_only, hex, json, + .. } => match keyring { Keyring::File(keyring) => { let items = keyring.search_items(&attributes).await?; @@ -713,7 +755,9 @@ impl Commands { } } }, - Commands::Store { label, attributes } => { + Commands::Store { + label, attributes, .. + } => { let mut stdin = std::io::stdin().lock(); let secret: oo7::Secret = if stdin.is_terminal() { print!("Type a secret: "); @@ -746,7 +790,7 @@ impl Commands { } Output::None } - Commands::List { hex, json } => { + Commands::List { hex, json, .. } => { let items = match keyring { Keyring::File(keyring) => { let items = keyring.all_items().await?; @@ -781,7 +825,7 @@ impl Commands { }; Output::Items(items, json) } - Commands::Lock => { + Commands::Lock { .. } => { match keyring { Keyring::File(_) => { return Err(Error::new("Keyring file doesn't support locking.")); @@ -792,7 +836,7 @@ impl Commands { } Output::None } - Commands::Unlock => { + Commands::Unlock { .. } => { match keyring { Keyring::File(_) => { return Err(Error::new("Keyring file doesn't support unlocking.")); @@ -803,7 +847,7 @@ impl Commands { } Output::None } - Commands::Repair => { + Commands::Repair { .. } => { match keyring { Keyring::File(keyring) => { let deleted_items = keyring.delete_broken_items().await?; @@ -815,7 +859,7 @@ impl Commands { } Output::None } - Commands::ChangeSecret { new_secret } => { + Commands::ChangeSecret { new_secret, .. } => { match keyring { Keyring::File(keyring) => { let secret = match resolve_secret(new_secret)? { @@ -988,17 +1032,21 @@ impl Commands { struct Cli { #[command(subcommand)] command: Commands, - #[command(flatten)] - args: Arguments, + #[arg( + short = 'v', + long = "verbose", + global = true, + help = "Print debug information during command processing." + )] + is_verbose: bool, } -#[derive(Args)] +#[derive(Args, Clone, Default)] struct Arguments { #[arg( name = "collection", short, long, - global = true, help = "Specify a collection by name. The default collection will be used if not specified" )] collection: Option, @@ -1006,7 +1054,6 @@ struct Arguments { name = "keyring", short, long, - global = true, help = "Specify the path to a keyring file" )] keyring: Option, @@ -1014,24 +1061,11 @@ struct Arguments { name = "secret", short, long, - global = true, help = "Specify the keyring secret. Use '-' to read it from stdin" )] secret: Option, - #[arg( - name = "app-id", - long, - global = true, - help = "Specify a sandboxed application ID" - )] + #[arg(name = "app-id", long, help = "Specify a sandboxed application ID")] app_id: Option, - #[arg( - short = 'v', - long = "verbose", - global = true, - help = "Print debug information during command processing." - )] - is_verbose: bool, } /// Read a secret from stdin, prompting on the terminal if there is one. @@ -1070,7 +1104,7 @@ pub(crate) fn resolve_secret(secret: Option) -> Result Result<(), Error> { let cli = Cli::parse(); - if cli.args.is_verbose { + if cli.is_verbose { tracing_subscriber::fmt() .with_max_level(tracing_subscriber::filter::LevelFilter::DEBUG) .init(); @@ -1078,7 +1112,7 @@ async fn main() -> Result<(), Error> { tracing_subscriber::fmt::init(); } - cli.command.execute(cli.args).await + cli.command.execute().await } // Source