Skip to main content

wal_backup/storage/
encrypted.rs

1use aes_gcm::aead::{Aead, KeyInit, OsRng};
2use aes_gcm::{AeadCore, Aes256Gcm, Nonce};
3use async_trait::async_trait;
4use bytes::Bytes;
5use std::collections::HashMap;
6use std::path::PathBuf;
7use std::sync::{Arc, RwLock};
8
9use crate::error::{Error, Result};
10use crate::storage::BucketStore;
11
12const CURRENT_VERSION: u8 = 1;
13const MAGIC: &[u8; 4] = b"ENCR";
14const MAGIC_SIZE: usize = 4;
15const NONCE_SIZE: usize = 12;
16const VERSION_SIZE: usize = 1;
17
18/// Key entry stored for decryption with past key versions.
19/// Aes256Gcm uses the aes crate internally, which implements ZeroizeOnDrop
20/// on its key schedule types — the cipher field zeroizes on drop.
21struct KeyEntry {
22    cipher: Aes256Gcm,
23}
24
25pub struct EncryptedBucketStore {
26    inner: Arc<dyn BucketStore>,
27    current_key: [u8; 32],
28    version: u8,
29    past_keys: Arc<RwLock<HashMap<u8, KeyEntry>>>,
30}
31
32impl EncryptedBucketStore {
33    pub fn new(inner: Arc<dyn BucketStore>, key: &[u8; 32]) -> Self {
34        EncryptedBucketStore {
35            inner,
36            current_key: *key,
37            version: CURRENT_VERSION,
38            past_keys: Arc::new(RwLock::new(HashMap::new())),
39        }
40    }
41
42    pub fn with_version(mut self, version: u8) -> Self {
43        self.version = version;
44        self
45    }
46
47    pub fn add_past_key(&self, version: u8, key: &[u8; 32]) -> Result<()> {
48        let cipher = Aes256Gcm::new_from_slice(key)
49            .map_err(|_| Error::Other("invalid AES-256-GCM key length for past key".into()))?;
50        let mut keys = self
51            .past_keys
52            .write()
53            .map_err(|_| Error::Other("poisoned past_keys lock".into()))?;
54        keys.insert(version, KeyEntry { cipher });
55        Ok(())
56    }
57
58    fn encrypt_with(&self, key_version: u8, plaintext: &[u8]) -> Result<Vec<u8>> {
59        if key_version != self.version {
60            return Err(Error::Other(format!(
61                "cannot encrypt with key version {} (current is {})",
62                key_version, self.version
63            )));
64        }
65
66        let cipher = Aes256Gcm::new_from_slice(&self.current_key)
67            .map_err(|_| Error::Other("invalid AES-256-GCM key length".into()))?;
68        let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
69        let ciphertext = cipher
70            .encrypt(&nonce, plaintext)
71            .map_err(|e| Error::Other(format!("AES encrypt: {e}")))?;
72
73        let mut out = Vec::with_capacity(MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE + ciphertext.len());
74        out.extend_from_slice(MAGIC);
75        out.push(key_version);
76        out.extend_from_slice(&nonce);
77        out.extend_from_slice(&ciphertext);
78        Ok(out)
79    }
80
81    fn decrypt_outer(&self, data: &[u8]) -> Result<Vec<u8>> {
82        let header_size = MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE;
83        if data.len() < header_size + 16 {
84            return Err(Error::Other("encrypted data too short".into()));
85        }
86        if &data[..MAGIC_SIZE] != MAGIC {
87            return Err(Error::Other(
88                "data is not encrypted (missing ENCR magic)".into(),
89            ));
90        }
91        let key_version = data[MAGIC_SIZE];
92        let nonce = Nonce::from_slice(
93            &data[MAGIC_SIZE + VERSION_SIZE..MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE],
94        );
95        let ciphertext = &data[MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE..];
96        if key_version == self.version {
97            let cipher = Aes256Gcm::new_from_slice(&self.current_key)
98                .map_err(|_| Error::Other("invalid AES-256-GCM key length".into()))?;
99            cipher
100                .decrypt(nonce, ciphertext)
101                .map_err(|e| Error::Other(format!("AES decrypt: {e}")))
102        } else {
103            let keys = self
104                .past_keys
105                .read()
106                .map_err(|_| Error::Other("poisoned past_keys lock".into()))?;
107            if let Some(entry) = keys.get(&key_version) {
108                entry
109                    .cipher
110                    .decrypt(nonce, ciphertext)
111                    .map_err(|e| Error::Other(format!("AES decrypt: {e}")))
112            } else {
113                Err(Error::Other(format!(
114                    "unknown key version {} (current is {})",
115                    key_version, self.version
116                )))
117            }
118        }
119    }
120}
121
122#[async_trait]
123impl BucketStore for EncryptedBucketStore {
124    fn prefix(&self) -> &str {
125        self.inner.prefix()
126    }
127    fn writer_id(&self) -> &str {
128        self.inner.writer_id()
129    }
130
131    async fn put(&self, key: &str, data: Bytes) -> Result<()> {
132        let encrypted = self.encrypt_with(self.version, &data)?;
133        self.inner.put(key, Bytes::from(encrypted)).await
134    }
135
136    async fn get(&self, key: &str) -> Result<Option<Bytes>> {
137        self.get_with_etag(key).await.map(|opt| opt.map(|(b, _)| b))
138    }
139
140    async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf> {
141        // Step 1: Download encrypted blob to a temp file to avoid loading it
142        // into RAM as a Bytes value (which would duplicate the allocation).
143        let encrypted_tmp = dest.with_extension("encrypted-tmp");
144        self.inner.get_file(key, &encrypted_tmp).await?;
145
146        // Step 2: Read encrypted file from disk and decrypt in a spawn_blocking
147        // task to avoid blocking the async thread. We pass the key explicitly so
148        // the closure can drop it before returning (zeroize-on-drop pattern).
149        let encrypted_tmp_owned = encrypted_tmp.clone();
150        let dest_owned = dest.to_path_buf();
151        let key_bytes = self.current_key;
152        let version = self.version;
153
154        // Clone past_keys so the blocking task has its own Arc reference
155        let past_keys = Arc::clone(&self.past_keys);
156
157        let result = tokio::task::spawn_blocking(move || -> Result<PathBuf> {
158            // Read encrypted data from disk (avoiding any further I/O on the
159            // async thread). AES-GCM decryption does NOT require spawning another
160            // thread — it is CPU-bound and fast enough for inline execution.
161            use std::io::{Read, Write};
162
163            let mut encrypted_file =
164                std::fs::File::open(&encrypted_tmp_owned).map_err(|e| {
165                    crate::error::Error::Other(format!("open encrypted temp file: {e}"))
166                })?;
167
168            let mut encrypted_data = Vec::new();
169            let mut chunk_buf = [0u8; 262144];
170            loop {
171                let n = encrypted_file.read(&mut chunk_buf).map_err(|e| {
172                    crate::error::Error::Other(format!("read encrypted temp file: {e}"))
173                })?;
174                if n == 0 {
175                    break;
176                }
177                encrypted_data.extend_from_slice(&chunk_buf[..n]);
178            }
179            drop(encrypted_file);
180
181            // --- Decrypt with current or past key --------------------------------
182            let plaintext = decrypt_from_bytes(
183                &encrypted_data,
184                key_bytes,
185                version,
186                past_keys,
187            )?;
188            drop(encrypted_data);
189
190            // --- Write decrypted plaintext in chunks ----------------------------
191            let mut file = std::fs::File::create(&dest_owned).map_err(|e| {
192                crate::error::Error::Other(format!("create decrypted file: {e}"))
193            })?;
194            for chunk in plaintext.chunks(262144) {
195                file.write_all(chunk).map_err(|e| {
196                    crate::error::Error::Other(format!("write decrypted file: {e}"))
197                })?;
198            }
199            file.flush().map_err(|e| {
200                crate::error::Error::Other(format!("flush decrypted file: {e}"))
201            })?;
202            file.sync_all().map_err(|e| {
203                crate::error::Error::Other(format!("sync decrypted file: {e}"))
204            })?;
205            drop(file);
206
207            std::fs::rename(&dest_owned, &dest_owned).map_err(|e| {
208                crate::error::Error::Other(format!("rename decrypted file: {e}"))
209            })?;
210            Ok(dest_owned)
211        })
212        .await?;
213
214        // Step 3: Clean up the encrypted temp file
215        let _ = tokio::fs::remove_file(&encrypted_tmp).await;
216        result
217    }
218
219    async fn get_with_etag(&self, key: &str) -> Result<Option<(Bytes, String)>> {
220        match self.inner.get_with_etag(key).await? {
221            Some((data, etag)) => {
222                let decrypted = self.decrypt_outer(&data)?;
223                Ok(Some((Bytes::from(decrypted), etag)))
224            }
225            None => Ok(None),
226        }
227    }
228
229    async fn list(&self, prefix: &str) -> Result<Vec<String>> {
230        self.inner.list(prefix).await
231    }
232
233    async fn delete(&self, key: &str) -> Result<()> {
234        self.inner.delete(key).await
235    }
236
237    async fn exists(&self, key: &str) -> Result<bool> {
238        self.inner.exists(key).await
239    }
240
241    async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<()> {
242        // Encrypt to a temp file (NamedTempFile for random, unpredictable path).
243        // Then upload the encrypted temp file through the inner store's streaming
244        // put_file. NamedTempFile auto-deletes on drop (RAII).
245        let tmp_file = tempfile::NamedTempFile::new()
246            .map_err(|e| crate::error::Error::Other(format!("create temp file: {e}")))?;
247        let tmp_path = tmp_file.path().to_path_buf();
248
249        tokio::task::spawn_blocking({
250            let tmp_path = tmp_path.clone();
251            let path = path.to_path_buf();
252            let version = self.version;
253            let current_key = self.current_key;
254            move || -> Result<()> {
255                let mut current_key = current_key;
256                let data = std::fs::read(&path).map_err(|e| {
257                    crate::error::Error::Other(format!("failed to read file for encryption: {e}"))
258                })?;
259                let cipher = Aes256Gcm::new_from_slice(&current_key).map_err(|_| {
260                    crate::error::Error::Other("invalid AES-256-GCM key length".into())
261                })?;
262                let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
263                let ciphertext = cipher
264                    .encrypt(&nonce, &data[..])
265                    .map_err(|e| crate::error::Error::Other(format!("AES encrypt: {e}")))?;
266                drop(data);
267                let mut out =
268                    Vec::with_capacity(MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE + ciphertext.len());
269                out.extend_from_slice(MAGIC);
270                out.push(version);
271                out.extend_from_slice(&nonce);
272                out.extend_from_slice(&ciphertext);
273                drop(ciphertext);
274                std::fs::write(&tmp_path, &out).map_err(|e| {
275                    crate::error::Error::Other(format!("failed to write encrypted temp file: {e}"))
276                })?;
277                use zeroize::Zeroize;
278                current_key.zeroize();
279                drop(cipher);
280                Ok(())
281            }
282        })
283        .await??;
284
285        let result = self.inner.put_file(key, &tmp_path).await;
286        drop(tmp_file);
287        result
288    }
289
290    async fn put_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<()> {
291        let encrypted = self.encrypt_with(self.version, &data)?;
292        self.inner
293            .put_if_match(key, Bytes::from(encrypted), etag)
294            .await
295    }
296
297    async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<()> {
298        let encrypted = self.encrypt_with(self.version, &data)?;
299        self.inner
300            .put_if_not_exists(key, Bytes::from(encrypted))
301            .await
302    }
303}
304
305/// Decrypt encrypted data using either the current key or a past key version.
306/// Called from a `spawn_blocking` task so the key material stays off the async
307/// stack and is dropped before the thread returns to the pool.
308fn decrypt_from_bytes(
309    encrypted_data: &[u8],
310    current_key: [u8; 32],
311    current_version: u8,
312    past_keys: Arc<RwLock<HashMap<u8, KeyEntry>>>,
313) -> Result<Vec<u8>> {
314    let header_size = MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE;
315    if encrypted_data.len() < header_size + 16 {
316        return Err(Error::Other("encrypted data too short".into()));
317    }
318    if &encrypted_data[..MAGIC_SIZE] != MAGIC {
319        return Err(Error::Other(
320            "data is not encrypted (missing ENCR magic)".into(),
321        ));
322    }
323    let key_version = encrypted_data[MAGIC_SIZE];
324    let nonce = Nonce::from_slice(
325        &encrypted_data[MAGIC_SIZE + VERSION_SIZE..MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE],
326    );
327    let ciphertext = &encrypted_data[MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE..];
328
329    if key_version == current_version {
330        let mut key = current_key;
331        let cipher = Aes256Gcm::new_from_slice(&key)
332            .map_err(|_| Error::Other("invalid AES-256-GCM key length".into()))?;
333        let result = cipher
334            .decrypt(nonce, ciphertext)
335            .map_err(|e| Error::Other(format!("AES decrypt: {e}")));
336        // Zeroize the key copy immediately after use
337        use zeroize::Zeroize;
338        key.zeroize();
339        result
340    } else {
341        let keys = past_keys.read().map_err(|_| {
342            Error::Other("poisoned past_keys lock in spawn_blocking".into())
343        })?;
344        if let Some(entry) = keys.get(&key_version) {
345            entry
346                .cipher
347                .decrypt(nonce, ciphertext)
348                .map_err(|e| Error::Other(format!("AES decrypt: {e}")))
349        } else {
350            Err(Error::Other(format!(
351                "unknown key version {} (current is {})",
352                key_version, current_version
353            )))
354        }
355    }
356}
357
358impl Drop for EncryptedBucketStore {
359    fn drop(&mut self) {
360        use zeroize::Zeroize;
361        self.current_key.zeroize();
362        if let Ok(mut keys) = self.past_keys.write() {
363            keys.clear();
364        }
365    }
366}