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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#[macro_use]
extern crate failure;
#[macro_use]
extern crate log;

use directories::UserDirs;
use docopt::ArgvMap;
use reqwest::header::AUTHORIZATION;
use reqwest::Response;
use serde_json::Value;
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufWriter;
use std::path::Path;
use std::{env, fs};
use url::Url;

use failure::Error;

#[derive(Debug)]
pub struct Config {
    pub paths: Vec<String>,
    pub token: String,
    pub address: String,
}

impl Config {
    pub fn new(args: &ArgvMap) -> Result<Self, Error> {
        let token_path = UserDirs::new().unwrap().home_dir().join(".vault-token");

        let token = if let Ok(token) = fs::read_to_string(token_path) {
            String::from(token.trim())
        } else {
            return Err(format_err!(
                "~/.vault-token must exist, try running `vault login`"
            ));
        };

        let address = match env::var("VAULT_ADDR") {
            Ok(addr) => addr.trim_end_matches('/').to_string(),
            Err(_) => {
                return Err(format_err!("the $VAULT_ADDR environment variable must be set, e.g. `export VAULT_ADDR=https://vault.example.com`"))
            }
        };

        let paths = args.get_vec("<path>");
        let paths: Vec<String> = paths.into_iter().map(String::from).collect();

        Ok(Self {
            paths,
            token,
            address,
        })
    }
}

pub fn run(config: Config) -> Result<(), Error> {
    // Create a new http client to make use of connec
    let http = reqwest::Client::new();

    let mut vars: HashMap<String, String> = HashMap::new();

    for path in config.paths {
        let url = format_vault_url(config.address.as_str(), path.as_str())?;

        debug!("making request to \"{}\"", url);

        let req = http
            .get(url)
            .header(AUTHORIZATION, format!("Bearer {}", config.token));

        let mut resp: Response = req.send()?;

        if !resp.status().is_success() {
            return Err(format_err!(
                "vault responded with a {} status code for the '{}' path",
                resp.status().as_str(),
                path.clone()
            ));
        }

        let resp: Value = resp.json()?;
        let data = &resp["data"];

        // Handle the diffrent data formats for version 1 and 2 of the key-value secrets engine.
        if data["metadata"]["version"].is_number() {
            for (name, value) in data["data"].as_object().unwrap() {
                vars.insert(name.to_string(), String::from(value.as_str().unwrap()));
            }
        } else {
            for (name, value) in data.as_object().unwrap() {
                vars.insert(name.to_string(), String::from(value.as_str().unwrap()));
            }
        }
    }

    if Path::new(".env").is_file() {
        warn!("overwriting existing .env file");
    }

    let file = File::create(".env")?;
    let mut buf = BufWriter::new(file);

    let count = vars.len();

    save_environment_variables(vars, &mut buf)?;

    info!(
        "saved {} environment {} to .env",
        count,
        if count == 1 { "variable" } else { "variables" }
    );

    Ok(())
}

fn save_environment_variables<I>(variables: I, w: &mut Write) -> Result<(), Error>
where
    I: IntoIterator<Item = (String, String)>,
{
    for (variable, value) in variables {
        if value.contains('\n') {
            let value = value.replace("\n", "\\n");
            writeln!(w, "{}=\"{}\"", variable, value)?;
        } else {
            writeln!(w, "{}={}", variable, value)?;
        }
    }

    Ok(())
}

fn format_vault_url(address: &str, path: &str) -> Result<Url, Error> {
    let url = Url::parse(address)?;

    if (url.scheme() != "http" && url.scheme() != "https") || !url.has_authority() {
        return Err(format_err!(
            "only http and https schemes are allowed in VAULT_ADDR"
        ));
    }

    let url = url.join("v1/")?;
    let url = url.join(path)?;

    Ok(url)
}

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

    #[test]
    fn test_save_environment_variables_formats_for_dotenv() {
        // Using BTreeMap to get a consistent order.
        let mut vars: BTreeMap<String, String> = BTreeMap::new();
        vars.insert(String::from("fizz"), String::from("buzz"));
        vars.insert(String::from("foo"), String::from("bar"));

        let mut dotenv = Vec::new();

        save_environment_variables(vars, &mut dotenv).unwrap();

        assert_eq!(
            String::from_utf8(dotenv).unwrap(),
            String::from("fizz=buzz\nfoo=bar\n")
        );
    }

    #[test]
    fn test_save_environment_variables_quotes_and_escapes_multi_line_values() {
        // Using BTreeMap to get a consistent order.
        let mut vars: BTreeMap<String, String> = BTreeMap::new();
        vars.insert(
            String::from("EXAMPLE"),
            String::from("this is a\nmulti-line\nvalue"),
        );

        let mut dotenv = Vec::new();

        save_environment_variables(vars, &mut dotenv).unwrap();

        assert_eq!(
            String::from_utf8(dotenv).unwrap(),
            String::from("EXAMPLE=\"this is a\\nmulti-line\\nvalue\"\n")
        );
    }

    #[test]
    fn test_format_vault_url_formats_to_v1_api() {
        assert_eq!(
            format_vault_url("http://vault.example.com", "secret/foo-bar").unwrap(),
            Url::parse("http://vault.example.com/v1/secret/foo-bar").unwrap()
        );

        assert_eq!(
            format_vault_url("http://vault.example.com", "secret/foo-bar").unwrap(),
            Url::parse("http://vault.example.com/v1/secret/foo-bar").unwrap()
        );

        assert_eq!(
            format_vault_url("https://vault.example.com", "secret/foo-bar").unwrap(),
            Url::parse("https://vault.example.com/v1/secret/foo-bar").unwrap()
        );

        assert_eq!(
            format_vault_url("https://vault.example.com/", "secret/foo-bar").unwrap(),
            Url::parse("https://vault.example.com/v1/secret/foo-bar").unwrap()
        );

        assert_eq!(
            format_vault_url("http://127.0.0.1", "secret/foo-bar").unwrap(),
            Url::parse("http://127.0.0.1/v1/secret/foo-bar").unwrap()
        );

        assert_eq!(
            format_vault_url("http://127.0.0.1/", "secret/foo-bar").unwrap(),
            Url::parse("http://127.0.0.1/v1/secret/foo-bar").unwrap()
        );

        assert_eq!(
            format_vault_url("https://127.0.0.1", "secret/foo-bar").unwrap(),
            Url::parse("https://127.0.0.1/v1/secret/foo-bar").unwrap()
        );

        assert_eq!(
            format_vault_url("https://127.0.0.1/", "secret/foo-bar").unwrap(),
            Url::parse("https://127.0.0.1/v1/secret/foo-bar").unwrap()
        );

        assert_eq!(
            format_vault_url("http://[::1]", "secret/foo-bar").unwrap(),
            Url::parse("http://[::1]/v1/secret/foo-bar").unwrap()
        );

        assert_eq!(
            format_vault_url("http://[::1]/", "secret/foo-bar").unwrap(),
            Url::parse("http://[::1]/v1/secret/foo-bar").unwrap()
        );
    }

    #[test]
    fn test_format_vault_url_errors_on_bad_address() {
        assert!(format_vault_url("host-with-no-scheme", "secret/fizz-buzz").is_err());
        assert!(format_vault_url("https://", "secret/fizz-buzz").is_err());
        assert!(format_vault_url("http//localhost", "secret/fizz-buzz").is_err());

        // Only accept http or https.
        assert!(format_vault_url("data:text/plain", "secret/fizz-buzz").is_err());
        assert!(format_vault_url("ftp://localhost", "secret/fizz-buzz").is_err());
        assert!(format_vault_url("unix://localhost", "secret/fizz-buzz").is_err());
    }
}