Skip to main content

lean_ctx/core/
index_bundle.rs

1//! Encrypted index bundles for the hosted Personal Index (GL #392).
2//!
3//! Packs the locally built retrieval artifacts (`bm25_index.bin.zst`,
4//! `embeddings.json` from the project's vector namespace) into one container,
5//! encrypts it client-side, and unpacks pulled bundles back into the
6//! namespace — so a fresh device gets working `ctx_semantic_search` without a
7//! local re-index.
8//!
9//! Contract: `docs/contracts/hosted-personal-index-v1.md`.
10//!
11//! ## Container format (`LCIB1`)
12//!
13//! ```text
14//! "LCIB1\n" | u32 LE manifest_len | manifest JSON | zstd(files payload)
15//! ```
16//!
17//! ## Encryption
18//!
19//! XChaCha20-Poly1305 with a 24-byte random nonce prepended to the
20//! ciphertext. The key is HKDF-SHA256-derived from the account API key —
21//! the backend stores that key only as a SHA-256 hash, so the server can
22//! never decrypt a bundle (true E2E for the operator threat model). Every
23//! logged-in device derives the same key with zero extra setup.
24
25use serde::{Deserialize, Serialize};
26use sha2::{Digest, Sha256};
27use std::path::Path;
28
29const MAGIC: &[u8; 6] = b"LCIB1\n";
30const ZSTD_LEVEL: i32 = 3;
31const NONCE_LEN: usize = 24;
32/// Hard ceiling for a decoded payload (defense against decompression bombs
33/// on pull; the server enforces its own per-bundle upload cap).
34const MAX_DECODED_BYTES: usize = 512 * 1024 * 1024;
35
36/// The two retrieval artifacts a v1 bundle carries.
37const BUNDLE_FILES: [&str; 2] = ["bm25_index.bin.zst", "embeddings.json"];
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct BundleManifest {
41    /// Format version of the container ("1").
42    pub version: u32,
43    /// Project namespace hash this bundle belongs to.
44    pub project_hash: String,
45    /// RFC 3339 creation timestamp.
46    pub created_at: String,
47    /// Engine version that produced the bundle.
48    pub engine_version: String,
49    pub files: Vec<BundleFileEntry>,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct BundleFileEntry {
54    pub name: String,
55    pub size: u64,
56    pub sha256: String,
57}
58
59#[derive(Debug, thiserror::Error)]
60pub enum BundleError {
61    #[error("no index artifacts found in {0} — run a search once (or `lean-ctx index`) to build the local index first")]
62    NothingToBundle(String),
63    #[error("not a lean-ctx index bundle (bad magic)")]
64    BadMagic,
65    #[error("corrupt bundle: {0}")]
66    Corrupt(String),
67    #[error("decryption failed — bundle was encrypted with a different account key (re-push from a logged-in device)")]
68    Decrypt,
69    #[error("io: {0}")]
70    Io(#[from] std::io::Error),
71}
72
73fn sha256_hex(data: &[u8]) -> String {
74    let mut h = Sha256::new();
75    h.update(data);
76    let digest = h.finalize();
77    let mut out = String::with_capacity(digest.len() * 2);
78    for b in digest {
79        use std::fmt::Write;
80        let _ = write!(out, "{b:02x}");
81    }
82    out
83}
84
85// ---------------------------------------------------------------------------
86// Pack / unpack (plaintext container)
87// ---------------------------------------------------------------------------
88
89/// Whether this project has any bundleable index artifacts on disk — the
90/// cheap pre-check the background auto-push (GL #392) uses to skip silently
91/// instead of erroring through [`pack`].
92#[must_use]
93pub fn local_index_present(project_root: &Path) -> bool {
94    let dir = crate::core::index_namespace::vectors_dir(project_root);
95    BUNDLE_FILES.iter().any(|name| dir.join(name).is_file())
96}
97
98/// Pack the project's index artifacts into a plaintext `LCIB1` container.
99/// Returns the container bytes and its manifest.
100pub fn pack(project_root: &Path) -> Result<(Vec<u8>, BundleManifest), BundleError> {
101    let dir = crate::core::index_namespace::vectors_dir(project_root);
102    let mut files = Vec::new();
103    let mut payload = Vec::new();
104
105    for name in BUNDLE_FILES {
106        let path = dir.join(name);
107        let Ok(data) = std::fs::read(&path) else {
108            continue;
109        };
110        files.push(BundleFileEntry {
111            name: name.to_string(),
112            size: data.len() as u64,
113            sha256: sha256_hex(&data),
114        });
115        payload.extend_from_slice(&data);
116    }
117
118    if files.is_empty() {
119        return Err(BundleError::NothingToBundle(dir.display().to_string()));
120    }
121
122    let manifest = BundleManifest {
123        version: 1,
124        // The vector-namespace hash: derived from the project *identity*
125        // (git remote / manifest name), so the same repo cloned on another
126        // device maps to the same hosted bucket.
127        project_hash: crate::core::index_namespace::namespace_hash(project_root),
128        created_at: chrono::Utc::now().to_rfc3339(),
129        engine_version: env!("CARGO_PKG_VERSION").to_string(),
130        files,
131    };
132
133    let manifest_json =
134        serde_json::to_vec(&manifest).map_err(|e| BundleError::Corrupt(e.to_string()))?;
135    let compressed = zstd::encode_all(payload.as_slice(), ZSTD_LEVEL)
136        .map_err(|e| BundleError::Corrupt(format!("zstd: {e}")))?;
137
138    let mut out = Vec::with_capacity(MAGIC.len() + 4 + manifest_json.len() + compressed.len());
139    out.extend_from_slice(MAGIC);
140    out.extend_from_slice(
141        &u32::try_from(manifest_json.len())
142            .map_err(|_| BundleError::Corrupt("manifest too large".into()))?
143            .to_le_bytes(),
144    );
145    out.extend_from_slice(&manifest_json);
146    out.extend_from_slice(&compressed);
147    Ok((out, manifest))
148}
149
150/// Parse a plaintext container without writing anything (manifest preview).
151pub fn read_manifest(container: &[u8]) -> Result<BundleManifest, BundleError> {
152    let (manifest, _payload) = split_container(container)?;
153    Ok(manifest)
154}
155
156fn split_container(container: &[u8]) -> Result<(BundleManifest, Vec<u8>), BundleError> {
157    if container.len() < MAGIC.len() + 4 || &container[..MAGIC.len()] != MAGIC {
158        return Err(BundleError::BadMagic);
159    }
160    let len_start = MAGIC.len();
161    let manifest_len = u32::from_le_bytes(
162        container[len_start..len_start + 4]
163            .try_into()
164            .map_err(|_| BundleError::Corrupt("truncated header".into()))?,
165    ) as usize;
166    let manifest_end = len_start + 4 + manifest_len;
167    if container.len() < manifest_end {
168        return Err(BundleError::Corrupt("truncated manifest".into()));
169    }
170    let manifest: BundleManifest = serde_json::from_slice(&container[len_start + 4..manifest_end])
171        .map_err(|e| BundleError::Corrupt(format!("manifest: {e}")))?;
172
173    let declared: u64 = manifest.files.iter().map(|f| f.size).sum();
174    if declared > MAX_DECODED_BYTES as u64 {
175        return Err(BundleError::Corrupt(format!(
176            "declared payload {declared} bytes exceeds the {MAX_DECODED_BYTES} byte ceiling"
177        )));
178    }
179
180    let payload = zstd::decode_all(&container[manifest_end..])
181        .map_err(|e| BundleError::Corrupt(format!("zstd: {e}")))?;
182    if payload.len() as u64 != declared {
183        return Err(BundleError::Corrupt(format!(
184            "payload size mismatch: got {}, manifest declares {declared}",
185            payload.len()
186        )));
187    }
188    Ok((manifest, payload))
189}
190
191/// Unpack a plaintext container into the project's vector namespace. Every
192/// file's SHA-256 is verified before anything is written; writes are atomic
193/// (tmp + rename) so a torn pull can never corrupt a working local index.
194pub fn unpack(project_root: &Path, container: &[u8]) -> Result<BundleManifest, BundleError> {
195    let (manifest, payload) = split_container(container)?;
196
197    let dir = crate::core::index_namespace::vectors_dir(project_root);
198    std::fs::create_dir_all(&dir)?;
199
200    // Verify all hashes first — only then start writing.
201    let mut offset = 0usize;
202    let mut verified: Vec<(&BundleFileEntry, &[u8])> = Vec::with_capacity(manifest.files.len());
203    for entry in &manifest.files {
204        let size = usize::try_from(entry.size)
205            .map_err(|_| BundleError::Corrupt("file size overflow".into()))?;
206        let end = offset
207            .checked_add(size)
208            .filter(|&e| e <= payload.len())
209            .ok_or_else(|| BundleError::Corrupt("file extends past payload".into()))?;
210        let data = &payload[offset..end];
211        if sha256_hex(data) != entry.sha256 {
212            return Err(BundleError::Corrupt(format!(
213                "sha256 mismatch for {}",
214                entry.name
215            )));
216        }
217        // File names are fixed by the format — never trust path components.
218        if !BUNDLE_FILES.contains(&entry.name.as_str()) {
219            return Err(BundleError::Corrupt(format!(
220                "unexpected file in bundle: {}",
221                entry.name
222            )));
223        }
224        verified.push((entry, data));
225        offset = end;
226    }
227
228    for (entry, data) in verified {
229        let target = dir.join(&entry.name);
230        let tmp = dir.join(format!(".{}.pull.tmp", entry.name));
231        std::fs::write(&tmp, data)?;
232        std::fs::rename(&tmp, &target)?;
233    }
234    Ok(manifest)
235}
236
237// ---------------------------------------------------------------------------
238// Encryption (XChaCha20-Poly1305, HKDF-SHA256 account key)
239// ---------------------------------------------------------------------------
240
241/// Derive the per-account bundle key from the API key. The server only ever
242/// stores `sha256(api_key)`, so this key is unknowable server-side.
243#[must_use]
244pub fn derive_key(api_key: &str) -> [u8; 32] {
245    let hk = hkdf::Hkdf::<Sha256>::new(Some(b"leanctx"), api_key.as_bytes());
246    let mut okm = [0u8; 32];
247    hk.expand(b"index-bundle-v1", &mut okm)
248        .expect("32 bytes is a valid HKDF-SHA256 output length");
249    okm
250}
251
252/// Encrypt a plaintext container. Output: `nonce (24B) || ciphertext`.
253pub fn encrypt(container: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, BundleError> {
254    use chacha20poly1305::aead::{Aead, KeyInit};
255    use chacha20poly1305::{XChaCha20Poly1305, XNonce};
256
257    let mut nonce_bytes = [0u8; NONCE_LEN];
258    getrandom::fill(&mut nonce_bytes)
259        .map_err(|e| BundleError::Corrupt(format!("nonce generation: {e}")))?;
260    let cipher = XChaCha20Poly1305::new(key.into());
261    let ciphertext = cipher
262        .encrypt(XNonce::from_slice(&nonce_bytes), container)
263        .map_err(|_| BundleError::Corrupt("encryption failed".into()))?;
264
265    let mut out = Vec::with_capacity(NONCE_LEN + ciphertext.len());
266    out.extend_from_slice(&nonce_bytes);
267    out.extend_from_slice(&ciphertext);
268    Ok(out)
269}
270
271/// Decrypt `nonce || ciphertext` back into the plaintext container.
272pub fn decrypt(blob: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, BundleError> {
273    use chacha20poly1305::aead::{Aead, KeyInit};
274    use chacha20poly1305::{XChaCha20Poly1305, XNonce};
275
276    if blob.len() <= NONCE_LEN {
277        return Err(BundleError::Corrupt("blob shorter than nonce".into()));
278    }
279    let (nonce, ciphertext) = blob.split_at(NONCE_LEN);
280    let cipher = XChaCha20Poly1305::new(key.into());
281    cipher
282        .decrypt(XNonce::from_slice(nonce), ciphertext)
283        .map_err(|_| BundleError::Decrypt)
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    /// Build a fake project with index artifacts and return (dir, root).
291    fn project_with_index() -> (tempfile::TempDir, std::path::PathBuf) {
292        let data_dir = tempfile::tempdir().unwrap();
293        let root = data_dir.path().join("proj");
294        std::fs::create_dir_all(root.join(".git")).unwrap();
295        std::env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
296
297        let vectors = crate::core::index_namespace::vectors_dir(&root);
298        std::fs::create_dir_all(&vectors).unwrap();
299        std::fs::write(vectors.join("bm25_index.bin.zst"), b"fake-bm25-bytes").unwrap();
300        std::fs::write(vectors.join("embeddings.json"), br#"{"entries":[]}"#).unwrap();
301        (data_dir, root)
302    }
303
304    #[test]
305    fn pack_unpack_roundtrip_preserves_artifacts() {
306        let _env = crate::core::data_dir::test_env_lock();
307        let (data_dir, root) = project_with_index();
308
309        let (container, manifest) = pack(&root).unwrap();
310        assert_eq!(manifest.version, 1);
311        assert_eq!(manifest.files.len(), 2);
312
313        // Wipe the local artifacts, then restore from the bundle.
314        let vectors = crate::core::index_namespace::vectors_dir(&root);
315        std::fs::remove_file(vectors.join("bm25_index.bin.zst")).unwrap();
316        std::fs::remove_file(vectors.join("embeddings.json")).unwrap();
317
318        let restored = unpack(&root, &container).unwrap();
319        assert_eq!(restored.project_hash, manifest.project_hash);
320        assert_eq!(
321            std::fs::read(vectors.join("bm25_index.bin.zst")).unwrap(),
322            b"fake-bm25-bytes"
323        );
324        assert_eq!(
325            std::fs::read(vectors.join("embeddings.json")).unwrap(),
326            br#"{"entries":[]}"#
327        );
328        drop(data_dir);
329    }
330
331    #[test]
332    fn pack_without_artifacts_is_a_clear_error() {
333        let _env = crate::core::data_dir::test_env_lock();
334        let data_dir = tempfile::tempdir().unwrap();
335        let root = data_dir.path().join("empty");
336        std::fs::create_dir_all(root.join(".git")).unwrap();
337        std::env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
338
339        match pack(&root) {
340            Err(BundleError::NothingToBundle(_)) => {}
341            other => panic!("expected NothingToBundle, got {other:?}"),
342        }
343    }
344
345    #[test]
346    fn tampered_payload_is_rejected() {
347        let _env = crate::core::data_dir::test_env_lock();
348        let (_data_dir, root) = project_with_index();
349        let (container, _) = pack(&root).unwrap();
350
351        // Re-compress a tampered payload behind the original manifest: the
352        // per-file sha256 must catch it.
353        let (manifest, mut payload) = split_container(&container).unwrap();
354        payload[0] ^= 0xFF;
355        let manifest_json = serde_json::to_vec(&manifest).unwrap();
356        let mut forged = Vec::new();
357        forged.extend_from_slice(MAGIC);
358        forged.extend_from_slice(&(u32::try_from(manifest_json.len()).unwrap()).to_le_bytes());
359        forged.extend_from_slice(&manifest_json);
360        forged.extend_from_slice(&zstd::encode_all(payload.as_slice(), 3).unwrap());
361
362        match unpack(&root, &forged) {
363            Err(BundleError::Corrupt(msg)) => assert!(msg.contains("sha256"), "{msg}"),
364            other => panic!("expected Corrupt(sha256), got {other:?}"),
365        }
366    }
367
368    #[test]
369    fn bad_magic_is_rejected() {
370        match read_manifest(b"not-a-bundle") {
371            Err(BundleError::BadMagic) => {}
372            other => panic!("expected BadMagic, got {other:?}"),
373        }
374    }
375
376    #[test]
377    fn encrypt_decrypt_roundtrip_and_wrong_key_fails() {
378        let key = derive_key("test-api-key-1");
379        let plaintext = b"LCIB1\n-fake-container-bytes".to_vec();
380
381        let blob = encrypt(&plaintext, &key).unwrap();
382        assert_ne!(&blob[NONCE_LEN..], plaintext.as_slice());
383        assert_eq!(decrypt(&blob, &key).unwrap(), plaintext);
384
385        let wrong = derive_key("test-api-key-2");
386        match decrypt(&blob, &wrong) {
387            Err(BundleError::Decrypt) => {}
388            other => panic!("expected Decrypt error, got {other:?}"),
389        }
390    }
391
392    #[test]
393    fn key_derivation_is_stable_and_key_separated() {
394        // Same input ⇒ same key (multi-device); different input ⇒ different key.
395        assert_eq!(derive_key("k"), derive_key("k"));
396        assert_ne!(derive_key("k"), derive_key("k2"));
397        // And never the raw key material itself.
398        assert_ne!(derive_key("k").as_slice(), b"k".as_slice());
399    }
400
401    #[test]
402    fn nonces_are_unique_per_encryption() {
403        let key = derive_key("k");
404        let a = encrypt(b"same", &key).unwrap();
405        let b = encrypt(b"same", &key).unwrap();
406        assert_ne!(a[..NONCE_LEN], b[..NONCE_LEN]);
407    }
408}