ssh_vault/cli/actions/
view.rs

1use crate::cli::actions::Action;
2use crate::vault::{SshVault, dio, find, parse, ssh::decrypt_private_key};
3use anyhow::Result;
4use std::io::{Read, Write};
5use zeroize::Zeroize;
6
7/// Handle viewing a vault.
8///
9/// # Errors
10///
11/// Returns an error if reading the vault fails, the key cannot be loaded or
12/// decrypted, or decryption of the vault content fails.
13pub fn handle(action: Action) -> Result<()> {
14    match action {
15        Action::View {
16            key,
17            output,
18            vault,
19            passphrase,
20        } => {
21            let mut data = String::new();
22
23            // setup Reader(input) and Writer (output)
24            let (mut input, mut output) = dio::setup_io(vault, output)?;
25
26            input.read_to_string(&mut data)?;
27
28            // parse vault
29            let (key_type, fingerprint, password, data) = parse(&data)?;
30
31            // find the private_key using the vault header AES256 or CHACHA20-POLY1305
32            let mut private_key = find::private_key_type(key, key_type)?;
33
34            // decrypt private_key if encrypted
35            if private_key.is_encrypted() {
36                private_key = decrypt_private_key(&private_key, passphrase)?;
37            }
38
39            // RSA or ED25519
40            let key_type = find::key_type(&private_key.algorithm())?;
41
42            let vault = SshVault::new(&key_type, None, Some(private_key))?;
43
44            let mut data = vault.view(&password, &data, &fingerprint)?;
45
46            output.write_all(data.as_bytes())?;
47
48            // zeroize the secret
49            data.zeroize();
50        }
51        _ => unreachable!(),
52    }
53    Ok(())
54}