aboutsummaryrefslogtreecommitdiffstats
path: root/src/bin/rbw
diff options
context:
space:
mode:
authorJesse Luehrs <doy@tozt.net>2020-04-12 00:08:03 -0400
committerJesse Luehrs <doy@tozt.net>2020-04-12 00:08:03 -0400
commit236f06736e45c2a70f43589c9d447a0a3ef240b5 (patch)
treec390d4cbfec5223ac1aefe3947f8e1bb885757d2 /src/bin/rbw
parent91d1d1890bdc3ee75b69e00d5368c5b29a4f461c (diff)
downloadrbw-236f06736e45c2a70f43589c9d447a0a3ef240b5.tar.gz
rbw-236f06736e45c2a70f43589c9d447a0a3ef240b5.zip
improve error handling and reporting
Diffstat (limited to 'src/bin/rbw')
-rw-r--r--src/bin/rbw/actions.rs54
-rw-r--r--src/bin/rbw/commands.rs164
-rw-r--r--src/bin/rbw/main.rs63
-rw-r--r--src/bin/rbw/sock.rs31
4 files changed, 200 insertions, 112 deletions
diff --git a/src/bin/rbw/actions.rs b/src/bin/rbw/actions.rs
index cca2cf1..0844696 100644
--- a/src/bin/rbw/actions.rs
+++ b/src/bin/rbw/actions.rs
@@ -1,60 +1,64 @@
-pub fn login() {
- simple_action(rbw::agent::Action::Login, "login");
+pub fn login() -> anyhow::Result<()> {
+ simple_action(rbw::agent::Action::Login, "login")
}
-pub fn unlock() {
- simple_action(rbw::agent::Action::Unlock, "unlock");
+pub fn unlock() -> anyhow::Result<()> {
+ simple_action(rbw::agent::Action::Unlock, "unlock")
}
-pub fn sync() {
- simple_action(rbw::agent::Action::Sync, "sync");
+pub fn sync() -> anyhow::Result<()> {
+ simple_action(rbw::agent::Action::Sync, "sync")
}
-pub fn lock() {
- simple_action(rbw::agent::Action::Lock, "lock");
+pub fn lock() -> anyhow::Result<()> {
+ simple_action(rbw::agent::Action::Lock, "lock")
}
-pub fn quit() {
- let mut sock = crate::sock::Sock::connect();
+pub fn quit() -> anyhow::Result<()> {
+ let mut sock = crate::sock::Sock::connect()?;
sock.send(&rbw::agent::Request {
tty: std::env::var("TTY").ok(),
action: rbw::agent::Action::Quit,
- });
+ })?;
+ Ok(())
}
-pub fn decrypt(cipherstring: &str) -> String {
- let mut sock = crate::sock::Sock::connect();
+pub fn decrypt(cipherstring: &str) -> anyhow::Result<String> {
+ let mut sock = crate::sock::Sock::connect()?;
sock.send(&rbw::agent::Request {
tty: std::env::var("TTY").ok(),
action: rbw::agent::Action::Decrypt {
cipherstring: cipherstring.to_string(),
},
- });
+ })?;
- let res = sock.recv();
+ let res = sock.recv()?;
match res {
- rbw::agent::Response::Decrypt { plaintext } => plaintext,
+ rbw::agent::Response::Decrypt { plaintext } => Ok(plaintext),
rbw::agent::Response::Error { error } => {
- panic!("failed to decrypt: {}", error)
+ Err(anyhow::anyhow!("failed to decrypt: {}", error))
}
- _ => panic!("unexpected message: {:?}", res),
+ _ => Err(anyhow::anyhow!("unexpected message: {:?}", res)),
}
}
-fn simple_action(action: rbw::agent::Action, desc: &str) {
- let mut sock = crate::sock::Sock::connect();
+fn simple_action(
+ action: rbw::agent::Action,
+ desc: &str,
+) -> anyhow::Result<()> {
+ let mut sock = crate::sock::Sock::connect()?;
sock.send(&rbw::agent::Request {
tty: std::env::var("TTY").ok(),
action,
- });
+ })?;
- let res = sock.recv();
+ let res = sock.recv()?;
match res {
- rbw::agent::Response::Ack => (),
+ rbw::agent::Response::Ack => Ok(()),
rbw::agent::Response::Error { error } => {
- panic!("failed to {}: {}", desc, error)
+ Err(anyhow::anyhow!("failed to {}: {}", desc, error))
}
- _ => panic!("unexpected message: {:?}", res),
+ _ => Err(anyhow::anyhow!("unexpected message: {:?}", res)),
}
}
diff --git a/src/bin/rbw/commands.rs b/src/bin/rbw/commands.rs
index b76658c..83c6c81 100644
--- a/src/bin/rbw/commands.rs
+++ b/src/bin/rbw/commands.rs
@@ -1,76 +1,108 @@
-pub fn config_show() {
- let config = rbw::config::Config::load().unwrap();
- serde_json::to_writer_pretty(std::io::stdout(), &config).unwrap();
+use anyhow::Context as _;
+
+pub fn config_show() -> anyhow::Result<()> {
+ let config =
+ rbw::config::Config::load().context("failed to load config")?;
+ serde_json::to_writer_pretty(std::io::stdout(), &config)
+ .context("failed to write config to stdout")?;
println!();
+
+ Ok(())
}
-pub fn config_set(key: &str, value: &str) {
+pub fn config_set(key: &str, value: &str) -> anyhow::Result<()> {
let mut config = rbw::config::Config::load()
.unwrap_or_else(|_| rbw::config::Config::new());
match key {
"email" => config.email = Some(value.to_string()),
"base_url" => config.base_url = Some(value.to_string()),
"identity_url" => config.identity_url = Some(value.to_string()),
- "lock_timeout" => config.lock_timeout = value.parse().unwrap(),
- _ => unimplemented!(),
+ "lock_timeout" => {
+ config.lock_timeout = value
+ .parse()
+ .context("failed to parse value for lock_timeout")?
+ }
+ _ => return Err(anyhow::anyhow!("invalid config key: {}", key)),
}
- config.save().unwrap();
+ config.save().context("failed to save config file")?;
+
+ Ok(())
}
-pub fn login() {
- ensure_agent();
- crate::actions::login();
+pub fn login() -> anyhow::Result<()> {
+ ensure_agent()?;
+ crate::actions::login()?;
+
+ Ok(())
}
-pub fn unlock() {
- ensure_agent();
- crate::actions::login();
- crate::actions::unlock();
+pub fn unlock() -> anyhow::Result<()> {
+ ensure_agent()?;
+ crate::actions::login()?;
+ crate::actions::unlock()?;
+
+ Ok(())
}
-pub fn sync() {
- ensure_agent();
- crate::actions::login();
- crate::actions::sync();
+pub fn sync() -> anyhow::Result<()> {
+ ensure_agent()?;
+ crate::actions::login()?;
+ crate::actions::sync()?;
+
+ Ok(())
}
-pub fn list() {
- unlock();
+pub fn list() -> anyhow::Result<()> {
+ unlock()?;
- let email = config_email();
- let db = rbw::db::Db::load(&email).unwrap_or_else(|_| rbw::db::Db::new());
+ let email = config_email()?;
+ let db = rbw::db::Db::load(&email)
+ .context("failed to load password database")?;
for cipher in db.ciphers {
- println!("{}", crate::actions::decrypt(&cipher.name));
+ println!(
+ "{}",
+ crate::actions::decrypt(&cipher.name)
+ .context("failed to decrypt entry name")?
+ );
}
+
+ Ok(())
}
-pub fn get(name: &str, user: Option<&str>) {
- unlock();
+pub fn get(name: &str, user: Option<&str>) -> anyhow::Result<()> {
+ unlock()?;
- let email = config_email();
- let db = rbw::db::Db::load(&email).unwrap_or_else(|_| rbw::db::Db::new());
+ let email = config_email()?;
+ let db = rbw::db::Db::load(&email)
+ .context("failed to load password database")?;
for cipher in db.ciphers {
- let cipher_name = crate::actions::decrypt(&cipher.name);
+ let cipher_name = crate::actions::decrypt(&cipher.name)
+ .context("failed to decrypt entry name")?;
if name == cipher_name {
- let cipher_user = crate::actions::decrypt(&cipher.login.username);
+ let cipher_user = crate::actions::decrypt(&cipher.login.username)
+ .context("failed to decrypt entry username")?;
if let Some(user) = user {
if user == cipher_user {
let pass =
- crate::actions::decrypt(&cipher.login.password);
+ crate::actions::decrypt(&cipher.login.password)
+ .context("failed to decrypt entry password")?;
println!("{}", pass);
- return;
+ return Ok(());
}
} else {
- let pass = crate::actions::decrypt(&cipher.login.password);
+ let pass = crate::actions::decrypt(&cipher.login.password)
+ .context("failed to decrypt entry password")?;
println!("{}", pass);
- return;
+ return Ok(());
}
}
}
+
+ Ok(())
}
-pub fn add() {
- unlock();
+pub fn add() -> anyhow::Result<()> {
+ unlock()?;
todo!()
}
@@ -80,62 +112,82 @@ pub fn generate(
user: Option<&str>,
len: usize,
ty: rbw::pwgen::Type,
-) {
+) -> anyhow::Result<()> {
let pw = rbw::pwgen::pwgen(ty, len);
+ // unwrap is safe because pwgen is guaranteed to always return valid utf8
println!("{}", std::str::from_utf8(pw.data()).unwrap());
if name.is_some() && user.is_some() {
- unlock();
+ unlock()?;
todo!();
}
+
+ Ok(())
}
-pub fn edit() {
- unlock();
+pub fn edit() -> anyhow::Result<()> {
+ unlock()?;
todo!()
}
-pub fn remove() {
- unlock();
+pub fn remove() -> anyhow::Result<()> {
+ unlock()?;
todo!()
}
-pub fn lock() {
- ensure_agent();
- crate::actions::lock();
+pub fn lock() -> anyhow::Result<()> {
+ ensure_agent()?;
+ crate::actions::lock()?;
+
+ Ok(())
}
-pub fn purge() {
- stop_agent();
+pub fn purge() -> anyhow::Result<()> {
+ stop_agent()?;
+
+ let email = config_email()?;
+ rbw::db::Db::remove(&email).context("failed to remove database")?;
- let email = config_email();
- rbw::db::Db::remove(&email).unwrap();
+ Ok(())
}
-pub fn stop_agent() {
- crate::actions::quit();
+pub fn stop_agent() -> anyhow::Result<()> {
+ crate::actions::quit()?;
+
+ Ok(())
}
-fn ensure_agent() {
+fn ensure_agent() -> anyhow::Result<()> {
let agent_path = std::env::var("RBW_AGENT");
let agent_path = agent_path
.as_ref()
.map(|s| s.as_str())
.unwrap_or("rbw-agent");
- let status = std::process::Command::new(agent_path).status().unwrap();
+ let status = std::process::Command::new(agent_path)
+ .status()
+ .context("failed to run rbw-agent")?;
if !status.success() {
if let Some(code) = status.code() {
if code != 23 {
- panic!("failed to run agent: {}", status);
+ return Err(anyhow::anyhow!(
+ "failed to run rbw-agent: {}",
+ status
+ ));
}
}
}
+
+ Ok(())
}
-fn config_email() -> String {
- let config = rbw::config::Config::load().unwrap();
- config.email.unwrap()
+fn config_email() -> anyhow::Result<String> {
+ let config = rbw::config::Config::load()?;
+ if let Some(email) = config.email {
+ Ok(email)
+ } else {
+ Err(anyhow::anyhow!("failed to find email address in config"))
+ }
}
diff --git a/src/bin/rbw/main.rs b/src/bin/rbw/main.rs
index 065d143..1260edf 100644
--- a/src/bin/rbw/main.rs
+++ b/src/bin/rbw/main.rs
@@ -1,3 +1,5 @@
+use anyhow::Context as _;
+
mod actions;
mod commands;
mod sock;
@@ -54,27 +56,34 @@ fn main() {
.subcommand(clap::SubCommand::with_name("stop-agent"))
.get_matches();
- match matches.subcommand() {
+ let res = match matches.subcommand() {
("config", Some(smatches)) => match smatches.subcommand() {
- ("show", Some(_)) => commands::config_show(),
+ ("show", Some(_)) => {
+ commands::config_show().context("config show")
+ }
+ // these unwraps are fine because key and value are both marked
+ // .required(true)
("set", Some(ssmatches)) => commands::config_set(
ssmatches.value_of("key").unwrap(),
ssmatches.value_of("value").unwrap(),
- ),
+ )
+ .context("config set"),
_ => {
eprintln!("{}", smatches.usage());
std::process::exit(1);
}
},
- ("login", Some(_)) => commands::login(),
- ("unlock", Some(_)) => commands::unlock(),
- ("sync", Some(_)) => commands::sync(),
- ("list", Some(_)) => commands::list(),
+ ("login", Some(_)) => commands::login().context("login"),
+ ("unlock", Some(_)) => commands::unlock().context("unlock"),
+ ("sync", Some(_)) => commands::sync().context("sync"),
+ ("list", Some(_)) => commands::list().context("list"),
+ // this unwrap is safe because name is marked .required(true)
("get", Some(smatches)) => commands::get(
smatches.value_of("name").unwrap(),
smatches.value_of("user"),
- ),
- ("add", Some(_)) => commands::add(),
+ )
+ .context("get"),
+ ("add", Some(_)) => commands::add().context("add"),
("generate", Some(smatches)) => {
let ty = if smatches.is_present("no-symbols") {
rbw::pwgen::Type::NoSymbols
@@ -87,21 +96,35 @@ fn main() {
} else {
rbw::pwgen::Type::AllChars
};
- commands::generate(
- smatches.value_of("name"),
- smatches.value_of("user"),
- smatches.value_of("len").unwrap().parse().unwrap(),
- ty,
- );
+ // this unwrap is fine because len is marked as .required(true)
+ let len = smatches.value_of("len").unwrap();
+ match len.parse() {
+ Ok(len) => commands::generate(
+ smatches.value_of("name"),
+ smatches.value_of("user"),
+ len,
+ ty,
+ )
+ .context("generate"),
+ Err(e) => Err(e.into()),
+ }
+ }
+ ("edit", Some(_)) => commands::edit().context("edit"),
+ ("remove", Some(_)) => commands::remove().context("remove"),
+ ("lock", Some(_)) => commands::lock().context("lock"),
+ ("purge", Some(_)) => commands::purge().context("purge"),
+ ("stop-agent", Some(_)) => {
+ commands::stop_agent().context("stop-agent")
}
- ("edit", Some(_)) => commands::edit(),
- ("remove", Some(_)) => commands::remove(),
- ("lock", Some(_)) => commands::lock(),
- ("purge", Some(_)) => commands::purge(),
- ("stop-agent", Some(_)) => commands::stop_agent(),
_ => {
eprintln!("{}", matches.usage());
std::process::exit(1);
}
}
+ .context("rbw");
+
+ if let Err(e) = res {
+ eprintln!("{:#}", e);
+ std::process::exit(1);
+ }
}
diff --git a/src/bin/rbw/sock.rs b/src/bin/rbw/sock.rs
index 05597e6..4534e5e 100644
--- a/src/bin/rbw/sock.rs
+++ b/src/bin/rbw/sock.rs
@@ -1,29 +1,38 @@
+use anyhow::Context as _;
use std::io::{BufRead as _, Write as _};
pub struct Sock(std::os::unix::net::UnixStream);
impl Sock {
- pub fn connect() -> Self {
- Self(
+ pub fn connect() -> anyhow::Result<Self> {
+ Ok(Self(
std::os::unix::net::UnixStream::connect(
rbw::dirs::runtime_dir().join("socket"),
)
- .unwrap(),
- )
+ .context("failed to connect to rbw-agent")?,
+ ))
}
- pub fn send(&mut self, msg: &rbw::agent::Request) {
+ pub fn send(&mut self, msg: &rbw::agent::Request) -> anyhow::Result<()> {
let Self(sock) = self;
- sock.write_all(serde_json::to_string(msg).unwrap().as_bytes())
- .unwrap();
- sock.write_all(b"\n").unwrap();
+ sock.write_all(
+ serde_json::to_string(msg)
+ .context("failed to serialize message to agent")?
+ .as_bytes(),
+ )
+ .context("failed to send message to agent")?;
+ sock.write_all(b"\n")
+ .context("failed to send message to agent")?;
+ Ok(())
}
- pub fn recv(&mut self) -> rbw::agent::Response {
+ pub fn recv(&mut self) -> anyhow::Result<rbw::agent::Response> {
let Self(sock) = self;
let mut buf = std::io::BufReader::new(sock);
let mut line = String::new();
- buf.read_line(&mut line).unwrap();
- serde_json::from_str(&line).unwrap()
+ buf.read_line(&mut line)
+ .context("failed to read message from agent")?;
+ Ok(serde_json::from_str(&line)
+ .context("failed to parse message from agent")?)
}
}