Files
tern-server/src/crypto.rs
T
Mateusz PstruchaandClaude Opus 5 4c1a6457c5 Initial sync server: IMAP engine, schema, and read API
Covers phases 1-2 of the build order in the architecture spec: the IMAP
sync engine (IDLE + UIDVALIDITY tracking + jittered reconnect, headers
first with lazy body fetch), the full data model, and a minimal REST API
for auth, accounts, folders, messages and delta polling.

Credentials are encrypted at rest with ChaCha20-Poly1305 rather than
libsodium secretbox, to avoid a system dependency for the same
construction.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 19:00:59 +02:00

72 lines
2.1 KiB
Rust

//! Encryption at rest for stored IMAP/SMTP credentials.
//!
//! server-architecture-spec.md §7 asks for "libsodium secretbox... or better, a
//! key derived from something you don't also store in the same DB". We use
//! ChaCha20-Poly1305 (RustCrypto, pure Rust, no libsodium system dependency)
//! which is the same construction family as secretbox (XSalsa20-Poly1305) —
//! an AEAD cipher with a random nonce per message. The key itself comes from
//! the `CREDENTIAL_KEY` env var (see config.rs), not from the database.
use anyhow::{Context, Result};
use chacha20poly1305::{
aead::{Aead, KeyInit},
ChaCha20Poly1305, Key, Nonce,
};
use rand::RngCore;
#[derive(Clone)]
pub struct CredentialCipher {
cipher: ChaCha20Poly1305,
}
pub struct Encrypted {
pub ciphertext: Vec<u8>,
pub nonce: Vec<u8>,
}
impl CredentialCipher {
pub fn new(key: &[u8; 32]) -> Self {
Self {
cipher: ChaCha20Poly1305::new(Key::from_slice(key)),
}
}
pub fn encrypt(&self, plaintext: &str) -> Result<Encrypted> {
let mut nonce_bytes = [0u8; 12];
rand::thread_rng().fill_bytes(&mut nonce_bytes);
let nonce = Nonce::from_slice(&nonce_bytes);
let ciphertext = self
.cipher
.encrypt(nonce, plaintext.as_bytes())
.map_err(|e| anyhow::anyhow!("credential encryption failed: {e}"))?;
Ok(Encrypted {
ciphertext,
nonce: nonce_bytes.to_vec(),
})
}
pub fn decrypt(&self, ciphertext: &[u8], nonce: &[u8]) -> Result<String> {
let nonce = Nonce::from_slice(nonce);
let plaintext = self
.cipher
.decrypt(nonce, ciphertext)
.map_err(|e| anyhow::anyhow!("credential decryption failed: {e}"))?;
String::from_utf8(plaintext).context("decrypted credential was not valid utf-8")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips() {
let key = [7u8; 32];
let c = CredentialCipher::new(&key);
let enc = c.encrypt("hunter2").unwrap();
assert_eq!(c.decrypt(&enc.ciphertext, &enc.nonce).unwrap(), "hunter2");
}
}