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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
use std::path::{Path, PathBuf};
use std::fs::File;
use std::io::{stdin, BufRead, BufReader, Read, Write};
use serde_yaml;
use util::{strip_ext, write_at, FingerprintUserId, ResetCWD};
use error::{IOMode, VaultError};
use failure::{err_msg, Error, ResultExt};
use glob::glob;
use spec::WriteMode;
use gpgme;
use std::collections::HashSet;
use std::iter::once;
use std::fs::create_dir_all;
use std::str::FromStr;
use std::io;

pub const GPG_GLOB: &str = "**/*.gpg";
pub fn recipients_default() -> PathBuf {
    PathBuf::from(".gpg-id")
}

pub fn secrets_default() -> PathBuf {
    PathBuf::from(".")
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Clone, Hash)]
pub enum VaultKind {
    Leader,
    Partition,
}

impl Default for VaultKind {
    fn default() -> Self {
        VaultKind::Leader
    }
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Clone, Hash, Ord, PartialOrd)]
#[serde(rename_all = "kebab-case")]
pub enum TrustModel {
    GpgWebOfTrust,
    Always,
}

impl Default for TrustModel {
    fn default() -> Self {
        TrustModel::GpgWebOfTrust
    }
}

impl FromStr for TrustModel {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
        Ok(match s {
            "web-of-trust" => TrustModel::GpgWebOfTrust,
            "always" => TrustModel::Always,
            _ => return Err(format!("Unknown trust model: '{}'", s)),
        })
    }
}

#[derive(Deserialize, Serialize, Debug, PartialEq, Eq, Clone, Hash)]
pub struct Vault {
    pub name: Option<String>,
    #[serde(skip)]
    pub kind: VaultKind,
    #[serde(skip)]
    pub index: usize,
    #[serde(skip)]
    pub partitions: Vec<Vault>,
    #[serde(skip)]
    pub resolved_at: PathBuf,
    #[serde(skip)]
    pub vault_path: Option<PathBuf>,
    #[serde(default)]
    pub auto_import: Option<bool>,
    #[serde(default)]
    pub trust_model: Option<TrustModel>,
    #[serde(default = "secrets_default")]
    pub secrets: PathBuf,
    pub gpg_keys: Option<PathBuf>,
    #[serde(default = "recipients_default")]
    pub recipients: PathBuf,
}

impl Default for Vault {
    fn default() -> Self {
        Vault {
            kind: VaultKind::default(),
            index: 0,
            partitions: Default::default(),
            trust_model: Default::default(),
            auto_import: Some(true),
            vault_path: None,
            name: None,
            secrets: secrets_default(),
            resolved_at: secrets_default(),
            gpg_keys: None,
            recipients: recipients_default(),
        }
    }
}

impl Vault {
    pub fn from_file(path: &Path) -> Result<Vec<Vault>, Error> {
        let path_is_stdin = path == Path::new("-");
        let reader: Box<Read> = if path_is_stdin {
            Box::new(stdin())
        } else {
            if !path.exists() {
                if let Some(recipients_path) = path.parent().map(|p| p.join(recipients_default())) {
                    if recipients_path.is_file() {
                        let mut vault = Vault {
                            name: None,
                            kind: VaultKind::Leader,
                            index: 0,
                            partitions: Vec::new(),
                            resolved_at: path.to_owned(),
                            vault_path: None,
                            secrets: PathBuf::from("."),
                            gpg_keys: None,
                            recipients: recipients_default(),
                            auto_import: Some(false),
                            trust_model: Some(TrustModel::GpgWebOfTrust),
                        };
                        vault = vault.set_resolved_at(&recipients_path
                            .parent()
                            .expect("parent dir for recipient path which was joined before")
                            .join("sy-vault.yml"))?;
                        return Ok(vec![vault]);
                    }
                }
            }
            Box::new(File::open(path).map_err(|cause| VaultError::from_io_err(cause, path, &IOMode::Read))?)
        };
        let vaults: Vec<_> = split_documents(reader)?
            .iter()
            .enumerate()
            .map(|(index, s)| {
                serde_yaml::from_str(s)
                    .map_err(|cause| VaultError::Deserialization {
                        cause,
                        path: path.to_owned(),
                    })
                    .map_err(Into::into)
                    .and_then(|v: Vault| match v.set_resolved_at(path) {
                        Ok(mut v) => {
                            v.index = index;
                            Ok(v)
                        }
                        err => err,
                    })
            })
            .collect::<Result<_, _>>()?;
        if !vaults.is_empty() {
            vaults[0].validate()?;
        }
        Ok(vaults)
    }

    pub fn set_resolved_at(mut self, vault_file: &Path) -> Result<Self, Error> {
        self.resolved_at = normalize(vault_file
            .parent()
            .ok_or_else(|| format_err!("The vault file path '{}' is invalid.", vault_file.display()))?);
        self.vault_path = Some(vault_file.to_owned());
        Ok(self)
    }

    pub fn validate(&self) -> Result<(), Error> {
        if self.partitions.is_empty() {
            return Ok(());
        }
        {
            let all_secrets_paths: Vec<_> = self.partitions
                .iter()
                .map(|v| v.secrets_path())
                .chain(once(self.secrets_path()))
                .map(|mut p| {
                    if p.is_relative() {
                        p = Path::new(".").join(p);
                    }
                    p
                })
                .collect();
            for (sp, dp) in iproduct!(
                all_secrets_paths.iter().enumerate(),
                all_secrets_paths.iter().enumerate()
            ).filter_map(|((si, s), (di, d))| if si == di { None } else { Some((s, d)) })
            {
                if sp.starts_with(&dp) {
                    bail!(
                        "Partition at '{}' is contained in another partitions resources directory at '{}'",
                        sp.display(),
                        dp.display()
                    );
                }
            }
        }
        {
            let mut seen: HashSet<_> = Default::default();
            for path in self.partitions
                .iter()
                .map(|v| v.recipients_path())
                .chain(once(self.recipients_path()))
            {
                if seen.contains(&path) {
                    bail!(
                        "Recipients path '{}' is already used, but must be unique across all partitions",
                        path.display()
                    );
                }
                seen.insert(path);
            }
        }

        Ok(())
    }

    pub fn to_file(&self, path: &Path, mode: WriteMode) -> Result<(), VaultError> {
        if let WriteMode::RefuseOverwrite = mode {
            if path.exists() {
                return Err(VaultError::ConfigurationFileExists(path.to_owned()));
            }
        }
        self.validate().map_err(VaultError::Validation)?;

        match self.kind {
            VaultKind::Partition => return Err(VaultError::PartitionUnsupported),
            VaultKind::Leader => {
                let mut file = write_at(path).map_err(|cause| VaultError::from_io_err(cause, path, &IOMode::Write))?;
                let all_vaults = self.all_in_order();
                for vault in &all_vaults {
                    serde_yaml::to_writer(&mut file, vault)
                        .map_err(|cause| VaultError::Serialization {
                            cause,
                            path: path.to_owned(),
                        })
                        .and_then(|_| {
                            writeln!(file).map_err(|cause| VaultError::from_io_err(cause, path, &IOMode::Write))
                        })?;
                }
            }
        }
        Ok(())
    }

    pub fn absolute_path(&self, path: &Path) -> PathBuf {
        normalize(&self.resolved_at.join(path))
    }

    pub fn secrets_path(&self) -> PathBuf {
        normalize(&self.absolute_path(&self.secrets))
    }
    pub fn url(&self) -> String {
        format!(
            "syv://{}{}",
            self.name
                .as_ref()
                .map(|s| format!("{}@", s))
                .unwrap_or_else(String::new),
            self.secrets_path().display()
        )
    }

    pub fn print_resources(&self, w: &mut Write) -> Result<(), Error> {
        for partition in once(self).chain(self.partitions.iter()) {
            writeln!(w, "{}", partition.url())?;
            let dir = partition.secrets_path();
            if !dir.is_dir() {
                continue;
            }
            let _change_cwd = ResetCWD::new(&dir)?;
            for entry in glob(GPG_GLOB).expect("valid pattern").filter_map(Result::ok) {
                writeln!(w, "{}", strip_ext(&entry).display())?;
            }
        }
        Ok(())
    }

    pub fn write_recipients_list(&self, recipients: &mut Vec<String>) -> Result<PathBuf, Error> {
        recipients.sort();
        recipients.dedup();

        let recipients_path = self.recipients_path();
        if let Some(recipients_parent_dir) = recipients_path.parent() {
            if !recipients_parent_dir.is_dir() {
                create_dir_all(recipients_parent_dir).context(format!(
                    "Failed to create directory leading to recipients file at '{}'",
                    recipients_path.display()
                ))?;
            }
        }
        let mut writer = write_at(&recipients_path).context(format!(
            "Failed to open recipients at '{}' file for writing",
            recipients_path.display()
        ))?;
        for recipient in recipients {
            writeln!(&mut writer, "{}", recipient).context(format!(
                "Failed to write recipient '{}' to file at '{}'",
                recipient,
                recipients_path.display()
            ))?
        }
        Ok(recipients_path)
    }

    pub fn recipients_path(&self) -> PathBuf {
        self.absolute_path(&self.recipients)
    }

    pub fn recipients_list(&self) -> Result<Vec<String>, Error> {
        let recipients_file_path = self.recipients_path();
        let rfile = File::open(&recipients_file_path).map(BufReader::new).context(format!(
            "Could not open recipients file at '{}' for reading",
            recipients_file_path.display()
        ))?;
        Ok(rfile.lines().collect::<Result<_, _>>().context(format!(
            "Could not read all recipients from file at '{}'",
            recipients_file_path.display()
        ))?)
    }

    pub fn keys_by_ids(
        &self,
        ctx: &mut gpgme::Context,
        ids: &[String],
        type_of_ids_for_errors: &str,
        gpg_keys_dir: Option<&Path>,
        output: &mut io::Write,
    ) -> Result<Vec<gpgme::Key>, Error> {
        ctx.find_keys(ids)
            .context(format!("Could not iterate keys for given {}s", type_of_ids_for_errors))?;
        let (keys, missing): (Vec<gpgme::Key>, Vec<String>) = ids.iter().map(|id| (ctx.find_key(id), id)).fold(
            (Vec::new(), Vec::new()),
            |(mut keys, mut missing), (r, id)| {
                match r {
                    Ok(k) => keys.push(k),
                    Err(_) => missing.push(id.to_owned()),
                };
                (keys, missing)
            },
        );
        if keys.len() == ids.len() {
            assert_eq!(missing.len(), 0);
            return Ok(keys);
        }
        let diff: isize = ids.len() as isize - keys.len() as isize;
        let mut msg = vec![
            if diff > 0 {
                if let Some(dir) = gpg_keys_dir {
                    self.import_keys(ctx, dir, &missing, output)
                        .context("Could not auto-import all required keys")?;
                    return self.keys_by_ids(ctx, ids, type_of_ids_for_errors, None, output);
                }

                let mut msg = format!(
                    "Didn't find the key for {} {}(s) in the gpg database.{}",
                    diff,
                    type_of_ids_for_errors,
                    match self.gpg_keys.as_ref() {
                        Some(dir) => format!(
                            " This might mean it wasn't imported yet from the '{}' directory.",
                            self.absolute_path(dir).display()
                        ),
                        None => String::new(),
                    }
                );
                msg.push_str(&format!(
                    "\nThe following {}(s) could not be found in the gpg key database:",
                    type_of_ids_for_errors
                ));
                for fpr in missing {
                    msg.push_str("\n");
                    let key_path_info = match self.gpg_keys.as_ref() {
                        Some(dir) => {
                            let key_path = self.absolute_path(dir).join(&fpr);
                            format!(
                                "{}'{}'",
                                if key_path.is_file() {
                                    "Import key-file using 'gpg --import "
                                } else {
                                    "Key-file does not exist at "
                                },
                                key_path.display()
                            )
                        }
                        None => "No GPG keys directory".into(),
                    };
                    msg.push_str(&format!("{} ({})", &fpr, key_path_info));
                }
                msg
            } else {
                format!(
                    "Found {} additional keys to encrypt for, which may indicate an unusual \
                     {}s specification in the recipients file at '{}'",
                    diff,
                    type_of_ids_for_errors,
                    self.recipients_path().display()
                )
            },
        ];
        if !keys.is_empty() {
            msg.push(format!("All {}s found in gpg database:", type_of_ids_for_errors));
            msg.extend(keys.iter().map(|k| format!("{}", FingerprintUserId(k))));
        }
        Err(err_msg(msg.join("\n")))
    }

    pub fn recipient_keys(
        &self,
        ctx: &mut gpgme::Context,
        gpg_keys_dir: Option<&Path>,
        output: &mut io::Write,
    ) -> Result<Vec<gpgme::Key>, Error> {
        let recipients_fprs = self.recipients_list()?;
        if recipients_fprs.is_empty() {
            return Err(format_err!(
                "No recipients found in recipients file at '{}'.",
                self.recipients.display()
            ));
        }
        self.keys_by_ids(ctx, &recipients_fprs, "recipient", gpg_keys_dir, output)
    }

    fn vault_path_for_display(&self) -> String {
        self.vault_path
            .as_ref()
            .map(|p| p.to_string_lossy().into_owned())
            .unwrap_or_else(|| String::from("<unknown>"))
    }

    /// TODO: change this to be similar to `find_trust_model()`
    /// as it's OK to let partitions override the master vault settings
    pub fn find_gpg_keys_dir(&self) -> Result<PathBuf, Error> {
        once(self.gpg_keys_dir())
            .chain(self.partitions.iter().map(|p| p.gpg_keys_dir()))
            .filter_map(Result::ok)
            .next()
            .ok_or_else(|| {
                format_err!(
                    "The vault at '{}' does not have a gpg_keys directory configured.",
                    self.vault_path_for_display()
                )
            })
    }

    pub fn gpg_keys_dir_for_auto_import(&self, partition: &Vault) -> Option<PathBuf> {
        let auto_import = partition
            .auto_import
            .clone()
            .or(self.auto_import.clone())
            .unwrap_or(false);
        if auto_import {
            self.find_gpg_keys_dir().ok()
        } else {
            None
        }
    }

    pub fn gpg_keys_dir(&self) -> Result<PathBuf, Error> {
        self.gpg_keys.as_ref().map(|p| self.absolute_path(p)).ok_or_else(|| {
            format_err!(
                "The vault at '{}' does not have a gpg_keys directory configured.",
                self.vault_path_for_display()
            )
        })
    }
}

pub trait VaultExt {
    fn select(self, vault_id: &str) -> Result<Vault, Error>;
}

impl VaultExt for Vec<Vault> {
    fn select(mut self, selector: &str) -> Result<Vault, Error> {
        let leader_index = Vault::partition_index(selector, self.iter(), None)?;
        for (_, vault) in self.iter_mut().enumerate().filter(|&(vid, _)| vid != leader_index) {
            vault.kind = VaultKind::Partition;
        }

        let mut vault = self[leader_index].clone();
        vault.kind = VaultKind::Leader;

        self.retain(|v| match v.kind {
            VaultKind::Partition => true,
            VaultKind::Leader => false,
        });

        vault.partitions = self;
        Ok(vault)
    }
}

fn normalize(p: &Path) -> PathBuf {
    use std::path::Component;
    let mut p = p.components().fold(PathBuf::new(), |mut p, c| {
        match c {
            Component::CurDir => {}
            _ => p.push(c.as_os_str()),
        }
        p
    });
    if p.components().count() == 0 {
        p = PathBuf::from(".");
    }
    p
}

fn split_documents<R: Read>(mut r: R) -> Result<Vec<String>, Error> {
    use yaml_rust::{YamlEmitter, YamlLoader};

    let mut buf = String::new();
    r.read_to_string(&mut buf)?;

    let docs = YamlLoader::load_from_str(&buf).context("YAML deserialization failed")?;
    Ok(docs.iter()
        .map(|d| {
            let mut out_str = String::new();
            {
                let mut emitter = YamlEmitter::new(&mut out_str);
                emitter.dump(d).expect("dumping a valid yaml into a string to work");
            }
            out_str
        })
        .collect())
}

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

    #[test]
    fn it_selects_by_name() {
        let vault = Vault {
            name: Some("foo".into()),
            ..Default::default()
        };
        let v = vec![vault.clone()];
        assert_eq!(v.select("foo").unwrap(), vault)
    }

    #[test]
    fn it_selects_by_secrets_dir() {
        let vault = Vault {
            secrets: PathBuf::from("../dir"),
            ..Default::default()
        };
        let v = vec![vault.clone()];
        assert_eq!(v.select("../dir").unwrap(), vault)
    }

    #[test]
    fn it_selects_by_index() {
        let v = vec![Vault::default()];
        assert!(v.select("0").is_ok())
    }

    #[test]
    fn it_errors_if_name_is_unknown() {
        let v = Vec::<Vault>::new();
        assert_eq!(
            format!("{}", v.select("foo").unwrap_err()),
            "No partition matched the given selector 'foo'"
        )
    }
    #[test]
    fn it_errors_if_index_is_out_of_bounds() {
        let v = Vec::<Vault>::new();
        assert_eq!(
            format!("{}", v.select("0").unwrap_err()),
            "Could not find partition with index 0"
        )
    }
}

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

    #[test]
    fn it_will_always_remove_current_dirs_including_the_first_one() {
        assert_eq!(format!("{}", normalize(Path::new("./././a")).display()), "a")
    }
    #[test]
    fn it_does_not_alter_parent_dirs() {
        assert_eq!(format!("{}", normalize(Path::new("./../.././a")).display()), "../../a")
    }
}

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

    #[test]
    fn it_print_the_name_in_the_url_if_there_is_none() {
        let mut v = Vault::default();
        v.name = Some("name".into());
        assert_eq!(v.url(), "syv://name@.")
    }

    #[test]
    fn it_does_not_print_the_name_in_the_url_if_there_is_none() {
        let v = Vault::default();
        assert_eq!(v.url(), "syv://.")
    }
}