vecboost 0.3.0-rc.1

High-performance embedding vector service written in Rust
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Serde helpers for transparent field-level encryption using confers'
//! `XChaCha20-Poly1305` crypto primitives.
//!
//! # Overview
//!
//! Sensitive config fields (JWT secret, admin password) are encrypted at rest
//! in config files using XChaCha20-Poly1305. The master encryption key is read
//! from the `VECBOOST_ENCRYPTION_KEY` environment variable (must be exactly 32
//! bytes). A per-field key is derived via HKDF-SHA256 to ensure domain separation.
//!
//! # Wire format
//!
//! Encrypted values are stored as hex-encoded strings: `nonce ‖ ciphertext`
//! (24-byte nonce followed by Poly1305-authenticated ciphertext).
//!
//! # Fallback
//!
//! When `VECBOOST_ENCRYPTION_KEY` is not set, values pass through as plaintext.
//! This allows development/test environments to operate without encryption setup.
//!
//! # Usage
//!
//! ```rust,ignore
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize)]
//! struct MyConfig {
//!     #[serde(
//!         default,
//!         serialize_with = "crate::config::encryption::encrypted_option::serialize",
//!         deserialize_with = "crate::config::encryption::encrypted_option::deserialize"
//!     )]
//!     pub secret: Option<String>,
//! }
//! ```

use confers::secret::{XChaCha20Crypto, derive_field_key};

/// Environment variable name for the master encryption key.
///
/// The value must be exactly 32 bytes (UTF-8 encoded) for XChaCha20-Poly1305.
const ENCRYPTION_KEY_ENV: &str = "VECBOOST_ENCRYPTION_KEY";

/// Validate that the master encryption key is configured.
///
/// Returns `Ok(())` when `VECBOOST_ENCRYPTION_KEY` is set to a valid 32-byte value.
/// Returns `Err(reason)` when the key is missing or has an invalid length.
///
/// # Production Deployment
///
/// **生产环境必须设置 `VECBOOST_REQUIRE_ENCRYPTION=1`**,否则启动时会自动调用
/// 此函数校验密钥。未配置时敏感字段(JWT secret、admin password 等)将以明文
/// 存储,存在安全风险。
///
/// # Usage
///
/// Call during application startup to enforce encryption in production:
///
/// ```rust,ignore
/// crate::config::encryption::validate_encryption_key()?;
/// ```
pub fn validate_encryption_key() -> Result<(), String> {
    match read_master_key() {
        Some(_) => Ok(()),
        None => {
            if std::env::var(ENCRYPTION_KEY_ENV).is_err() {
                Err(crate::i18n::tr_with_args(
                    "config-encryption-missing",
                    crate::i18n::tr_args(&[("key", ENCRYPTION_KEY_ENV)]),
                ))
            } else {
                Err(crate::i18n::tr_with_args(
                    "config-encryption-length",
                    crate::i18n::tr_args(&[("key", ENCRYPTION_KEY_ENV)]),
                ))
            }
        }
    }
}

/// HKDF field path used to derive per-field encryption keys.
const FIELD_PATH: &str = "vecboost.config.sensitive";

/// Key version for HKDF domain separation (bump on key rotation).
const KEY_VERSION: &str = "v1";

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Read the 32-byte master key from the environment.
///
/// Returns `None` when the env var is unset or empty (encryption disabled).
/// 未配置时记录 `log::warn!` 提醒生产环境应配置加密密钥。
fn read_master_key() -> Option<[u8; 32]> {
    let key = match std::env::var(ENCRYPTION_KEY_ENV) {
        Ok(k) => k,
        Err(_) => {
            log::warn!(
                "{ENCRYPTION_KEY_ENV} not set — sensitive config fields stored as plaintext. \
                 Production deployments MUST set this to a 32-byte key \
                 (e.g. `openssl rand -hex 32`) and enable VECBOOST_REQUIRE_ENCRYPTION=1."
            );
            return None;
        }
    };
    if key.len() != 32 {
        log::warn!(
            "{ENCRYPTION_KEY_ENV} must be exactly 32 bytes for XChaCha20-Poly1305, \
             got {} bytes — encryption disabled",
            key.len()
        );
        return None;
    }
    let mut buf = [0u8; 32];
    buf.copy_from_slice(key.as_bytes());
    Some(buf)
}

/// Derive a 32-byte field key from the master key via HKDF-SHA256.
fn derive_key(master: &[u8; 32]) -> Result<[u8; 32], String> {
    derive_field_key(master, FIELD_PATH, KEY_VERSION)
        .map_err(|e| format!("key derivation failed: {e}"))
}

/// Encrypt plaintext bytes → hex-encoded `nonce ‖ ciphertext`.
fn encrypt_to_hex(plaintext: &[u8], master: &[u8; 32]) -> Result<String, String> {
    let field_key = derive_key(master)?;
    let crypto = XChaCha20Crypto::new();
    let (nonce, ciphertext) = crypto
        .encrypt(plaintext, &field_key)
        .map_err(|e| format!("encryption failed: {e}"))?;
    let mut combined = nonce;
    combined.extend_from_slice(&ciphertext);
    Ok(hex::encode(combined))
}

/// Decrypt hex-encoded `nonce ‖ ciphertext` → plaintext bytes.
fn decrypt_from_hex(encoded: &str, master: &[u8; 32]) -> Result<Vec<u8>, String> {
    let combined = hex::decode(encoded).map_err(|e| format!("invalid hex: {e}"))?;
    if combined.len() < confers::secret::NONCE_SIZE {
        return Err("encrypted value too short".to_string());
    }
    let (nonce_bytes, ciphertext) = combined.split_at(confers::secret::NONCE_SIZE);
    let field_key = derive_key(master)?;
    let crypto = XChaCha20Crypto::new();
    crypto
        .decrypt(nonce_bytes, ciphertext, &field_key)
        .map_err(|e| format!("decryption failed: {e}"))
}

// ---------------------------------------------------------------------------
// Serde helper modules for `#[serde(serialize_with / deserialize_with)]`
// ---------------------------------------------------------------------------

/// Serde helpers for `Option<String>` fields with transparent encryption.
///
/// - **Serialize**: encrypts the inner `String` (if `Some`) using XChaCha20-Poly1305.
/// - **Deserialize**: decrypts the hex-encoded ciphertext back to `String`.
/// - **Fallback**: when `VECBOOST_ENCRYPTION_KEY` is not set, values pass through
///   as plaintext (development convenience).
pub mod encrypted_option {
    use super::*;
    use serde::{Deserialize, Deserializer, Serializer};

    /// Serialize `Option<String>` with encryption.
    ///
    /// - `None` → serde `none` (omitted or null).
    /// - `Some(plaintext)` → hex-encoded encrypted string.
    pub fn serialize<S: Serializer>(
        value: &Option<String>,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        match value {
            None => serializer.serialize_none(),
            Some(plaintext) => {
                let encrypted = match read_master_key() {
                    Some(master) => encrypt_to_hex(plaintext.as_bytes(), &master)
                        .map_err(serde::ser::Error::custom)?,
                    None => {
                        // No encryption key → pass through as plaintext.
                        plaintext.clone()
                    }
                };
                serializer.serialize_str(&encrypted)
            }
        }
    }

    /// Deserialize `Option<String>` with decryption.
    ///
    /// - Missing/null → `None`.
    /// - Present → attempt decryption; on failure, treat as plaintext.
    pub fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Option<String>, D::Error> {
        let opt = Option::<String>::deserialize(deserializer)?;
        match opt {
            None => Ok(None),
            Some(encoded) => {
                let decrypted = match read_master_key() {
                    Some(master) => match decrypt_from_hex(&encoded, &master) {
                        Ok(bytes) => String::from_utf8(bytes).map_err(serde::de::Error::custom)?,
                        Err(_) => {
                            // Decryption failed → assume plaintext value.
                            encoded
                        }
                    },
                    None => encoded,
                };
                Ok(Some(decrypted))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// 串行化进程级环境变量 VECBOOST_ENCRYPTION_KEY 的测试访问(共享锁见 utils::test_env_lock)。
    use crate::utils::test_env_lock::ENV_LOCK;
    use serde::{Deserialize, Serialize};

    /// A fixed 32-byte key used exclusively by unit tests.
    const TEST_KEY: [u8; 32] = *b"vecboost-test-encryption-key-32b"; // pragma: allowlist secret

    #[test]
    fn test_encrypt_decrypt_hex_roundtrip() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let plaintext = b"super-secret-jwt-token";
        let encrypted = encrypt_to_hex(plaintext, &TEST_KEY).expect("encrypt");
        let decrypted = decrypt_from_hex(&encrypted, &TEST_KEY).expect("decrypt");
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn test_encrypt_decrypt_hex_empty_plaintext() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let plaintext = b"";
        let encrypted = encrypt_to_hex(plaintext, &TEST_KEY).expect("encrypt");
        let decrypted = decrypt_from_hex(&encrypted, &TEST_KEY).expect("decrypt");
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn test_encrypt_decrypt_hex_unicode() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let plaintext = "你好世界🌍".as_bytes();
        let encrypted = encrypt_to_hex(plaintext, &TEST_KEY).expect("encrypt");
        let decrypted = decrypt_from_hex(&encrypted, &TEST_KEY).expect("decrypt");
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn test_decrypt_with_wrong_key_fails() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let plaintext = b"secret-data";
        let encrypted = encrypt_to_hex(plaintext, &TEST_KEY).expect("encrypt");
        let wrong_key = *b"vecboost-wrong-encryption-key32b"; // pragma: allowlist secret
        let result = decrypt_from_hex(&encrypted, &wrong_key);
        assert!(result.is_err());
    }

    #[test]
    fn test_decrypt_invalid_hex_fails() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let result = decrypt_from_hex("not-valid-hex!", &TEST_KEY);
        assert!(result.is_err());
    }

    #[test]
    fn test_decrypt_too_short_value_fails() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // 10 hex chars = 5 bytes, less than NONCE_SIZE (24)
        let result = decrypt_from_hex("aabbccddee", &TEST_KEY);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_encryption_key_missing() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::remove_var("VECBOOST_ENCRYPTION_KEY") };
        let result = validate_encryption_key();
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_encryption_key_wrong_length() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::set_var("VECBOOST_ENCRYPTION_KEY", "tooshort") };
        let result = validate_encryption_key();
        assert!(result.is_err());
        unsafe { std::env::remove_var("VECBOOST_ENCRYPTION_KEY") };
    }

    #[test]
    fn test_validate_encryption_key_valid() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe {
            std::env::set_var(
                "VECBOOST_ENCRYPTION_KEY",
                "vecboost-test-encryption-key-32b",
            )
        };
        let result = validate_encryption_key();
        assert!(result.is_ok());
        unsafe { std::env::remove_var("VECBOOST_ENCRYPTION_KEY") };
    }

    #[test]
    fn test_read_master_key_missing() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::remove_var("VECBOOST_ENCRYPTION_KEY") };
        assert!(read_master_key().is_none());
    }

    #[test]
    fn test_read_master_key_wrong_length() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::set_var("VECBOOST_ENCRYPTION_KEY", "short") };
        assert!(read_master_key().is_none());
        unsafe { std::env::remove_var("VECBOOST_ENCRYPTION_KEY") };
    }

    #[test]
    fn test_read_master_key_valid() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe {
            std::env::set_var(
                "VECBOOST_ENCRYPTION_KEY",
                "vecboost-test-encryption-key-32b",
            )
        };
        let key = read_master_key();
        assert!(key.is_some());
        unsafe { std::env::remove_var("VECBOOST_ENCRYPTION_KEY") };
    }

    #[test]
    fn test_derive_key_produces_32_bytes() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let derived = derive_key(&TEST_KEY);
        assert!(derived.is_ok());
        assert_eq!(derived.unwrap().len(), 32);
    }

    #[test]
    fn test_encrypted_option_serde_none() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        #[derive(Serialize, Deserialize)]
        struct Cfg {
            #[serde(
                default,
                serialize_with = "encrypted_option::serialize",
                deserialize_with = "encrypted_option::deserialize"
            )]
            val: Option<String>,
        }
        let cfg = Cfg { val: None };
        let json = serde_json::to_string(&cfg).unwrap();
        let deserialized: Cfg = serde_json::from_str(&json).unwrap();
        assert!(deserialized.val.is_none());
    }

    #[test]
    fn test_encrypted_option_serde_some_no_key() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::remove_var("VECBOOST_ENCRYPTION_KEY") };
        #[derive(Serialize, Deserialize)]
        struct Cfg {
            #[serde(
                default,
                serialize_with = "encrypted_option::serialize",
                deserialize_with = "encrypted_option::deserialize"
            )]
            val: Option<String>,
        }
        let cfg = Cfg {
            val: Some("plaintext".to_string()),
        };
        let json = serde_json::to_string(&cfg).unwrap();
        let deserialized: Cfg = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.val, Some("plaintext".to_string()));
    }

    #[test]
    fn test_encrypted_option_serde_some_with_key() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe {
            std::env::set_var(
                "VECBOOST_ENCRYPTION_KEY",
                "vecboost-test-encryption-key-32b",
            )
        };
        #[derive(Serialize, Deserialize)]
        struct Cfg {
            #[serde(
                default,
                serialize_with = "encrypted_option::serialize",
                deserialize_with = "encrypted_option::deserialize"
            )]
            val: Option<String>,
        }
        let cfg = Cfg {
            val: Some("secret".to_string()),
        };
        let json = serde_json::to_string(&cfg).unwrap();
        // Encrypted value should differ from plaintext
        assert!(!json.contains("\"secret\""));
        let deserialized: Cfg = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.val, Some("secret".to_string()));
        unsafe { std::env::remove_var("VECBOOST_ENCRYPTION_KEY") };
    }

    #[test]
    fn test_encrypted_option_deserialize_none() {
        let _env_guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::remove_var("VECBOOST_ENCRYPTION_KEY") };
        #[derive(Serialize, Deserialize)]
        struct Cfg {
            #[serde(
                default,
                serialize_with = "encrypted_option::serialize",
                deserialize_with = "encrypted_option::deserialize"
            )]
            val: Option<String>,
        }
        let json = r#"{}"#;
        let deserialized: Cfg = serde_json::from_str(json).unwrap();
        assert!(deserialized.val.is_none());
    }
}