wal-backup 0.8.11

Embedded SQLite WAL replication to S3-compatible object storage. Not a sidecar — a library. Like Litestream, but embedded.
Documentation
use aes_gcm::aead::{Aead, KeyInit, OsRng};
use aes_gcm::{AeadCore, Aes256Gcm, Nonce};
use async_trait::async_trait;
use bytes::Bytes;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};

use crate::error::{Error, Result};
use crate::storage::BucketStore;

const CURRENT_VERSION: u8 = 1;
const MAGIC: &[u8; 4] = b"ENCR";
const MAGIC_SIZE: usize = 4;
const NONCE_SIZE: usize = 12;
const VERSION_SIZE: usize = 1;

/// Key entry stored for decryption with past key versions.
/// Aes256Gcm uses the aes crate internally, which implements ZeroizeOnDrop
/// on its key schedule types — the cipher field zeroizes on drop.
struct KeyEntry {
    cipher: Aes256Gcm,
}

pub struct EncryptedBucketStore {
    inner: Arc<dyn BucketStore>,
    current_key: [u8; 32],
    version: u8,
    past_keys: Arc<RwLock<HashMap<u8, KeyEntry>>>,
}

impl EncryptedBucketStore {
    pub fn new(inner: Arc<dyn BucketStore>, key: &[u8; 32]) -> Self {
        EncryptedBucketStore {
            inner,
            current_key: *key,
            version: CURRENT_VERSION,
            past_keys: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    pub fn with_version(mut self, version: u8) -> Self {
        self.version = version;
        self
    }

    pub fn add_past_key(&self, version: u8, key: &[u8; 32]) -> Result<()> {
        let cipher = Aes256Gcm::new_from_slice(key)
            .map_err(|_| Error::Other("invalid AES-256-GCM key length for past key".into()))?;
        let mut keys = self
            .past_keys
            .write()
            .map_err(|_| Error::Other("poisoned past_keys lock".into()))?;
        keys.insert(version, KeyEntry { cipher });
        Ok(())
    }

    fn encrypt_with(&self, key_version: u8, plaintext: &[u8]) -> Result<Vec<u8>> {
        if key_version != self.version {
            return Err(Error::Other(format!(
                "cannot encrypt with key version {} (current is {})",
                key_version, self.version
            )));
        }

        let cipher = Aes256Gcm::new_from_slice(&self.current_key)
            .map_err(|_| Error::Other("invalid AES-256-GCM key length".into()))?;
        let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
        let ciphertext = cipher
            .encrypt(&nonce, plaintext)
            .map_err(|e| Error::Other(format!("AES encrypt: {e}")))?;

        let mut out = Vec::with_capacity(MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE + ciphertext.len());
        out.extend_from_slice(MAGIC);
        out.push(key_version);
        out.extend_from_slice(&nonce);
        out.extend_from_slice(&ciphertext);
        Ok(out)
    }

    fn decrypt_outer(&self, data: &[u8]) -> Result<Vec<u8>> {
        let header_size = MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE;
        if data.len() < header_size + 16 {
            return Err(Error::Other("encrypted data too short".into()));
        }
        if &data[..MAGIC_SIZE] != MAGIC {
            return Err(Error::Other(
                "data is not encrypted (missing ENCR magic)".into(),
            ));
        }
        let key_version = data[MAGIC_SIZE];
        let nonce = Nonce::from_slice(
            &data[MAGIC_SIZE + VERSION_SIZE..MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE],
        );
        let ciphertext = &data[MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE..];
        if key_version == self.version {
            let cipher = Aes256Gcm::new_from_slice(&self.current_key)
                .map_err(|_| Error::Other("invalid AES-256-GCM key length".into()))?;
            cipher
                .decrypt(nonce, ciphertext)
                .map_err(|e| Error::Other(format!("AES decrypt: {e}")))
        } else {
            let keys = self
                .past_keys
                .read()
                .map_err(|_| Error::Other("poisoned past_keys lock".into()))?;
            if let Some(entry) = keys.get(&key_version) {
                entry
                    .cipher
                    .decrypt(nonce, ciphertext)
                    .map_err(|e| Error::Other(format!("AES decrypt: {e}")))
            } else {
                Err(Error::Other(format!(
                    "unknown key version {} (current is {})",
                    key_version, self.version
                )))
            }
        }
    }
}

#[async_trait]
impl BucketStore for EncryptedBucketStore {
    fn prefix(&self) -> &str {
        self.inner.prefix()
    }
    fn writer_id(&self) -> &str {
        self.inner.writer_id()
    }

    async fn put(&self, key: &str, data: Bytes) -> Result<()> {
        let encrypted = self.encrypt_with(self.version, &data)?;
        self.inner.put(key, Bytes::from(encrypted)).await
    }

    async fn get(&self, key: &str) -> Result<Option<Bytes>> {
        self.get_with_etag(key).await.map(|opt| opt.map(|(b, _)| b))
    }

    async fn get_file(&self, key: &str, dest: &std::path::Path) -> Result<PathBuf> {
        // Step 1: Download encrypted blob to a temp file to avoid loading it
        // into RAM as a Bytes value (which would duplicate the allocation).
        let encrypted_tmp = dest.with_extension("encrypted-tmp");
        self.inner.get_file(key, &encrypted_tmp).await?;

        // Step 2: Read encrypted file from disk and decrypt in a spawn_blocking
        // task to avoid blocking the async thread. We pass the key explicitly so
        // the closure can drop it before returning (zeroize-on-drop pattern).
        let encrypted_tmp_owned = encrypted_tmp.clone();
        let dest_owned = dest.to_path_buf();
        let key_bytes = self.current_key;
        let version = self.version;

        // Clone past_keys so the blocking task has its own Arc reference
        let past_keys = Arc::clone(&self.past_keys);

        let result = tokio::task::spawn_blocking(move || -> Result<PathBuf> {
            // Read encrypted data from disk (avoiding any further I/O on the
            // async thread). AES-GCM decryption does NOT require spawning another
            // thread — it is CPU-bound and fast enough for inline execution.
            use std::io::{Read, Write};

            let mut encrypted_file =
                std::fs::File::open(&encrypted_tmp_owned).map_err(|e| {
                    crate::error::Error::Other(format!("open encrypted temp file: {e}"))
                })?;

            let mut encrypted_data = Vec::new();
            let mut chunk_buf = [0u8; 262144];
            loop {
                let n = encrypted_file.read(&mut chunk_buf).map_err(|e| {
                    crate::error::Error::Other(format!("read encrypted temp file: {e}"))
                })?;
                if n == 0 {
                    break;
                }
                encrypted_data.extend_from_slice(&chunk_buf[..n]);
            }
            drop(encrypted_file);

            // --- Decrypt with current or past key --------------------------------
            let plaintext = decrypt_from_bytes(
                &encrypted_data,
                key_bytes,
                version,
                past_keys,
            )?;
            drop(encrypted_data);

            // --- Write decrypted plaintext in chunks ----------------------------
            let mut file = std::fs::File::create(&dest_owned).map_err(|e| {
                crate::error::Error::Other(format!("create decrypted file: {e}"))
            })?;
            for chunk in plaintext.chunks(262144) {
                file.write_all(chunk).map_err(|e| {
                    crate::error::Error::Other(format!("write decrypted file: {e}"))
                })?;
            }
            file.flush().map_err(|e| {
                crate::error::Error::Other(format!("flush decrypted file: {e}"))
            })?;
            file.sync_all().map_err(|e| {
                crate::error::Error::Other(format!("sync decrypted file: {e}"))
            })?;
            drop(file);

            std::fs::rename(&dest_owned, &dest_owned).map_err(|e| {
                crate::error::Error::Other(format!("rename decrypted file: {e}"))
            })?;
            Ok(dest_owned)
        })
        .await?;

        // Step 3: Clean up the encrypted temp file
        let _ = tokio::fs::remove_file(&encrypted_tmp).await;
        result
    }

    async fn get_with_etag(&self, key: &str) -> Result<Option<(Bytes, String)>> {
        match self.inner.get_with_etag(key).await? {
            Some((data, etag)) => {
                let decrypted = self.decrypt_outer(&data)?;
                Ok(Some((Bytes::from(decrypted), etag)))
            }
            None => Ok(None),
        }
    }

    async fn list(&self, prefix: &str) -> Result<Vec<String>> {
        self.inner.list(prefix).await
    }

    async fn delete(&self, key: &str) -> Result<()> {
        self.inner.delete(key).await
    }

    async fn exists(&self, key: &str) -> Result<bool> {
        self.inner.exists(key).await
    }

    async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<()> {
        // Encrypt to a temp file (NamedTempFile for random, unpredictable path).
        // Then upload the encrypted temp file through the inner store's streaming
        // put_file. NamedTempFile auto-deletes on drop (RAII).
        let tmp_file = tempfile::NamedTempFile::new()
            .map_err(|e| crate::error::Error::Other(format!("create temp file: {e}")))?;
        let tmp_path = tmp_file.path().to_path_buf();

        tokio::task::spawn_blocking({
            let tmp_path = tmp_path.clone();
            let path = path.to_path_buf();
            let version = self.version;
            let current_key = self.current_key;
            move || -> Result<()> {
                let mut current_key = current_key;
                let data = std::fs::read(&path).map_err(|e| {
                    crate::error::Error::Other(format!("failed to read file for encryption: {e}"))
                })?;
                let cipher = Aes256Gcm::new_from_slice(&current_key).map_err(|_| {
                    crate::error::Error::Other("invalid AES-256-GCM key length".into())
                })?;
                let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
                let ciphertext = cipher
                    .encrypt(&nonce, &data[..])
                    .map_err(|e| crate::error::Error::Other(format!("AES encrypt: {e}")))?;
                drop(data);
                let mut out =
                    Vec::with_capacity(MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE + ciphertext.len());
                out.extend_from_slice(MAGIC);
                out.push(version);
                out.extend_from_slice(&nonce);
                out.extend_from_slice(&ciphertext);
                drop(ciphertext);
                std::fs::write(&tmp_path, &out).map_err(|e| {
                    crate::error::Error::Other(format!("failed to write encrypted temp file: {e}"))
                })?;
                use zeroize::Zeroize;
                current_key.zeroize();
                drop(cipher);
                Ok(())
            }
        })
        .await??;

        let result = self.inner.put_file(key, &tmp_path).await;
        drop(tmp_file);
        result
    }

    async fn put_if_match(&self, key: &str, data: Bytes, etag: &str) -> Result<()> {
        let encrypted = self.encrypt_with(self.version, &data)?;
        self.inner
            .put_if_match(key, Bytes::from(encrypted), etag)
            .await
    }

    async fn put_if_not_exists(&self, key: &str, data: Bytes) -> Result<()> {
        let encrypted = self.encrypt_with(self.version, &data)?;
        self.inner
            .put_if_not_exists(key, Bytes::from(encrypted))
            .await
    }
}

/// Decrypt encrypted data using either the current key or a past key version.
/// Called from a `spawn_blocking` task so the key material stays off the async
/// stack and is dropped before the thread returns to the pool.
fn decrypt_from_bytes(
    encrypted_data: &[u8],
    current_key: [u8; 32],
    current_version: u8,
    past_keys: Arc<RwLock<HashMap<u8, KeyEntry>>>,
) -> Result<Vec<u8>> {
    let header_size = MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE;
    if encrypted_data.len() < header_size + 16 {
        return Err(Error::Other("encrypted data too short".into()));
    }
    if &encrypted_data[..MAGIC_SIZE] != MAGIC {
        return Err(Error::Other(
            "data is not encrypted (missing ENCR magic)".into(),
        ));
    }
    let key_version = encrypted_data[MAGIC_SIZE];
    let nonce = Nonce::from_slice(
        &encrypted_data[MAGIC_SIZE + VERSION_SIZE..MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE],
    );
    let ciphertext = &encrypted_data[MAGIC_SIZE + VERSION_SIZE + NONCE_SIZE..];

    if key_version == current_version {
        let mut key = current_key;
        let cipher = Aes256Gcm::new_from_slice(&key)
            .map_err(|_| Error::Other("invalid AES-256-GCM key length".into()))?;
        let result = cipher
            .decrypt(nonce, ciphertext)
            .map_err(|e| Error::Other(format!("AES decrypt: {e}")));
        // Zeroize the key copy immediately after use
        use zeroize::Zeroize;
        key.zeroize();
        result
    } else {
        let keys = past_keys.read().map_err(|_| {
            Error::Other("poisoned past_keys lock in spawn_blocking".into())
        })?;
        if let Some(entry) = keys.get(&key_version) {
            entry
                .cipher
                .decrypt(nonce, ciphertext)
                .map_err(|e| Error::Other(format!("AES decrypt: {e}")))
        } else {
            Err(Error::Other(format!(
                "unknown key version {} (current is {})",
                key_version, current_version
            )))
        }
    }
}

impl Drop for EncryptedBucketStore {
    fn drop(&mut self) {
        use zeroize::Zeroize;
        self.current_key.zeroize();
        if let Ok(mut keys) = self.past_keys.write() {
            keys.clear();
        }
    }
}