1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use ::std::env;
use ::std::fs;
use ::std::io::{stdin, BufRead};
use ::std::path::Path;
use ::std::path::PathBuf;
use ::std::str::FromStr;

use crate::key::Key;
use crate::util::FedResult;

#[derive(Debug, PartialEq, Eq)]
pub enum KeySource {
    CliArg(Key),
    EnvVar(String),
    File(PathBuf),
    AskTwice,
    AskOnce,
    Pipe,
}

impl FromStr for KeySource {
    type Err = String;

    fn from_str(txt: &str) -> Result<Self, Self::Err> {
        if txt.starts_with("pass:") {
            return Ok(KeySource::CliArg(Key::new(&txt[5..])));
        }
        if txt.starts_with("env:") {
            return Ok(KeySource::EnvVar(txt[4..].to_owned()));
        }
        if txt.starts_with("file:") {
            return Ok(KeySource::File(PathBuf::from(txt[5..].to_owned())));
        }
        if txt == "ask-once" || txt == "askonce" {
            return Ok(KeySource::AskOnce);
        }
        if txt == "ask" {
            return Ok(KeySource::AskTwice);
        }
        if txt == "pipe" {
            return Ok(KeySource::Pipe);
        }
        let txt_snip = if txt.len() > 5 {
            format!("{}...", txt[..4].to_owned())
        } else {
            txt.to_owned()
        };
        Err(format!(
            "key string was not recognized; got '{}', should be one of \
            'pass:$password', 'env:$var_name', 'file:$path', 'ask', 'ask-once', 'pipe'",
            txt_snip
        ))
    }
}

fn key_from_env_var(env_var_name: &str) -> FedResult<Key> {
    match env::var(env_var_name) {
        Ok(env_var_value) => Ok(Key::new(env_var_value.trim())),
        Err(err) => match err {
            env::VarError::NotPresent => Err(format!(
                "could not find environment variable named '{}' (which is \
                            expected to contain the encryption key)",
                env_var_name
            )),
            env::VarError::NotUnicode(_) => Err(format!(
                "environment variable named '{}' did not contain valid data (it \
                            is expected to contain the encryption key, which must be unicode)",
                env_var_name
            )),
        },
    }
}

fn key_from_file(file_path: &Path) -> FedResult<Key> {
    match fs::read_to_string(file_path) {
        Ok(content) => Ok(Key::new(content.trim())),
        Err(io_err) => Err(format!(
            "failed to read encryption key from \
                        file '{}'; reason: {}",
            file_path.to_string_lossy(),
            io_err
        )),
    }
}

fn ask_key_from_prompt(message: &str) -> FedResult<Key> {
    match rpassword::read_password_from_tty(Some(message)) {
        Ok(pw) => Ok(Key::new(pw.trim())),
        Err(_) => Err("failed to get password from interactive console".to_string()),
    }
}

fn key_from_prompt(ask_twice: bool) -> FedResult<Key> {
    if ask_twice {
        let pw1 = ask_key_from_prompt("key: ")?;
        let pw2 = ask_key_from_prompt("repeat key: ")?;
        if pw1 != pw2 {
            return Err("passwords did not match".to_owned());
        }
        Ok(pw2)
    } else {
        ask_key_from_prompt("key: ")
    }
}

fn key_from_pipe() -> FedResult<Key> {
    let mut pw = String::new();
    match stdin().lock().read_line(&mut pw) {
        Ok(count) => {
            if count >= 1 {
                Ok(Key::new(pw.trim()))
            } else {
                Err("no key was piped into the program".to_owned())
            }
        }
        Err(_) => Err("failed to read data piped into the program".to_owned()),
    }
}

impl KeySource {
    /// Obtain the key, which might involve IO.
    pub fn obtain_key(&self) -> FedResult<Key> {
        match self {
            KeySource::CliArg(pw) => Ok(pw.to_owned()),
            KeySource::EnvVar(env_var_name) => key_from_env_var(&env_var_name),
            KeySource::File(file_path) => key_from_file(&file_path),
            KeySource::AskOnce => key_from_prompt(false),
            KeySource::AskTwice => key_from_prompt(true),
            KeySource::Pipe => key_from_pipe(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn valid_pass() {
        assert_eq!(
            KeySource::from_str("pass:secret").unwrap(),
            KeySource::CliArg(Key::new("secret")),
        );
    }

    #[test]
    fn valid_env() {
        assert_eq!(
            KeySource::from_str("env:varname").unwrap(),
            KeySource::EnvVar("varname".to_owned()),
        );
    }

    #[test]
    fn valid_file() {
        assert_eq!(
            KeySource::from_str("file:/my/pass.txt").unwrap(),
            KeySource::File(PathBuf::from("/my/pass.txt")),
        );
    }
    #[test]
    fn valid_ask_twice() {
        assert_eq!(KeySource::from_str("ask").unwrap(), KeySource::AskTwice,);
    }
    #[test]
    fn valid_ask_once() {
        assert_eq!(KeySource::from_str("ask-once").unwrap(), KeySource::AskOnce,);
    }
    #[test]
    fn valid_pipe() {
        assert_eq!(KeySource::from_str("pipe").unwrap(), KeySource::Pipe,);
    }

    #[test]
    fn invalid_key() {
        assert!(KeySource::from_str("hi").is_err());
    }
}