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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
//! This is documentation for the `vdot` crate.

use failure::{Error, Fail};
use log::{debug, info, warn};
use std::collections::HashMap;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufWriter;
use std::path::{Path, PathBuf};
use std::process::Command;
use structopt::StructOpt;
use url::Url;

pub mod logger;

#[derive(Fail, Debug)]
#[fail(display = "Vault responded with {} for the '{}' path", status, path)]
pub struct VaultResponseError {
    status: reqwest::StatusCode,
    path: String,
}

#[derive(StructOpt, Debug)]
#[structopt(author = "", about = "", usage = "vdot [FLAGS] [OPTIONS] <PATH>...")]
pub struct Args {
    /// Path to the Vault secrets
    ///
    /// If duplicate keys are found when providing more than one path the value from the first path will be saved.
    ///
    /// Use something like `secret/foo-bar` for v1 of the Vault key-value secrets engine, and `secret/data/foo-bar` for v2.
    ///
    /// e.g. `vdot secret/foo secret/bar`
    ///
    /// See https://www.vaultproject.io/docs/secrets/kv/index.html for more information.
    #[structopt(name = "PATH", raw(required = "true"))]
    pub paths: Vec<String>,

    /// Write to the given file
    ///
    /// e.g. `vdot --output .env.test secret/foo`
    #[structopt(
        short = "o",
        long = "output",
        default_value = ".env",
        parse(from_os_str)
    )]
    pub output: PathBuf,

    /// Command to spawn
    ///
    /// This option will spawn the given command with the environment variables downloaded from Vault.
    ///
    /// e.g. `vdot -c 'npm start' secret/foo`
    #[structopt(short = "c", long = "command", conflicts_with = "output")]
    pub command: Option<String>,

    /// Vault token used to authenticate requests
    ///
    /// This can also be provided by setting the VAULT_TOKEN environment variable.
    ///
    /// e.g. `vdot --vault-token $(cat ~/.vault-token) secret/foo`
    ///
    /// See https://www.vaultproject.io/docs/concepts/auth.html#tokens for more information.
    #[structopt(long = "vault-token", env = "VAULT_TOKEN", hide_env_values = true)]
    pub vault_token: String,

    /// Vault server address
    ///
    /// This can also be provided by setting the VAULT_ADDR environment variable.
    ///
    /// e.g. `vdot --vault-address http://127.0.0.1:8200 secret/foo`
    #[structopt(long = "vault-address", env = "VAULT_ADDR", hide_env_values = true)]
    pub vault_address: Url,

    /// Verbose mode
    #[structopt(short = "v", long = "verbose", parse(from_occurrences))]
    pub verbose: u8,
}

/// Use the given command line arguments to run vdot.
///
/// # Examples
///
/// ```
/// use log::error;
/// use std::path::PathBuf;
/// use std::process;
/// use vdot::Args;
///
/// let args = Args {
///     paths: vec![],
///     output: PathBuf::from(".env"),
///     command: None,
///     vault_token: "hunter2".to_string(),
///     vault_address: url::Url::parse("http://127.0.0.1:8200").unwrap(),
///     verbose: 0
/// };
///
/// if let Err(err) = vdot::run(args) {
///     error!("{}", err);
///     process::exit(1);
/// }
/// ```
///
/// # Errors
///
/// Returns an error if anything goes wrong, and exits the process with a status code of 1.
pub fn run(args: Args) -> Result<(), Error> {
    // Create a new http client to make use of connection pooling.
    let http = reqwest::Client::new();

    // Key-value store for the environment variable downloaded from Vault.
    let mut vars: HashMap<String, String> = HashMap::new();

    let mut paths = args.paths;

    // Reverse the order of paths so that latter paths with a duplicate variable name are overwritten.
    paths.reverse();

    for path in paths {
        // Build the Vault API url.
        let url = args.vault_address.join("v1/")?;
        let url = url.join(path.as_str())?;

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

        let req = http.get(url).header(
            reqwest::header::AUTHORIZATION,
            format!("Bearer {}", args.vault_token),
        );

        let mut resp = req.send()?;

        if !resp.status().is_success() {
            return Err(VaultResponseError {
                status: resp.status(),
                path,
            })?;
        }

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

        // Handle the diffrent data formats for version 1 and 2 of the key-value secrets engine.
        let data = if data["metadata"]["version"].is_number() {
            data["data"].as_object().unwrap()
        } else {
            data.as_object().unwrap()
        };

        for (name, value) in data {
            let name = name.to_string();
            let value = match stringify_json_value(&value) {
                Some(value) => value,
                None => {
                    warn!(
                        "the value for {} in {} is an array or object and will be ignored",
                        name, path
                    );
                    continue;
                }
            };

            vars.insert(name, value);
        }
    }

    if let Some(command) = args.command {
        return start_process(command, vars);
    }

    save_dotenv(args.output, vars)
}

fn start_process(process: String, vars: HashMap<String, String>) -> Result<(), Error> {
    let mut command = process.split_whitespace();

    info!("running `{}`", process);

    // The first part is the process to start.
    Command::new(command.next().unwrap())
        .args(command)
        .envs(vars)
        .status()?;

    Ok(())
}

fn save_dotenv(path: PathBuf, vars: HashMap<String, String>) -> Result<(), Error> {
    if Path::new(&path).is_file() {
        warn!("overwriting existing file at {}", path.display());
    }

    let file = File::create(&path)?;
    let mut buf = BufWriter::new(file);

    let count = vars.len();

    for (variable, value) in vars {
        if value.contains('\n') {
            let value = value.replace("\n", "\\n");
            writeln!(buf, "{}=\"{}\"", variable, value)?;
        } else {
            writeln!(buf, "{}={}", variable, value)?;
        }
    }

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

    Ok(())
}

fn stringify_json_value(value: &serde_json::Value) -> Option<String> {
    if value.is_string() {
        return Some(value.as_str().unwrap().to_string());
    }

    if value.is_boolean() {
        return Some(value.as_bool().unwrap().to_string());
    }

    if value.is_null() {
        return Some("".to_string());
    }

    if value.is_f64() {
        return Some(value.as_f64().unwrap().to_string());
    }

    if value.is_i64() {
        return Some(value.as_i64().unwrap().to_string());
    }

    None
}

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

    #[test]
    fn stringify_json_value_converts_strings() {
        let json = json!("hello world");
        assert_eq!(stringify_json_value(&json), Some("hello world".to_string()));
    }

    #[test]
    fn stringify_json_value_converts_numbers() {
        let json = json!(42);
        assert_eq!(stringify_json_value(&json), Some("42".to_string()));

        let json = json!(-42);
        assert_eq!(stringify_json_value(&json), Some("-42".to_string()));

        let json = json!(4.2);
        assert_eq!(stringify_json_value(&json), Some("4.2".to_string()));
    }

    #[test]
    fn stringify_json_value_converts_null() {
        let json = json!(null);
        assert_eq!(stringify_json_value(&json["key"]), Some("".to_string()));
    }

    #[test]
    fn stringify_json_value_converts_booleans() {
        let json = json!(true);
        assert_eq!(stringify_json_value(&json), Some("true".to_string()));

        let json = json!(false);
        assert_eq!(stringify_json_value(&json), Some("false".to_string()));
    }

    #[test]
    fn stringify_json_value_does_not_convert_arrays_and_objects() {
        let json = json!({});
        assert_eq!(stringify_json_value(&json), None);

        let json = json!([]);
        assert_eq!(stringify_json_value(&json), None);
    }
}