1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
//! Central encryption manager that wires together config, key provider, key
//! derivation, and cipher creation at database startup.
//!
//! [`EncryptionManager`] is the single entry-point that the rest of the database
//! uses to obtain per-component ciphers.
use std::sync::Arc;
use crate::encryption::cipher::Cipher;
use crate::encryption::config::{EncryptionConfig, KeyProviderConfig};
use crate::encryption::error::KeyProviderError;
use crate::encryption::factory::create_cipher;
use crate::encryption::key_derivation::{
CHECKPOINT_DEK_CONTEXT, COLD_DEK_CONTEXT, INDEX_DEK_CONTEXT, KeyDerivation, WAL_DEK_CONTEXT,
};
use crate::encryption::key_provider::{EnvKeyProvider, FileKeyProvider, KeyProvider};
/// Central manager that owns per-component ciphers for encryption at rest.
///
/// Created once at database startup via [`from_config`](Self::from_config) and
/// then shared (via `Arc`) with every persistence subsystem that needs to
/// encrypt/decrypt data.
pub struct EncryptionManager {
wal_cipher: Arc<dyn Cipher>,
index_cipher: Arc<dyn Cipher>,
cold_cipher: Arc<dyn Cipher>,
checkpoint_cipher: Arc<dyn Cipher>,
provider_name: String,
}
impl std::fmt::Debug for EncryptionManager {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EncryptionManager")
.field("wal_cipher", &self.wal_cipher.algorithm_name())
.field("index_cipher", &self.index_cipher.algorithm_name())
.field("cold_cipher", &self.cold_cipher.algorithm_name())
.field(
"checkpoint_cipher",
&self.checkpoint_cipher.algorithm_name(),
)
.field("provider_name", &self.provider_name)
.finish()
}
}
impl EncryptionManager {
/// Build an [`EncryptionManager`] from an [`EncryptionConfig`].
///
/// This:
/// 1. Creates the appropriate [`KeyProvider`] based on config.
/// 2. Loads the Master Encryption Key (MEK).
/// 3. Derives four per-component DEKs via HKDF-SHA256.
/// 4. Creates four independent ciphers (one per storage component).
///
/// # Errors
///
/// Returns [`KeyProviderError`] if the MEK cannot be loaded (missing file,
/// missing env var, invalid format, etc.).
pub fn from_config(config: &EncryptionConfig) -> Result<Self, KeyProviderError> {
// 1. Create the key provider.
let provider: Box<dyn KeyProvider> = match &config.key_provider {
KeyProviderConfig::File { path } => Box::new(FileKeyProvider::new(path)),
KeyProviderConfig::Env { variable } => Box::new(EnvKeyProvider::new(variable)),
};
let name = provider.provider_name().to_string();
// 2. Load the MEK.
let mek = provider.get_mek()?;
// 3. Derive per-component DEKs.
let kd = KeyDerivation::new(mek);
let wal_dek = kd
.derive_dek(WAL_DEK_CONTEXT)
.map_err(|e| KeyProviderError::Provider(Box::new(e)))?;
let index_dek = kd
.derive_dek(INDEX_DEK_CONTEXT)
.map_err(|e| KeyProviderError::Provider(Box::new(e)))?;
let cold_dek = kd
.derive_dek(COLD_DEK_CONTEXT)
.map_err(|e| KeyProviderError::Provider(Box::new(e)))?;
let checkpoint_dek = kd
.derive_dek(CHECKPOINT_DEK_CONTEXT)
.map_err(|e| KeyProviderError::Provider(Box::new(e)))?;
// 4. Create ciphers.
let algorithm = config.algorithm;
Ok(Self {
wal_cipher: Arc::from(create_cipher(algorithm, &wal_dek)),
index_cipher: Arc::from(create_cipher(algorithm, &index_dek)),
cold_cipher: Arc::from(create_cipher(algorithm, &cold_dek)),
checkpoint_cipher: Arc::from(create_cipher(algorithm, &checkpoint_dek)),
provider_name: name,
})
}
/// Cipher for WAL encryption/decryption.
///
/// # Why?
/// Each component gets its own derived key (DEK) to limit the blast radius if a single
/// component's key is compromised. The WAL cipher is specifically for the write-ahead log.
///
/// ## Examples
/// ```
/// use aletheiadb::encryption::manager::EncryptionManager;
/// use aletheiadb::encryption::config::EncryptionConfig;
/// use aletheiadb::encryption::key_provider::FileKeyProvider;
/// use aletheiadb::encryption::cipher::Cipher;
///
/// let dir = tempfile::tempdir().unwrap();
/// let key_path = dir.path().join("test.key");
/// FileKeyProvider::generate_key_file(&key_path).unwrap();
///
/// let config = EncryptionConfig::file_based(&key_path);
/// let manager = EncryptionManager::from_config(&config).unwrap();
///
/// let encrypted = manager.wal_cipher().encrypt(b"data", b"aad").unwrap();
/// ```
#[must_use]
pub fn wal_cipher(&self) -> &Arc<dyn Cipher> {
&self.wal_cipher
}
/// Cipher for index persistence encryption/decryption.
///
/// # Why?
/// The index cipher uses a separate derived key from the WAL and cold storage to ensure
/// cryptographic isolation between the vector search indexes and core database data.
///
/// ## Examples
/// ```
/// use aletheiadb::encryption::manager::EncryptionManager;
/// use aletheiadb::encryption::config::EncryptionConfig;
/// use aletheiadb::encryption::key_provider::FileKeyProvider;
/// use aletheiadb::encryption::cipher::Cipher;
///
/// let dir = tempfile::tempdir().unwrap();
/// let key_path = dir.path().join("test.key");
/// FileKeyProvider::generate_key_file(&key_path).unwrap();
///
/// let config = EncryptionConfig::file_based(&key_path);
/// let manager = EncryptionManager::from_config(&config).unwrap();
///
/// let encrypted = manager.index_cipher().encrypt(b"data", b"aad").unwrap();
/// ```
#[must_use]
pub fn index_cipher(&self) -> &Arc<dyn Cipher> {
&self.index_cipher
}
/// Cipher for cold storage encryption/decryption.
///
/// # Why?
/// Cold storage files might be archived to untrusted cloud storage (like S3). Using a
/// dedicated key ensures that even if an attacker obtains an archive, they cannot decrypt
/// it without this specific DEK.
///
/// ## Examples
/// ```
/// use aletheiadb::encryption::manager::EncryptionManager;
/// use aletheiadb::encryption::config::EncryptionConfig;
/// use aletheiadb::encryption::key_provider::FileKeyProvider;
/// use aletheiadb::encryption::cipher::Cipher;
///
/// let dir = tempfile::tempdir().unwrap();
/// let key_path = dir.path().join("test.key");
/// FileKeyProvider::generate_key_file(&key_path).unwrap();
///
/// let config = EncryptionConfig::file_based(&key_path);
/// let manager = EncryptionManager::from_config(&config).unwrap();
///
/// let encrypted = manager.cold_cipher().encrypt(b"data", b"aad").unwrap();
/// ```
#[must_use]
pub fn cold_cipher(&self) -> &Arc<dyn Cipher> {
&self.cold_cipher
}
/// Cipher for checkpoint encryption/decryption.
///
/// # Why?
/// Checkpoint files contain complete database snapshots. Isolating their encryption
/// from active WAL segments prevents attackers from exploiting potential nonce-reuse
/// vulnerabilities across different snapshot versions.
///
/// ## Examples
/// ```
/// use aletheiadb::encryption::manager::EncryptionManager;
/// use aletheiadb::encryption::config::EncryptionConfig;
/// use aletheiadb::encryption::key_provider::FileKeyProvider;
/// use aletheiadb::encryption::cipher::Cipher;
///
/// let dir = tempfile::tempdir().unwrap();
/// let key_path = dir.path().join("test.key");
/// FileKeyProvider::generate_key_file(&key_path).unwrap();
///
/// let config = EncryptionConfig::file_based(&key_path);
/// let manager = EncryptionManager::from_config(&config).unwrap();
///
/// let encrypted = manager.checkpoint_cipher().encrypt(b"data", b"aad").unwrap();
/// ```
#[must_use]
pub fn checkpoint_cipher(&self) -> &Arc<dyn Cipher> {
&self.checkpoint_cipher
}
/// Human-readable name of the key provider backend (e.g., `"file"`, `"env"`).
///
/// # Why?
/// This is used exclusively for diagnostic logging and telemetry, allowing operators
/// to see where the master key was sourced without exposing the key itself.
///
/// ## Examples
/// ```
/// use aletheiadb::encryption::manager::EncryptionManager;
/// use aletheiadb::encryption::config::EncryptionConfig;
/// use aletheiadb::encryption::key_provider::FileKeyProvider;
///
/// let dir = tempfile::tempdir().unwrap();
/// let key_path = dir.path().join("test.key");
/// FileKeyProvider::generate_key_file(&key_path).unwrap();
///
/// let config = EncryptionConfig::file_based(&key_path);
/// let manager = EncryptionManager::from_config(&config).unwrap();
///
/// assert_eq!(manager.provider_name(), "file");
/// ```
#[must_use]
pub fn provider_name(&self) -> &str {
&self.provider_name
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::encryption::key_provider::FileKeyProvider;
#[test]
fn from_config_with_file_provider() {
let dir = tempfile::tempdir().unwrap();
let key_path = dir.path().join("test.key");
FileKeyProvider::generate_key_file(&key_path).unwrap();
let config = EncryptionConfig::file_based(&key_path);
let mgr = EncryptionManager::from_config(&config).unwrap();
assert_eq!(mgr.provider_name(), "file");
// All four ciphers should round-trip independently.
let plaintext = b"manager test payload";
let aad = b"test-aad";
for (label, cipher) in [
("wal", mgr.wal_cipher()),
("index", mgr.index_cipher()),
("cold", mgr.cold_cipher()),
("checkpoint", mgr.checkpoint_cipher()),
] {
let encrypted = cipher.encrypt(plaintext, aad).unwrap();
let decrypted = cipher.decrypt(&encrypted, aad).unwrap();
assert_eq!(
decrypted.as_slice(),
plaintext,
"{label} cipher roundtrip failed"
);
}
}
#[test]
fn from_config_different_ciphers_per_component() {
let dir = tempfile::tempdir().unwrap();
let key_path = dir.path().join("test.key");
FileKeyProvider::generate_key_file(&key_path).unwrap();
let config = EncryptionConfig::file_based(&key_path);
let mgr = EncryptionManager::from_config(&config).unwrap();
let plaintext = b"cross-cipher test";
let aad = b"test-aad";
// Encrypt with WAL cipher, attempt decrypt with index cipher -- must fail.
let wal_encrypted = mgr.wal_cipher().encrypt(plaintext, aad).unwrap();
let result = mgr.index_cipher().decrypt(&wal_encrypted, aad);
assert!(
result.is_err(),
"Decrypting WAL ciphertext with index cipher should fail (different DEKs)"
);
}
#[test]
fn from_config_missing_key_file() {
let config = EncryptionConfig::file_based("/nonexistent/path/missing.key");
let err = EncryptionManager::from_config(&config).unwrap_err();
assert!(
matches!(err, KeyProviderError::KeyNotFound),
"expected KeyNotFound, got: {err}"
);
}
}