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/// Helper trait that lets a `dyn Error + Send + Sync` trait object be upcast
16/// to `&dyn Error` without requiring Rust 1.86's trait-upcasting coercion.
17/// The crate's MSRV is 1.85; once it moves to 1.86+ this can be removed and
18/// `source()` can be a plain `self.source.as_deref()`.
19trait ErrorExt: fmt::Debug + std::error::Error {
20 /// Upcast this error to a `dyn std::error::Error` reference.
21 fn as_std_error(&self) -> &(dyn std::error::Error + 'static);
22}
23
24impl<T: std::error::Error + 'static> ErrorExt for T {
25 fn as_std_error(&self) -> &(dyn std::error::Error + 'static) {
26 self
27 }
28}
29
30/// Error returned by [`SegmentCipher`] implementations.
31///
32/// Deliberately minimal: the cipher operates on bytes, not files, so it has no
33/// path or sequence context to carry. The segment I/O layer enriches this into
34/// a [`crate::SegmentError::Cipher`] with the offending file's path.
35///
36/// Construct with [`CipherError::msg`] for a plain message, or
37/// [`CipherError::with_source`] when you want to preserve the underlying AEAD
38/// (or other) error type for `std::error::Error::source()` chaining. The
39/// fields are private so that adding context later is non-breaking.
40#[derive(Debug, Clone)]
41pub struct CipherError {
42 /// Human-readable description of what went wrong.
43 message: String,
44 /// Optional underlying cause (e.g. the AEAD crate's opaque error).
45 /// `Arc` (not `Box`) so [`CipherError`] stays [`Clone`]. Surfaced via
46 /// [`std::error::Error::source`].
47 source: Option<Arc<dyn ErrorExt + Send + Sync>>,
48}
49
50impl CipherError {
51 /// Construct a [`CipherError`] from anything displayable, with no
52 /// underlying cause.
53 pub fn msg(message: impl fmt::Display) -> Self {
54 Self {
55 message: message.to_string(),
56 source: None,
57 }
58 }
59
60 /// Construct a [`CipherError`] that preserves the underlying error so
61 /// operators can inspect it via [`std::error::Error::source`].
62 ///
63 /// Use this when wrapping a typed error from an AEAD implementation
64 /// (`aes_gcm::Error`, `chacha20poly1305::Error`, …) so the original
65 /// failure is not erased behind a `format!`.
66 ///
67 /// # Example
68 ///
69 /// ```
70 /// use segment_buffer::CipherError;
71 /// use std::fmt;
72 /// use std::error::Error;
73 ///
74 /// /// A tiny typed error an AEAD crate might expose.
75 /// #[derive(Debug)]
76 /// struct AeadError;
77 /// impl fmt::Display for AeadError {
78 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 /// f.write_str("tag mismatch")
80 /// }
81 /// }
82 /// impl std::error::Error for AeadError {}
83 ///
84 /// let err = CipherError::with_source("AES-GCM decryption failed", AeadError);
85 /// assert_eq!(err.to_string(), "AES-GCM decryption failed");
86 /// // The underlying cause is preserved via `source()`:
87 /// let src = err.source().expect("source should be set by with_source");
88 /// assert_eq!(src.to_string(), "tag mismatch");
89 /// ```
90 pub fn with_source<E>(message: impl fmt::Display, source: E) -> Self
91 where
92 E: std::error::Error + Send + Sync + 'static,
93 {
94 Self {
95 message: message.to_string(),
96 source: Some(Arc::new(source)),
97 }
98 }
99}
100
101impl fmt::Display for CipherError {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 f.write_str(&self.message)
104 }
105}
106
107impl std::error::Error for CipherError {
108 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
109 // `Arc<dyn ErrorExt + Send + Sync>` cannot be coerced to
110 // `&dyn Error` until trait-upcasting stabilises for our MSRV (1.86+);
111 // `ErrorExt::as_std_error` does the upcast explicitly.
112 self.source.as_ref().map(|s| s.as_std_error())
113 }
114}
115
116/// Encrypts and decrypts segment file payloads.
117///
118/// Implementations must be [`Send`] + [`Sync`] because the buffer is shared
119/// across threads via `Arc<SegmentBuffer>`.
120///
121/// The ciphertext format is implementation-defined but must be self-describing:
122/// [`decrypt`](Self::decrypt) must be able to recover the plaintext from the
123/// exact bytes returned by [`encrypt`](Self::encrypt) without external state.
124///
125/// # Example
126///
127/// ```
128/// use segment_buffer::{CipherError, SegmentCipher};
129///
130/// struct Rot13;
131///
132/// impl SegmentCipher for Rot13 {
133/// fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
134/// Ok(plaintext.iter().map(|b| b.wrapping_add(13)).collect())
135/// }
136/// fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>, CipherError> {
137/// Ok(ciphertext.iter().map(|b| b.wrapping_sub(13)).collect())
138/// }
139/// }
140/// ```
141pub trait SegmentCipher: Send + Sync {
142 /// Encrypt `plaintext`, returning self-describing ciphertext.
143 fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>, CipherError>;
144
145 /// Decrypt previously-produced ciphertext back to the original plaintext.
146 fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>, CipherError>;
147}
148
149// ---------------------------------------------------------------------------
150// AES-256-GCM implementation (behind the `encryption` feature)
151// ---------------------------------------------------------------------------
152
153#[cfg(feature = "encryption")]
154mod private {
155 use super::{CipherError, SegmentCipher};
156 use std::fmt;
157 use std::sync::Arc;
158
159 /// Wrapper that turns any `Display`able AEAD error (e.g. the opaque
160 /// `aes_gcm::Error`, which intentionally does not impl `std::error::Error`)
161 /// into something that does, so it can flow through
162 /// [`std::error::Error::source`] chains without losing the original
163 /// diagnostic message.
164 #[derive(Debug, Clone)]
165 struct AeadError(String);
166
167 impl fmt::Display for AeadError {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 f.write_str(&self.0)
170 }
171 }
172
173 impl std::error::Error for AeadError {}
174
175 fn wrap<E: fmt::Display>(message: &'static str, e: E) -> CipherError {
176 CipherError {
177 message: message.to_string(),
178 source: Some(Arc::new(AeadError(e.to_string()))),
179 }
180 }
181
182 /// AES-256-GCM cipher with a random 12-byte nonce prepended to each ciphertext.
183 ///
184 /// The on-disk payload format is: `[12-byte nonce][ciphertext + 16-byte GCM tag]`.
185 /// This is byte-compatible with monitor365's `EncryptionKey` segment format,
186 /// so existing encrypted segments can be read without migration. (The segment
187 /// file envelope, if present, is stripped before the cipher sees the bytes.)
188 pub struct AesGcmCipher {
189 cipher: aes_gcm::Aes256Gcm,
190 }
191
192 impl AesGcmCipher {
193 /// Create a new cipher from a 32-byte AES-256 key.
194 ///
195 /// # Errors
196 ///
197 /// Returns [`CipherError`] if the key length is not 32 bytes.
198 pub fn from_slice(key_bytes: &[u8]) -> Result<Self, CipherError> {
199 use aes_gcm::KeyInit;
200 let cipher = aes_gcm::Aes256Gcm::new_from_slice(key_bytes)
201 .map_err(|e| wrap("invalid AES-256 key", e))?;
202 Ok(Self { cipher })
203 }
204
205 /// Create a new cipher from a 32-byte AES-256 key (const-sized input).
206 pub fn new(key_bytes: &[u8; 32]) -> Self {
207 use aes_gcm::KeyInit;
208 Self {
209 cipher: aes_gcm::Aes256Gcm::new_from_slice(key_bytes)
210 .expect("32-byte key is always valid for AES-256"),
211 }
212 }
213 }
214
215 impl SegmentCipher for AesGcmCipher {
216 fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>, CipherError> {
217 use aes_gcm::aead::Aead;
218 use rand::RngCore;
219
220 let mut nonce_bytes = [0u8; 12];
221 rand::thread_rng().fill_bytes(&mut nonce_bytes);
222 let nonce = aes_gcm::Nonce::from_slice(&nonce_bytes);
223
224 let ciphertext = self
225 .cipher
226 .encrypt(nonce, plaintext)
227 .map_err(|e| wrap("AES-GCM encryption failed", e))?;
228
229 let mut out = Vec::with_capacity(12 + ciphertext.len());
230 out.extend_from_slice(&nonce_bytes);
231 out.extend_from_slice(&ciphertext);
232 Ok(out)
233 }
234
235 fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>, CipherError> {
236 use aes_gcm::aead::Aead;
237
238 if ciphertext.len() < 12 {
239 return Err(CipherError::msg("ciphertext too small for nonce prefix"));
240 }
241 let (nonce_bytes, encrypted) = ciphertext.split_at(12);
242 let nonce = aes_gcm::Nonce::from_slice(nonce_bytes);
243
244 self.cipher
245 .decrypt(nonce, encrypted)
246 .map_err(|e| wrap("AES-GCM decryption failed", e))
247 }
248 }
249}
250
251#[cfg(feature = "encryption")]
252pub use private::AesGcmCipher;