diff options
-rw-r--r-- | src/actions.rs | 48 | ||||
-rw-r--r-- | src/api.rs | 29 | ||||
-rw-r--r-- | src/bin/rbw-agent/actions.rs | 2 | ||||
-rw-r--r-- | src/bin/rbw/commands.rs | 12 | ||||
-rw-r--r-- | src/config.rs | 8 | ||||
-rw-r--r-- | src/dirs.rs | 23 |
6 files changed, 78 insertions, 44 deletions
diff --git a/src/actions.rs b/src/actions.rs index f6cef56..df94c29 100644 --- a/src/actions.rs +++ b/src/actions.rs @@ -1,12 +1,17 @@ use crate::prelude::*; +fn api_client() -> Result<(crate::api::Client, crate::config::Config)> { + let config = crate::config::Config::load()?; + let client = + crate::api::Client::new(&config.base_url(), &config.identity_url(), &config.client_cert_path()); + Ok((client, config)) +} + pub async fn register( email: &str, apikey: crate::locked::ApiKey, ) -> Result<()> { - let config = crate::config::Config::load_async().await?; - let client = - crate::api::Client::new(&config.base_url(), &config.identity_url()); + let (client, config) = api_client()?; client .register(email, &crate::config::device_id(&config).await?, &apikey) @@ -21,10 +26,7 @@ pub async fn login( two_factor_token: Option<&str>, two_factor_provider: Option<crate::api::TwoFactorProviderType>, ) -> Result<(String, String, u32, String)> { - let config = crate::config::Config::load_async().await?; - let client = - crate::api::Client::new(&config.base_url(), &config.identity_url()); - + let (client, config) = api_client()?; let iterations = client.prelogin(email).await?; let identity = crate::identity::Identity::new(email, &password, iterations)?; @@ -121,9 +123,7 @@ async fn sync_once( std::collections::HashMap<String, String>, Vec<crate::db::Entry>, )> { - let config = crate::config::Config::load_async().await?; - let client = - crate::api::Client::new(&config.base_url(), &config.identity_url()); + let (client, _) = api_client()?; client.sync(access_token).await } @@ -147,9 +147,7 @@ fn add_once( notes: Option<&str>, folder_id: Option<&str>, ) -> Result<()> { - let config = crate::config::Config::load()?; - let client = - crate::api::Client::new(&config.base_url(), &config.identity_url()); + let (client, _) = api_client()?; client.add(access_token, name, data, notes, folder_id)?; Ok(()) } @@ -189,9 +187,7 @@ fn edit_once( folder_uuid: Option<&str>, history: &[crate::db::HistoryEntry], ) -> Result<()> { - let config = crate::config::Config::load()?; - let client = - crate::api::Client::new(&config.base_url(), &config.identity_url()); + let (client, _) = api_client()?; client.edit( access_token, id, @@ -216,9 +212,7 @@ pub fn remove( } fn remove_once(access_token: &str, id: &str) -> Result<()> { - let config = crate::config::Config::load()?; - let client = - crate::api::Client::new(&config.base_url(), &config.identity_url()); + let (client, _) = api_client()?; client.remove(access_token, id)?; Ok(()) } @@ -233,9 +227,7 @@ pub fn list_folders( } fn list_folders_once(access_token: &str) -> Result<Vec<(String, String)>> { - let config = crate::config::Config::load()?; - let client = - crate::api::Client::new(&config.base_url(), &config.identity_url()); + let (client, _) = api_client()?; client.folders(access_token) } @@ -250,9 +242,7 @@ pub fn create_folder( } fn create_folder_once(access_token: &str, name: &str) -> Result<String> { - let config = crate::config::Config::load()?; - let client = - crate::api::Client::new(&config.base_url(), &config.identity_url()); + let (client, _) = api_client()?; client.create_folder(access_token, name) } @@ -302,15 +292,11 @@ where } fn exchange_refresh_token(refresh_token: &str) -> Result<String> { - let config = crate::config::Config::load()?; - let client = - crate::api::Client::new(&config.base_url(), &config.identity_url()); + let (client, _) = api_client()?; client.exchange_refresh_token(refresh_token) } async fn exchange_refresh_token_async(refresh_token: &str) -> Result<String> { - let config = crate::config::Config::load_async().await?; - let client = - crate::api::Client::new(&config.base_url(), &config.identity_url()); + let (client, _) = api_client()?; client.exchange_refresh_token_async(refresh_token).await } @@ -8,6 +8,9 @@ use crate::json::{ DeserializeJsonWithPath as _, DeserializeJsonWithPathAsync as _, }; +use std::fs::File; +use std::io::Read; + #[derive( serde_repr::Serialize_repr, serde_repr::Deserialize_repr, @@ -551,22 +554,36 @@ struct FoldersPostReq { pub struct Client { base_url: String, identity_url: String, + client_cert_path: String, } impl Client { #[must_use] - pub fn new(base_url: &str, identity_url: &str) -> Self { + pub fn new(base_url: &str, identity_url: &str, client_cert_path: &str) -> Self { Self { base_url: base_url.to_string(), identity_url: identity_url.to_string(), + client_cert_path: client_cert_path.to_string(), } } + fn reqwest_client(&self) -> reqwest::Client { + return if self.client_cert_path == "" { + reqwest::Client::new() + } else { + let mut buf = Vec::new(); + let mut f = File::open(self.client_cert_path.to_string()).expect("cert not found"); + f.read_to_end(&mut buf).expect("cert read failed"); + let pem = reqwest::Identity::from_pem(&buf).expect("invalid cert"); + reqwest::Client::builder().identity(pem).build().expect("wtv") + }; + } + pub async fn prelogin(&self, email: &str) -> Result<u32> { let prelogin = PreloginReq { email: email.to_string(), }; - let client = reqwest::Client::new(); + let client = self.reqwest_client(); let res = client .post(&self.api_url("/accounts/prelogin")) .json(&prelogin) @@ -601,7 +618,7 @@ impl Client { two_factor_token: None, two_factor_provider: None, }; - let client = reqwest::Client::new(); + let client = self.reqwest_client(); let res = client .post(&self.identity_url("/connect/token")) .form(&connect_req) @@ -642,7 +659,7 @@ impl Client { #[allow(clippy::as_conversions)] two_factor_provider: two_factor_provider.map(|ty| ty as u32), }; - let client = reqwest::Client::new(); + let client = self.reqwest_client(); let res = client .post(&self.identity_url("/connect/token")) .form(&connect_req) @@ -676,7 +693,7 @@ impl Client { std::collections::HashMap<String, String>, Vec<crate::db::Entry>, )> { - let client = reqwest::Client::new(); + let client = self.reqwest_client(); let res = client .get(&self.api_url("/sync")) .header("Authorization", format!("Bearer {}", access_token)) @@ -1072,7 +1089,7 @@ impl Client { client_id: "desktop".to_string(), refresh_token: refresh_token.to_string(), }; - let client = reqwest::Client::new(); + let client = self.reqwest_client(); let res = client .post(&self.identity_url("/connect/token")) .form(&connect_req) diff --git a/src/bin/rbw-agent/actions.rs b/src/bin/rbw-agent/actions.rs index 87a8276..61eb74b 100644 --- a/src/bin/rbw-agent/actions.rs +++ b/src/bin/rbw-agent/actions.rs @@ -367,7 +367,7 @@ pub async fn unlock( let password = rbw::pinentry::getpin( &config_pinentry().await?, "Master Password", - "Unlock the local database", + &format!("Unlock the local database for '{}'", rbw::dirs::profile()), err.as_deref(), tty, true, diff --git a/src/bin/rbw/commands.rs b/src/bin/rbw/commands.rs index 654d964..fd720cf 100644 --- a/src/bin/rbw/commands.rs +++ b/src/bin/rbw/commands.rs @@ -1,4 +1,6 @@ use anyhow::Context as _; +use std::io; +use std::io::prelude::Write; const MISSING_CONFIG_HELP: &str = "Before using rbw, you must configure the email address you would like to \ @@ -614,6 +616,7 @@ pub fn config_set(key: &str, value: &str) -> anyhow::Result<()> { "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()), + "client_cert_path" => config.client_cert_path = Some(value.to_string()), "lock_timeout" => { let timeout = value .parse() @@ -646,6 +649,7 @@ pub fn config_unset(key: &str) -> anyhow::Result<()> { "email" => config.email = None, "base_url" => config.base_url = None, "identity_url" => config.identity_url = None, + "client_cert_path" => config.client_cert_path = None, "lock_timeout" => { config.lock_timeout = rbw::config::default_lock_timeout(); } @@ -739,7 +743,13 @@ pub fn list(fields: &[String]) -> anyhow::Result<()> { ), }) .collect(); - println!("{}", values.join("\t")); + + // write to stdout but don't panic when pipe get's closed + // this happens when piping stdout in a shell + match writeln!(&mut io::stdout(), "{}", values.join("\t")) { + Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => Ok(()), + res => res, + }?; } Ok(()) diff --git a/src/config.rs b/src/config.rs index 23ef765..baa855b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -12,6 +12,7 @@ pub struct Config { pub lock_timeout: u64, #[serde(default = "default_pinentry")] pub pinentry: String, + pub client_cert_path: Option<String>, // backcompat, no longer generated in new configs #[serde(skip_serializing)] pub device_id: Option<String>, @@ -25,6 +26,7 @@ impl Default for Config { identity_url: None, lock_timeout: default_lock_timeout(), pinentry: default_pinentry(), + client_cert_path: None, device_id: None, } } @@ -149,6 +151,12 @@ impl Config { } #[must_use] + pub fn client_cert_path(&self) -> String { + self.client_cert_path.clone() + .unwrap_or_else(|| "".to_string()) + } + + #[must_use] pub fn server_name(&self) -> String { self.base_url .clone() diff --git a/src/dirs.rs b/src/dirs.rs index 5ebeaa2..429f8bd 100644 --- a/src/dirs.rs +++ b/src/dirs.rs @@ -79,32 +79,45 @@ pub fn socket_file() -> std::path::PathBuf { #[must_use] fn config_dir() -> std::path::PathBuf { - let project_dirs = directories::ProjectDirs::from("", "", "rbw").unwrap(); + let project_dirs = + directories::ProjectDirs::from("", "", &profile()).unwrap(); project_dirs.config_dir().to_path_buf() } #[must_use] fn cache_dir() -> std::path::PathBuf { - let project_dirs = directories::ProjectDirs::from("", "", "rbw").unwrap(); + let project_dirs = + directories::ProjectDirs::from("", "", &profile()).unwrap(); project_dirs.cache_dir().to_path_buf() } #[must_use] fn data_dir() -> std::path::PathBuf { - let project_dirs = directories::ProjectDirs::from("", "", "rbw").unwrap(); + let project_dirs = + directories::ProjectDirs::from("", "", &profile()).unwrap(); project_dirs.data_dir().to_path_buf() } #[must_use] fn runtime_dir() -> std::path::PathBuf { - let project_dirs = directories::ProjectDirs::from("", "", "rbw").unwrap(); + let project_dirs = + directories::ProjectDirs::from("", "", &profile()).unwrap(); match project_dirs.runtime_dir() { Some(dir) => dir.to_path_buf(), None => format!( - "{}/rbw-{}", + "{}/{}-{}", std::env::temp_dir().to_string_lossy(), + &profile(), nix::unistd::getuid().as_raw() ) .into(), } } + +#[must_use] +pub fn profile() -> String { + match std::env::var("RBW_PROFILE") { + Ok(profile) if !profile.is_empty() => format!("rbw-{}", profile), + _ => "rbw".to_string(), + } +} |