diff --git a/src/main.rs b/src/main.rs index 0c7fca4..e715f6d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -222,30 +222,40 @@ fn run() -> Result<()> { } // check if there are any subscriptions that we can fulfill - for open_subscription in &key_map.open_subscriptions() { - println!(); - println!("-- Open Subscription"); - println!("-- user: {}", open_subscription.username()); - println!("-- name: {}", open_subscription.name()); - - if !key_map.could_fulfill_subscription(open_subscription) { - println!( - "no key found to fulfill the subscription, ask someone who has access to this key" - ); - continue; + let mut fulfillable = Vec::new(); + let mut unfulfillable = Vec::new(); + for open_subscription in key_map.open_subscriptions() { + if key_map.could_fulfill_subscription(&open_subscription) { + fulfillable.push(open_subscription); + } else { + unfulfillable.push(open_subscription); } + } + if !unfulfillable.is_empty() { println!(); - - if Question::confirm( - " you've the required right to fulfill the subscription, give him access?", - ) { - key_map.fulfill_subscription(open_subscription)?; - } else { - println!("maybe later"); + println!( + "open subscriptions without a key to fulfill them, ask someone who has access ({}):", + unfulfillable.len() + ); + for subscription in &unfulfillable { + println!( + " - user: {}, name: {}", + subscription.username(), + subscription.name() + ); } + } - println!(); + fulfillable.sort_by(|a, b| (a.username(), a.name()).cmp(&(b.username(), b.name()))); + let accepted = Question::select( + "open subscriptions you've the required right to fulfill", + fulfillable, + |s| format!("user: {}, name: {}", s.username(), s.name()), + |s| format!(" give {} access to {}?", s.username(), s.name()), + ); + for subscription in &accepted { + key_map.fulfill_subscription(subscription)?; } println!(); @@ -275,6 +285,8 @@ pub fn scan_for_new_secrets(key_map: &KeyMap) -> Result { format!("could not read subscription path. could the directory be missing? {secret_path}") })?; + let mut new_secret_paths = Vec::new(); + for raw_path in paths { let path = raw_path.context("could not parse path")?; @@ -286,16 +298,19 @@ pub fn scan_for_new_secrets(key_map: &KeyMap) -> Result { continue; } - let path_as_string = path.path().display().to_string(); - - if !Question::confirm(&format!( - "do you want to add the new secret at {path_as_string}?" - )) { - continue; - } + new_secret_paths.push(path.path().display().to_string()); + } - key_map.add_new_secret(&path_as_string)?; + new_secret_paths.sort(); + let accepted = Question::select( + "new secrets", + new_secret_paths, + |path| path.clone(), + |path| format!("do you want to add the new secret at {path}?"), + ); + for path in &accepted { + key_map.add_new_secret(path)?; new_secrets_created += 1; } diff --git a/src/ui/question.rs b/src/ui/question.rs index 75044ae..c8216c6 100644 --- a/src/ui/question.rs +++ b/src/ui/question.rs @@ -3,6 +3,13 @@ use std::sync::atomic::{AtomicBool, Ordering}; static YES: AtomicBool = AtomicBool::new(false); +#[derive(Debug, PartialEq, Eq)] +pub enum BatchAnswer { + All, + None, + Each, +} + pub struct Question; impl Question { @@ -31,12 +38,70 @@ impl Question { s } - pub fn confirm(question: &str) -> bool { - if YES.load(Ordering::Relaxed) { - return true; + fn always_yes() -> bool { + YES.load(Ordering::Relaxed) + || std::env::vars().any(|(ref key, ref value)| key == "VAULT_FORCE_YES" && value == "1") + } + + /// Asks once for a whole batch: apply all, skip all, or decide item by item. + pub fn confirm_batch(question: &str) -> BatchAnswer { + if Self::always_yes() { + return BatchAnswer::All; + } + + loop { + match Self::ask(&format!( + "{question} (y)es to all / (n)o to all / (c)ase by case" + )) + .trim() + .to_lowercase() + .as_ref() + { + "y" | "j" | "a" => return BatchAnswer::All, + "n" => return BatchAnswer::None, + "c" => return BatchAnswer::Each, + chars => { + eprintln!("unexpected char \"{chars}\" - reask."); + continue; + } + }; + } + } + + /// Lists all planned changes, asks once, and returns the items the user accepted. + /// Choosing "each" falls back to asking per item. + pub fn select( + heading: &str, + items: Vec, + describe: impl Fn(&T) -> String, + per_item_question: impl Fn(&T) -> String, + ) -> Vec { + if items.is_empty() { + return items; } - if std::env::vars().any(|(ref key, ref value)| key == "VAULT_FORCE_YES" && value == "1") { + println!(); + println!("{heading} ({}):", items.len()); + for item in &items { + println!(" - {}", describe(item)); + } + println!(); + + match Self::confirm_batch(&format!("apply these {} change(s)?", items.len())) { + BatchAnswer::All => items, + BatchAnswer::None => { + println!("maybe later"); + Vec::new() + } + BatchAnswer::Each => items + .into_iter() + .filter(|item| Self::confirm(&per_item_question(item))) + .collect(), + } + } + + pub fn confirm(question: &str) -> bool { + if Self::always_yes() { return true; } @@ -66,5 +131,9 @@ mod test { Question::set_yes(true); let result = Question::confirm("a_question"); assert!(result); + assert_eq!(Question::confirm_batch("a_batch"), BatchAnswer::All); + let selected = + Question::select("items", vec![1, 2, 3], |i| i.to_string(), |i| i.to_string()); + assert_eq!(selected, vec![1, 2, 3]); } } diff --git a/tests/cli.rs b/tests/cli.rs index a6c714f..8f5df25 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1,4 +1,6 @@ //! Tests for CLI flags and general vault behavior. +use std::fs; +use std::time::Duration; use predicates::prelude::*; @@ -77,3 +79,96 @@ fn fails_without_vault_directory() { .assert() .failure(); } + +#[test] +fn batch_each_adds_only_accepted_secrets() { + let vault = TestVault::builder().build(); + fs::write(vault.path().join(".vault/secrets/A"), "a").unwrap(); + fs::write(vault.path().join(".vault/secrets/B"), "b").unwrap(); + + vault + .command() + .env_remove("VAULT_FORCE_YES") + .write_stdin("c\ny\nn\n") // case by case → yes to A, no to B (paths are sorted) + .timeout(Duration::from_secs(10)) + .assert() + .success() + .stdout(predicate::str::contains("new secrets (2):")) + .stderr(predicate::str::contains("unexpected char").not()); + + let secrets = vault.path().join(".vault/secrets"); + + // A was encrypted: the plaintext file is replaced by a directory with .crypt + assert!(secrets.join("A").is_dir()); + assert!( + secrets + .join("A") + .join(format!("{}.crypt", vault.username())) + .is_file() + ); + + // B was declined: still a plaintext file + assert!(secrets.join("B").is_file()); + assert_eq!(fs::read_to_string(secrets.join("B")).unwrap(), "b"); + + // A decrypts back to its original content + vault + .command() + .args(["get", "A"]) + .assert() + .success() + .stdout("a"); +} + +#[test] +fn batch_adds_all_secrets() { + let vault = TestVault::builder().build(); + fs::write(vault.path().join(".vault/secrets/A"), "a").unwrap(); + fs::write(vault.path().join(".vault/secrets/B"), "b").unwrap(); + + vault + .command() + .env_remove("VAULT_FORCE_YES") + .write_stdin("y\n") // yes to all + .timeout(Duration::from_secs(10)) + .assert() + .success() + .stdout(predicate::str::contains("new secrets (2):")) + .stderr(predicate::str::contains("unexpected char").not()); + + let secrets = vault.path().join(".vault/secrets"); + + // A was encrypted: the plaintext file is replaced by a directory with .crypt + assert!(secrets.join("A").is_dir()); + assert!( + secrets + .join("A") + .join(format!("{}.crypt", vault.username())) + .is_file() + ); + + // B was encrypted: the plaintext file is replaced by a directory with .crypt + assert!(secrets.join("B").is_dir()); + assert!( + secrets + .join("B") + .join(format!("{}.crypt", vault.username())) + .is_file() + ); + + // A decrypts back to its original content + vault + .command() + .args(["get", "A"]) + .assert() + .success() + .stdout("a"); + + // B decrypts back to its original content + vault + .command() + .args(["get", "B"]) + .assert() + .success() + .stdout("b"); +}