Skip to content
Open
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
69 changes: 42 additions & 27 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!();
Expand Down Expand Up @@ -275,6 +285,8 @@ pub fn scan_for_new_secrets(key_map: &KeyMap) -> Result<usize> {
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")?;

Expand All @@ -286,16 +298,19 @@ pub fn scan_for_new_secrets(key_map: &KeyMap) -> Result<usize> {
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;
}

Expand Down
77 changes: 73 additions & 4 deletions src/ui/question.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Comment on lines +8 to +10

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
All,
None,
Each,
None,
Each,
All,

Please also add doc comments to the enum itself and it's values.

}

pub struct Question;

impl Question {
Expand Down Expand Up @@ -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<T>(
heading: &str,
items: Vec<T>,
describe: impl Fn(&T) -> String,
per_item_question: impl Fn(&T) -> String,
) -> Vec<T> {
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 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add documentation comments for all public items you touched.

if Self::always_yes() {
return true;
}

Expand Down Expand Up @@ -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]);
}
}
95 changes: 95 additions & 0 deletions tests/cli.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
//! Tests for CLI flags and general vault behavior.
use std::fs;
use std::time::Duration;

use predicates::prelude::*;

Expand Down Expand Up @@ -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 <user>.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 <user>.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 <user>.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");
}