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
use crate::atoms::Outcome;

use super::super::Atom;
use super::FileAtom;
use age::armor::ArmoredReader;
use age::secrecy::Secret;
use std::io::Read;
use std::path::PathBuf;
use tracing::error;

pub struct Decrypt {
    pub encrypted_content: Vec<u8>,
    pub passphrase: String,
    pub path: PathBuf,
}

impl FileAtom for Decrypt {
    fn get_path(&self) -> &PathBuf {
        &self.path
    }
}

impl std::fmt::Display for Decrypt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "The content needs to be decrypted to {}",
            self.path.as_path().display()
        )
    }
}

impl Atom for Decrypt {
    fn plan(&self) -> anyhow::Result<Outcome> {
        // If the file doesn't exist, assume it's because
        // another atom is going to provide it.
        if !self.path.exists() {
            return Ok(Outcome {
                side_effects: vec![],
                should_run: true,
            });
        }

        // Decrypting file with provided passphrase makes plan work
        match decrypt(&self.passphrase, &self.encrypted_content) {
            Ok(_) => Ok(Outcome {
                side_effects: vec![],
                should_run: true,
            }),
            Err(err) => {
                error!(
                    "Cannot decrypt file {} because {:?}. Skipping.",
                    self.path.display(),
                    err
                );

                Ok(Outcome {
                    side_effects: vec![],
                    should_run: false,
                })
            }
        }
    }

    fn execute(&mut self) -> anyhow::Result<()> {
        let decrypted_content = decrypt(&self.passphrase, &self.encrypted_content)?;

        std::fs::write(&self.path, decrypted_content)?;

        Ok(())
    }
}

fn decrypt(passphrase: &str, encrypted_content: &[u8]) -> anyhow::Result<Vec<u8>> {
    let decryptor = match age::Decryptor::new(ArmoredReader::new(encrypted_content))? {
        age::Decryptor::Passphrase(d) => Ok(d),
        _ => Err(anyhow::anyhow!("Cannot create passphrase decryptor!")),
    }?;

    let mut decrypted = vec![];
    let secret = Secret::new(passphrase.to_owned());
    let mut reader = decryptor.decrypt(&secret, None)?;
    reader.read_to_end(&mut decrypted)?;

    Ok(decrypted)
}

#[cfg(test)]
mod tests {
    use tempfile::NamedTempFile;

    use super::*;
    use pretty_assertions::assert_eq;
    use std::io::Write;

    #[test]
    fn it_can_plan() -> anyhow::Result<()> {
        // encrypt and write to file
        let passphrase = "Teal'c".to_string();
        let content = b"Shol'va";
        let encrypted_content = encrypt(passphrase.to_owned(), content.to_vec())?;

        // prepare atom
        let mut file = NamedTempFile::new()?;
        file.reopen()?;
        file.write_all(&encrypted_content)?;

        let decrypt = Decrypt {
            encrypted_content: encrypted_content.to_owned(),
            path: file.path().to_path_buf(),
            passphrase,
        };

        // plan
        assert_eq!(true, decrypt.plan().unwrap().should_run);

        // prepare another atom
        let another_decrypt = Decrypt {
            encrypted_content: encrypted_content.to_owned(),
            path: file.path().to_path_buf(),
            passphrase: "fkbr".to_string(),
        };

        // plan
        assert_eq!(false, another_decrypt.plan().unwrap().should_run);

        Ok(())
    }

    #[test]
    fn it_can_execute() -> anyhow::Result<()> {
        // encrypt and write to file
        let passphrase = "Teal'c".to_string();
        let content = b"Shol'va";
        let encrypted_content = encrypt(passphrase.to_owned(), content.to_vec())?;

        // prepare atom
        let mut file = NamedTempFile::new()?;
        file.reopen()?;
        file.write_all(&encrypted_content)?;

        let mut decrypt = Decrypt {
            encrypted_content: encrypted_content.to_owned(),
            path: file.path().to_path_buf(),
            passphrase,
        };

        // plan, execute
        assert_eq!(true, decrypt.plan().unwrap().should_run);
        assert_eq!(true, decrypt.execute().is_ok());

        Ok(())
    }

    fn encrypt(passphrase: String, content: Vec<u8>) -> anyhow::Result<Vec<u8>> {
        let secret = Secret::new(passphrase);
        let encryptor = age::Encryptor::with_user_passphrase(secret);

        let mut encrypted = vec![];
        let mut writer = encryptor.wrap_output(&mut encrypted)?;
        writer.write_all(&content)?;
        writer.finish()?;

        Ok(encrypted)
    }
}