nethsm_cli/
passphrase_file.rs

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
use std::{
    fs::read_to_string,
    path::{Path, PathBuf},
    str::FromStr,
};

use nethsm::Passphrase;

/// A passphrase file error
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// An I/O error
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    /// Path creation error
    #[error("Path error: {0}")]
    Path(#[from] core::convert::Infallible),
}

/// A representation of a file containing a passphrase
#[derive(Clone, Debug)]
pub struct PassphraseFile {
    pub passphrase: Passphrase,
}

impl PassphraseFile {
    pub fn new(path: &Path) -> Result<Self, Error> {
        Ok(Self {
            passphrase: Passphrase::new(read_to_string(path)?),
        })
    }
}

impl FromStr for PassphraseFile {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        PassphraseFile::new(&PathBuf::from_str(s)?)
    }
}

#[cfg(test)]
mod tests {
    use std::fs::File;
    use std::io::Write;

    use rand::{thread_rng, Rng};
    use rstest::rstest;
    use testdir::testdir;
    use testresult::TestResult;

    use super::*;

    #[rstest]
    fn passphrase_file() -> TestResult {
        let mut i = 0;
        while i < 20 {
            let mut rng = thread_rng();
            let lines = rng.gen_range(0..20);
            let lines_vec = (0..lines)
                .map(|_x| "this is a passphrase".to_string())
                .collect::<Vec<String>>();
            let path = testdir!().join(format!("passphrase_file_lines_{}.txt", lines));
            let mut file = File::create(&path)?;
            file.write_all(lines_vec.join("\n").as_bytes())?;

            let passphrase_file = PassphraseFile::new(&path);
            assert!(passphrase_file.is_ok());
            i += 1;
        }

        Ok(())
    }
}