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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 123 additions & 36 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#![deny(unsafe_code)]

mod merge;

use std::{
collections::HashMap,
fmt,
Expand All @@ -10,14 +12,15 @@ use std::{
};

use clap::{Args, Parser, Subcommand};
use merge::OnConflict;
use oo7::dbus::Service;
use serde::Serialize;
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 {
Expand Down Expand Up @@ -63,7 +66,7 @@ trait InternalInterface {
) -> zbus::Result<zbus::wire::OwnedObjectPath>;
}

enum Error {
pub(crate) enum Error {
Owned(String),
Borrowed(&'static str),
}
Expand Down Expand Up @@ -323,6 +326,8 @@ enum Commands {
required = true, num_args = 1
)]
attributes: Vec<(String, String)>,
#[command(flatten)]
arguments: Arguments,
},

#[command(
Expand All @@ -344,6 +349,8 @@ enum Commands {
hex: bool,
#[arg(long, help = "Format the output as json.")]
json: bool,
#[command(flatten)]
arguments: Arguments,
},

#[command(
Expand All @@ -369,6 +376,8 @@ enum Commands {
hex: bool,
#[arg(long, help = "Format the output as json.")]
json: bool,
#[command(flatten)]
arguments: Arguments,
},

#[command(
Expand All @@ -385,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")]
Expand All @@ -393,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")]
Expand All @@ -402,20 +415,31 @@ 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 {
#[arg(
help = "The new secret. If not provided, it will be read from the terminal. Use '-' to read it from stdin"
)]
new_secret: Option<String>,
#[command(flatten)]
arguments: Arguments,
},

#[command(
Expand All @@ -429,6 +453,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<String>,
#[arg(
long,
value_name = "SECRET",
help = "The secret of the destination keyring file, use '-' to read it from stdin"
)]
destination_secret: Option<String>,
#[arg(
long,
value_enum,
help = "What to do when an item exists on both sides, defaults to asking"
)]
on_conflict: Option<OnConflict>,
},
}

#[derive(Clone, Default, clap::ValueEnum, fmt::Debug)]
Expand All @@ -450,7 +504,44 @@ 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,
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())?;

Expand Down Expand Up @@ -560,8 +651,10 @@ impl Commands {
};

let output = match self {
Commands::Migrate { .. } | Commands::ListCollections { .. } => unreachable!(),
Commands::Delete { attributes } => {
Commands::Migrate { .. }
| Commands::Merge { .. }
| Commands::ListCollections { .. } => unreachable!(),
Commands::Delete { attributes, .. } => {
match keyring {
Keyring::Collection(collection) => {
let items = collection.search_items(&attributes).await?;
Expand All @@ -580,6 +673,7 @@ impl Commands {
secret_only,
hex,
json,
..
} => match keyring {
Keyring::Collection(collection) => {
let items = collection.search_items(&attributes).await?;
Expand Down Expand Up @@ -612,6 +706,7 @@ impl Commands {
secret_only,
hex,
json,
..
} => match keyring {
Keyring::File(keyring) => {
let items = keyring.search_items(&attributes).await?;
Expand Down Expand Up @@ -660,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: ");
Expand Down Expand Up @@ -693,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?;
Expand Down Expand Up @@ -728,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."));
Expand All @@ -739,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."));
Expand All @@ -750,7 +847,7 @@ impl Commands {
}
Output::None
}
Commands::Repair => {
Commands::Repair { .. } => {
match keyring {
Keyring::File(keyring) => {
let deleted_items = keyring.delete_broken_items().await?;
Expand All @@ -762,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)? {
Expand Down Expand Up @@ -935,50 +1032,40 @@ 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<String>,
#[arg(
name = "keyring",
short,
long,
global = true,
help = "Specify the path to a keyring file"
)]
keyring: Option<PathBuf>,
#[arg(
name = "secret",
short,
long,
global = true,
help = "Specify the keyring secret. Use '-' to read it from stdin"
)]
secret: Option<String>,
#[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<oo7::ashpd::AppID>,
#[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.
Expand All @@ -1005,7 +1092,7 @@ fn read_secret_from_stdin() -> Result<oo7::Secret, Error> {
}

/// Resolve a secret argument, reading it from stdin when set to "-".
fn resolve_secret(secret: Option<String>) -> Result<Option<oo7::Secret>, Error> {
pub(crate) fn resolve_secret(secret: Option<String>) -> Result<Option<oo7::Secret>, Error> {
match secret {
Some(s) if s == "-" => Ok(Some(read_secret_from_stdin()?)),
Some(s) => Ok(Some(s.into())),
Expand All @@ -1017,15 +1104,15 @@ fn resolve_secret(secret: Option<String>) -> Result<Option<oo7::Secret>, Error>
async fn main() -> 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();
} else {
tracing_subscriber::fmt::init();
}

cli.command.execute(cli.args).await
cli.command.execute().await
}

// Source <https://github.com/clap-rs/clap/blob/master/examples/typed-derive.rs#L48>
Expand Down
Loading
Loading