Skip to main content

segment_buffer/
cipher.rs

1//! Pluggable encryption for segment files at rest.
2//!
3//! The [`SegmentCipher`] trait abstracts the encrypt/decrypt operations so
4//! callers can bring any AEAD (AES-GCM, ChaCha20-Poly1305, etc.). When the
5//! `encryption` feature is enabled, a ready-made [`AesGcmCipher`] is provided.
6//!
7//! Cipher implementations return the lightweight [`CipherError`] so they don't
8//! need to know about segment paths or the wider [`crate::SegmentError`]
9//! hierarchy. The segment I/O layer attaches path context when promoting a
10//! [`CipherError`] to a [`crate::SegmentError::Cipher`].
11
12use std::fmt;
13use std::sync::Arc;
14
15/// Error returned by [`SegmentCipher`] implementations.
16///
17/// Deliberately minimal: the cipher operates on bytes, not files, so it has no
18/// path or sequence context to carry. The segment I/O layer enriches this into
19/// a [`crate::SegmentError::Cipher`] with the offending file's path.
20///
21/// Construct with [`CipherError::msg`] for a plain message, or
22/// [`CipherError::with_source`] when you want to preserve the underlying AEAD
23/// (or other) error type for `std::error::Error::source()` chaining. The
24/// fields are private so that adding context later is non-breaking.
25#[derive(Debug, Clone)]
26pub struct CipherError {
27    /// Human-readable description of what went wrong.
28    message: String,
29    /// Optional underlying cause (e.g. the AEAD crate's opaque error).
30    /// `Arc` (not `Box`) so [`CipherError`] stays [`Clone`]. Surfaced via
31    /// [`std::error::Error::source`].
32    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
33}
34
35impl CipherError {
36    /// Construct a [`CipherError`] from anything displayable, with no
37    /// underlying cause.
38    ///
39    /// # Example
40    ///
41    /// ```
42    /// use segment_buffer::CipherError;
43    ///
44    /// let err = CipherError::msg("key not configured");
45    /// assert_eq!(err.to_string(), "key not configured");
46    /// assert!(std::error::Error::source(&err).is_none());
47    /// ```
48    pub fn msg(message: impl fmt::Display) -> Self {
49        Self {
50            message: message.to_string(),
51            source: None,
52        }
53    }
54
55    /// Construct a [`CipherError`] that preserves the underlying error so
56    /// operators can inspect it via [`std::error::Error::source`].
57    ///
58    /// Use this when wrapping a typed error from an AEAD implementation
59    /// (`aes_gcm::Error`, `chacha20poly1305::Error`, …) so the original
60    /// failure is not erased behind a `format!`.
61    ///
62    /// # Example
63    ///
64    /// ```
65    /// use segment_buffer::CipherError;
66    /// use std::fmt;
67    /// use std::error::Error;
68    ///
69    /// /// A tiny typed error an AEAD crate might expose.
70    /// #[derive(Debug)]
71    /// struct AeadError;
72    /// impl fmt::Display for AeadError {
73    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74    ///         f.write_str("tag mismatch")
75    ///     }
76    /// }
77    /// impl std::error::Error for AeadError {}
78    ///
79    /// let err = CipherError::with_source("AES-GCM decryption failed", AeadError);
80    /// assert_eq!(err.to_string(), "AES-GCM decryption failed");
81    /// // The underlying cause is preserved via `source()`:
82    /// let src = err.source().expect("source should be set by with_source");
83    /// assert_eq!(src.to_string(), "tag mismatch");
84    /// ```
85    pub fn with_source<E>(message: impl fmt::Display, source: E) -> Self
86    where
87        E: std::error::Error + Send + Sync + 'static,
88    {
89        Self {
90            message: message.to_string(),
91            source: Some(Arc::new(source)),
92        }
93    }
94}
95
96impl fmt::Display for CipherError {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        f.write_str(&self.message)
99    }
100}
101
102impl std::error::Error for CipherError {
103    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
104        // Trait-upcasting coercion (stable since Rust 1.86) turns
105        // `&(dyn Error + Send + Sync)` into `&dyn Error`. The explicit
106        // closure return type forces the coercion through `Option::map`.
107        self.source
108            .as_deref()
109            .map(|s| -> &(dyn std::error::Error + 'static) { s })
110    }
111}
112
113/// Encrypts and decrypts segment file payloads.
114///
115/// Implementations must be [`Send`] + [`Sync`] because the buffer is shared
116/// across threads via `Arc<SegmentBuffer>`.
117///
118/// The ciphertext format is implementation-defined but must be self-describing:
119/// [`decrypt`](Self::decrypt) must be able to recover the plaintext from the
120/// exact bytes returned by [`encrypt`](Self::encrypt) without external state.
121///
122/// # Naming
123///
124/// The trait is called `SegmentCipher`, not `SegmentAead`, even though the
125/// shipped implementation (the `AesGcmCipher` behind the `encryption` feature)
126/// is an AEAD. This is deliberate: the trait contract is "any stateless
127/// self-describing encrypt/decrypt pair", which admits AEADs (recommended),
128/// HMAC-wrapped symmetric ciphers, or even custom schemes that combine
129/// encryption with a separate authenticator. Renaming to `SegmentAead` would
130/// narrow the contract to AEADs only — a constraint the trait does not actually
131/// enforce. Use an AEAD in practice; the trait stays general on purpose.
132///
133/// # Example
134///
135/// ```
136/// use segment_buffer::{CipherError, SegmentCipher};
137///
138/// struct Rot13;
139///
140/// impl SegmentCipher for Rot13 {
141///     fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
142///         Ok(plaintext.iter().map(|b| b.wrapping_add(13)).collect())
143///     }
144///     fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>, CipherError> {
145///         Ok(ciphertext.iter().map(|b| b.wrapping_sub(13)).collect())
146///     }
147/// }
148/// ```
149pub trait SegmentCipher: Send + Sync {
150    /// Encrypt `plaintext`, returning self-describing ciphertext.
151    fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>, CipherError>;
152
153    /// Decrypt previously-produced ciphertext back to the original plaintext.
154    fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>, CipherError>;
155}
156
157// ---------------------------------------------------------------------------
158// AES-256-GCM implementation (behind the `encryption` feature)
159// ---------------------------------------------------------------------------
160
161#[cfg(feature = "encryption")]
162mod private {
163    use super::{CipherError, SegmentCipher};
164    use std::fmt;
165    use std::sync::Arc;
166
167    /// Wrapper that turns any `Display`able AEAD error (e.g. the opaque
168    /// `aes_gcm::Error`, which intentionally does not impl `std::error::Error`)
169    /// into something that does, so it can flow through
170    /// [`std::error::Error::source`] chains without losing the original
171    /// diagnostic message.
172    #[derive(Debug, Clone)]
173    struct AeadError(String);
174
175    impl fmt::Display for AeadError {
176        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177            f.write_str(&self.0)
178        }
179    }
180
181    impl std::error::Error for AeadError {}
182
183    fn wrap<E: fmt::Display>(message: &'static str, e: E) -> CipherError {
184        CipherError {
185            message: message.to_string(),
186            source: Some(Arc::new(AeadError(e.to_string()))),
187        }
188    }
189
190    /// AES-256-GCM cipher with a random 12-byte nonce prepended to each ciphertext.
191    ///
192    /// The on-disk payload format is: `[12-byte nonce][ciphertext + 16-byte GCM tag]`.
193    /// This is byte-compatible with monitor365's `EncryptionKey` segment format,
194    /// so existing encrypted segments can be read without migration. (The segment
195    /// file envelope, if present, is stripped before the cipher sees the bytes.)
196    pub struct AesGcmCipher {
197        cipher: aes_gcm::Aes256Gcm,
198    }
199
200    impl AesGcmCipher {
201        /// Create a new cipher from a 32-byte AES-256 key.
202        ///
203        /// # Example
204        ///
205        /// ```
206        /// use segment_buffer::AesGcmCipher;
207        ///
208        /// let key = [0u8; 32];
209        /// let _cipher = AesGcmCipher::from_slice(&key).unwrap();
210        /// ```
211        ///
212        /// # Errors
213        ///
214        /// Returns [`CipherError`] if the key length is not 32 bytes.
215        pub fn from_slice(key_bytes: &[u8]) -> Result<Self, CipherError> {
216            use aes_gcm::KeyInit;
217            let cipher = aes_gcm::Aes256Gcm::new_from_slice(key_bytes)
218                .map_err(|e| wrap("invalid AES-256 key", e))?;
219            Ok(Self { cipher })
220        }
221
222        /// Create a new cipher from a 32-byte AES-256 key (const-sized input).
223        ///
224        /// # Example
225        ///
226        /// ```
227        /// use segment_buffer::AesGcmCipher;
228        /// use segment_buffer::SegmentCipher;
229        ///
230        /// let cipher = AesGcmCipher::new(&[0u8; 32]);
231        /// let ciphertext = cipher.encrypt(b"hello").unwrap();
232        /// let plaintext = cipher.decrypt(&ciphertext).unwrap();
233        /// assert_eq!(plaintext, b"hello");
234        /// ```
235        pub fn new(key_bytes: &[u8; 32]) -> Self {
236            use aes_gcm::KeyInit;
237            Self {
238                cipher: aes_gcm::Aes256Gcm::new_from_slice(key_bytes)
239                    .expect("32-byte key is always valid for AES-256"),
240            }
241        }
242    }
243
244    impl SegmentCipher for AesGcmCipher {
245        fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
246            use aes_gcm::aead::Aead;
247            use rand::Rng;
248
249            let mut nonce_bytes = [0u8; 12];
250            rand::rng().fill_bytes(&mut nonce_bytes);
251            let nonce = aes_gcm::Nonce::from(nonce_bytes);
252
253            let ciphertext = self
254                .cipher
255                .encrypt(&nonce, plaintext)
256                .map_err(|e| wrap("AES-GCM encryption failed", e))?;
257
258            let mut out = Vec::with_capacity(12 + ciphertext.len());
259            out.extend_from_slice(&nonce_bytes);
260            out.extend_from_slice(&ciphertext);
261            Ok(out)
262        }
263
264        fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>, CipherError> {
265            use aes_gcm::aead::Aead;
266
267            if ciphertext.len() < 12 {
268                return Err(CipherError::msg("ciphertext too small for nonce prefix"));
269            }
270            let (nonce_bytes, encrypted) = ciphertext.split_at(12);
271            let nonce: [u8; 12] = nonce_bytes
272                .try_into()
273                .map_err(|_| CipherError::msg("invalid nonce length: expected 12 bytes"))?;
274            let nonce = aes_gcm::Nonce::from(nonce);
275
276            self.cipher
277                .decrypt(&nonce, encrypted)
278                .map_err(|e| wrap("AES-GCM decryption failed", e))
279        }
280    }
281
282    // -----------------------------------------------------------------------
283    // XChaCha20-Poly1305
284    // -----------------------------------------------------------------------
285
286    /// Nonce length for XChaCha20-Poly1305: 24 bytes. Public so callers can
287    /// reason about the on-disk payload shape without importing the AEAD crate.
288    const XCHACHA_NONCE_LEN: usize = 24;
289
290    /// XChaCha20-Poly1305 cipher with a random 24-byte nonce prepended to each
291    /// ciphertext.
292    ///
293    /// The on-disk payload format is:
294    /// `[24-byte nonce][ciphertext + 16-byte Poly1305 tag]`.
295    ///
296    /// # Why XChaCha20 over AES-GCM for new buffers
297    ///
298    /// - **No 2³²-message limit per key.** AES-GCM's 12-byte nonce collides
299    ///   after ~2³² messages under the same key (a collision breaks
300    ///   confidentiality). XChaCha20's 24-byte nonce makes random-nonce
301    ///   collision negligible well past 2⁴⁸ messages.
302    /// - **Constant-time on hosts without AES-NI.** ChaCha20 is constant-time
303    ///   in software; AES-GCM relies on hardware acceleration (AES-NI on
304    ///   x86, ARMv8 Crypto Extensions on aarch64) for performance and leaks
305    ///   timing on hosts without it (older CPUs, some embedded ARM).
306    ///
307    /// Legacy AES-GCM segments still decrypt through [`AesGcmCipher`]; the
308    /// two formats are byte-distinguishable only by which cipher the buffer
309    /// was opened with (no envelope marker for the cipher type today — see
310    /// the envelope v2 design doc for the migration path).
311    pub struct XChaCha20Poly1305Cipher {
312        cipher: chacha20poly1305::XChaCha20Poly1305,
313    }
314
315    impl XChaCha20Poly1305Cipher {
316        /// Create a new cipher from a 32-byte key.
317        ///
318        /// # Example
319        ///
320        /// ```
321        /// use segment_buffer::{SegmentCipher, XChaCha20Poly1305Cipher};
322        ///
323        /// let cipher = XChaCha20Poly1305Cipher::new(&[0u8; 32]);
324        /// let ciphertext = cipher.encrypt(b"hello").unwrap();
325        /// let plaintext = cipher.decrypt(&ciphertext).unwrap();
326        /// assert_eq!(plaintext, b"hello");
327        /// ```
328        pub fn new(key_bytes: &[u8; 32]) -> Self {
329            use chacha20poly1305::KeyInit;
330            Self {
331                cipher: chacha20poly1305::XChaCha20Poly1305::new_from_slice(key_bytes)
332                    .expect("32-byte key is always valid for XChaCha20-Poly1305"),
333            }
334        }
335
336        /// Create a new cipher from a 32-byte slice. Falls back to
337        /// [`CipherError`] when the slice is not exactly 32 bytes.
338        ///
339        /// # Errors
340        ///
341        /// Returns [`CipherError`] if the key length is not 32 bytes.
342        pub fn from_slice(key_bytes: &[u8]) -> Result<Self, CipherError> {
343            use chacha20poly1305::KeyInit;
344            let cipher = chacha20poly1305::XChaCha20Poly1305::new_from_slice(key_bytes)
345                .map_err(|e| wrap("invalid XChaCha20 key", e))?;
346            Ok(Self { cipher })
347        }
348    }
349
350    impl SegmentCipher for XChaCha20Poly1305Cipher {
351        fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
352            use chacha20poly1305::aead::Aead;
353            use rand::Rng;
354
355            let mut nonce_bytes = [0u8; XCHACHA_NONCE_LEN];
356            rand::rng().fill_bytes(&mut nonce_bytes);
357            let nonce = chacha20poly1305::XNonce::from_slice(&nonce_bytes);
358
359            let ciphertext = self
360                .cipher
361                .encrypt(nonce, plaintext)
362                .map_err(|e| wrap("XChaCha20 encryption failed", e))?;
363
364            let mut out = Vec::with_capacity(XCHACHA_NONCE_LEN + ciphertext.len());
365            out.extend_from_slice(&nonce_bytes);
366            out.extend_from_slice(&ciphertext);
367            Ok(out)
368        }
369
370        fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>, CipherError> {
371            use chacha20poly1305::aead::Aead;
372
373            if ciphertext.len() < XCHACHA_NONCE_LEN {
374                return Err(CipherError::msg(
375                    "ciphertext too small for XChaCha20 nonce prefix (need 24 bytes)",
376                ));
377            }
378            let (nonce_bytes, encrypted) = ciphertext.split_at(XCHACHA_NONCE_LEN);
379            let nonce = chacha20poly1305::XNonce::from_slice(nonce_bytes);
380
381            self.cipher
382                .decrypt(nonce, encrypted)
383                .map_err(|e| wrap("XChaCha20 decryption failed", e))
384        }
385    }
386}
387
388#[cfg(feature = "encryption")]
389pub use private::{AesGcmCipher, XChaCha20Poly1305Cipher};