AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
hub client: anti-rollback, decompression-bomb bound, file:// device guard (#1733)
xerj-org979b0c48e149
diff --git a/engine/crates/xerj-hub/src/catalogue.rs b/engine/crates/xerj-hub/src/catalogue.rsindex d67f265be..c99548d66 100644--- a/engine/crates/xerj-hub/src/catalogue.rs+++ b/engine/crates/xerj-hub/src/catalogue.rs@@ -516,6 +516,24 @@ fn fetch_and_store(hub_url: &str, cache_file: &Path, etag_file: &Path) -> Result// Only trusted bytes get parsed and cached.let cat = parse_catalogue(&body)?;++ // Anti-rollback. A signature proves the hub made these bytes, not that they+ // are the hub's CURRENT catalogue: every catalogue the hub ever signed+ // verifies for ever. Whoever answers for the hub URL (a compromised mirror or+ // CDN, a captive proxy, an `XERJ_HUB_URL` someone else chose) could otherwise+ // replay an older signed catalogue, and `hub sync` would then "update" every+ // cached pack back to an older pin and delete the newer one. A catalogue+ // generated before the copy already cached is refused and the cache kept.+ if let Some(prev) = read_cached(cache_file) {+ if is_rollback(&cat.generated_at, &prev.generated_at) {+ bail!(+ "refusing a catalogue generated {} — older than the cached one ({}); a signed \+ but older catalogue is a rollback, so the cache was kept",+ cat.generated_at,+ prev.generated_at+ );+ }+ }if let Some(parent) = cache_file.parent() {fs::create_dir_all(parent).with_context(|| format!("create cache dir {}", parent.display()))?;@@ -535,6 +553,20 @@ fn fetch_and_store(hub_url: &str, cache_file: &Path, etag_file: &Path) -> ResultOk(cat)}+/// True when `fetched` was generated before `cached` — a rollback. Both are the+/// signed `generated_at` (RFC 3339). An unparsable cached time cannot anchor a+/// comparison, so it never blocks; an unparsable fetched time against a+/// parsable cached one cannot be shown to be newer, so it is refused.+fn is_rollback(fetched: &str, cached: &str) -> bool {+ let Ok(cached) = chrono::DateTime::parse_from_rfc3339(cached.trim()) else {+ return false;+ };+ match chrono::DateTime::parse_from_rfc3339(fetched.trim()) {+ Ok(fetched) => fetched < cached,+ Err(_) => true,+ }+}+/// The response's `Content-Type`, or `no content type`.fn content_type(resp: &reqwest::blocking::Response) -> String {resp.headers()@@ -1090,4 +1122,52 @@ mod tests {assert!(msg.contains("signature does not verify"), "{msg}");assert!(!cache.path().join(CACHE_FILE).exists(), "nothing cached");}++ #[test]+ fn an_older_signed_catalogue_is_refused_as_a_rollback() {+ let _guard = ENV_LOCK.lock().unwrap();+ let fx = tempfile::tempdir().unwrap();+ let inputs = two_inputs(fx.path());+ let (seed, public) = keypair();++ // The client already holds today's catalogue (aged, so it would refresh).+ let (new_cat, new_sig) = build_catalogue(&inputs, "2026-10-14T00:00:00Z", &seed).unwrap();+ let new_bytes = canonical_json(&new_cat).unwrap();+ let cache = tempfile::tempdir().unwrap();+ seed_cache(cache.path(), &new_bytes, &new_sig);+ age_file(&cache.path().join(CACHE_FILE), 48 * 3600);++ // The hub URL answers with an OLDER catalogue, genuinely signed by the+ // trusted key — a replay of what the hub published two weeks earlier.+ let (old_cat, old_sig) = build_catalogue(&inputs, "2026-10-01T00:00:00Z", &seed).unwrap();+ let old_bytes = canonical_json(&old_cat).unwrap();++ std::env::set_var("XERJ_HUB_PUBKEY", &public);+ let (url, handle) = spawn_hub(old_bytes.clone(), old_sig.clone());+ let err = refresh_catalogue(&url, cache.path()).expect_err("a rollback is refused");+ handle.join().unwrap();+ let (url, handle) = spawn_hub(old_bytes, old_sig);+ let served = load_catalogue(&url, cache.path(), false).expect("cached copy kept");+ std::env::remove_var("XERJ_HUB_PUBKEY");+ handle.join().unwrap();++ assert!(format!("{err:#}").contains("rollback"), "{err:#}");+ assert_eq!(served.generated_at, "2026-10-14T00:00:00Z");+ let on_disk = fs::read(cache.path().join(CACHE_FILE)).unwrap();+ assert_eq!(on_disk, new_bytes, "the newer cache is untouched");+ }++ #[test]+ fn rollback_comparison_rules() {+ assert!(is_rollback("2026-10-01T00:00:00Z", "2026-10-14T00:00:00Z"));+ assert!(!is_rollback("2026-10-14T00:00:00Z", "2026-10-14T00:00:00Z"));+ assert!(!is_rollback("2026-10-15T00:00:00Z", "2026-10-14T00:00:00Z"));+ // Same instant, different offset: not older.+ assert!(!is_rollback(+ "2026-10-14T02:00:00+02:00",+ "2026-10-14T00:00:00Z"+ ));+ assert!(is_rollback("not a time", "2026-10-14T00:00:00Z"));+ assert!(!is_rollback("2026-10-01T00:00:00Z", "not a time"));+ }}diff --git a/engine/crates/xerj-hub/src/cli.rs b/engine/crates/xerj-hub/src/cli.rsindex 8f8b717ee..f0b1be9a4 100644--- a/engine/crates/xerj-hub/src/cli.rs+++ b/engine/crates/xerj-hub/src/cli.rs@@ -984,14 +984,29 @@ pub fn valid_slug(s: &str) -> bool {/// of bytes written.fn fetch_to(url: &str, dest: &Path, max_bytes: u64) -> Result<u64> {if let Some(path) = url.strip_prefix("file://") {- let sz = fs::metadata(path)- .with_context(|| format!("stat {path}"))?- .len();+ // A regular file only. `/dev/zero` (or a FIFO, `/dev/stdin`, …) stats as+ // 0 bytes, passed the size check, and was then `fs::copy`'d without end,+ // filling the disk under `~/.xerj/hub`. The read is bounded as well, in+ // case the file grows between the stat and the read.+ let meta = fs::metadata(path).with_context(|| format!("stat {path}"))?;+ if !meta.is_file() {+ bail!("{path} is not a regular file");+ }+ let sz = meta.len();if sz > max_bytes {bail!("{path} is {sz} bytes, over the {max_bytes}-byte cap");}- let n = fs::copy(path, dest).with_context(|| format!("copy {path}"))?;- return Ok(n);+ let mut buf = Vec::new();+ fs::File::open(path)+ .with_context(|| format!("open {path}"))?+ .take(max_bytes + 1)+ .read_to_end(&mut buf)+ .with_context(|| format!("read {path}"))?;+ if buf.len() as u64 > max_bytes {+ bail!("{path} grew past the {max_bytes}-byte cap while it was read");+ }+ fs::write(dest, &buf).with_context(|| format!("write {}", dest.display()))?;+ return Ok(buf.len() as u64);}let resp = reqwest::blocking::get(url).with_context(|| format!("GET {url}"))?;let status = resp.status();@@ -1593,6 +1608,19 @@ mod tests {assert!(!dst.exists(), "nothing is written when over the cap");}+ #[cfg(unix)]+ #[test]+ fn fetch_to_refuses_a_device_that_stats_as_empty() {+ // `/dev/zero` stats as 0 bytes. It used to pass the cap and then be copied+ // without end (a signed catalogue `pack_url: "file:///dev/zero"` fills the+ // disk). A non-regular file is refused before a byte is read.+ let tmp = tempfile::tempdir().unwrap();+ let dst = tmp.path().join("dst.bin");+ let err = fetch_to("file:///dev/zero", &dst, 1024).unwrap_err();+ assert!(err.to_string().contains("not a regular file"), "{err}");+ assert!(!dst.exists(), "nothing is written");+ }+#[test]fn valid_slug_accepts_real_slugs_and_rejects_traversal() {for ok in ["mini-c", "lz4", "a", "xerj-blogposts", "a.b_c-1", "x9"] {diff --git a/engine/crates/xerj-hub/src/pack.rs b/engine/crates/xerj-hub/src/pack.rsindex b1adb517b..fffe6c373 100644--- a/engine/crates/xerj-hub/src/pack.rs+++ b/engine/crates/xerj-hub/src/pack.rs@@ -45,6 +45,18 @@ const FILES_JSONL: &str = "files.jsonl";const SNAPSHOT_DIR: &str = "snapshot";/// zstd level for the archive — 9 matches the builder recipe (§2 step 5).const ZSTD_LEVEL: i32 = 9;+/// Largest decompressed tar a reader accepts. The archive itself is capped by+/// `AUTO_PULL_MAX_BYTES` (50 MiB) before it is read, but zstd reaches ratios of+/// several thousand to one on repetitive input (1 GiB of zeros is ~32 KiB at+/// level 9), so a capped archive could still expand to terabytes in memory. A+/// signature only says who made the pack, not that the maker's key was never+/// stolen or its build never fed a bad snapshot: the reader bounds what it+/// allocates whatever the signature says. 1 GiB is twenty times the pull cap —+/// far above what a snapshot of already-compressed segment files expands to.+const MAX_UNPACKED_BYTES: u64 = 1 << 30;+/// Largest number of tar entries a reader accepts (a pack holds four fixed+/// members plus the snapshot's files — a few hundred in practice).+const MAX_MEMBERS: usize = 100_000;/// One line of `files.jsonl`: an indexed source file with its per-path licence./// `read_and_verify_pack` does not parse this (it is extracted verbatim); it is@@ -146,6 +158,26 @@ pub fn read_and_verify_pack(expected_sha256: &str,pubkey_hex: &str,dest: &Path,+) -> Result<PackManifest> {+ read_and_verify_pack_bounded(+ archive,+ sig,+ expected_sha256,+ pubkey_hex,+ dest,+ MAX_UNPACKED_BYTES,+ )+}++/// [`read_and_verify_pack`] with the decompressed-size bound as a parameter, so+/// a test can prove the bound with a small archive.+fn read_and_verify_pack_bounded(+ archive: &Path,+ sig: &Path,+ expected_sha256: &str,+ pubkey_hex: &str,+ dest: &Path,+ max_unpacked: u64,) -> Result<PackManifest> {// The whole archive is read into memory because the detached signature is over// the complete archive bytes (ed25519 verifies a contiguous message); the hub's@@ -164,7 +196,8 @@ pub fn read_and_verify_pack(verify_bytes(&archive_bytes, sig_hex.trim(), pubkey_hex).context("pack signature")?;// 3. Decompress and load the members (still nothing written to dest).- let tar_bytes = zstd::decode_all(archive_bytes.as_slice()).context("zstd decompress")?;+ // Bounded: never allocate more than `max_unpacked` however well it compresses.+ let tar_bytes = decompress_bounded(&archive_bytes, max_unpacked)?;drop(archive_bytes);let members = read_members(&tar_bytes)?;@@ -293,11 +326,30 @@ fn rel_to_forward_slash(rel: &Path) -> Result<String> {Ok(parts.join("/"))}+/// zstd-decompress `archive`, refusing output larger than `max` bytes. Reads at+/// most `max + 1` bytes from the decoder, so a decompression bomb costs at most+/// that much memory before it is refused.+fn decompress_bounded(archive: &[u8], max: u64) -> Result<Vec<u8>> {+ let decoder = zstd::stream::read::Decoder::new(archive).context("zstd decompress")?;+ let mut out = Vec::new();+ decoder+ .take(max.saturating_add(1))+ .read_to_end(&mut out)+ .context("zstd decompress")?;+ if out.len() as u64 > max {+ bail!("pack decompresses to more than {max} bytes; refusing to extract it");+ }+ Ok(out)+}+/// Read every regular tar entry into a map, keyed by a sanitised archive path.fn read_members(tar_bytes: &[u8]) -> Result<BTreeMap<String, Vec<u8>>> {let mut archive = tar::Archive::new(std::io::Cursor::new(tar_bytes));let mut members: BTreeMap<String, Vec<u8>> = BTreeMap::new();- for entry in archive.entries().context("read tar entries")? {+ for (n, entry) in archive.entries().context("read tar entries")?.enumerate() {+ if n >= MAX_MEMBERS {+ bail!("pack holds more than {MAX_MEMBERS} entries; refusing to extract it");+ }let mut entry = entry.context("read tar entry")?;if entry.header().entry_type().is_dir() {continue;@@ -1020,4 +1072,41 @@ mod tests {);}}++ #[test]+ fn a_pack_that_decompresses_past_the_bound_is_refused_before_extraction() {+ // A validly signed pack whose snapshot is 8 MiB of zeros: the archive is a+ // few KiB (zstd's ratio on repetitive input is in the thousands), so the+ // 50 MiB download cap alone does not bound what the reader allocates.+ // Before the bound, `zstd::decode_all` inflated whatever the archive held.+ let tmp = tempfile::tempdir().unwrap();+ let snap = make_snapshot(tmp.path());+ fs::write(snap.join("idx/zeros.bin"), vec![0u8; 8 << 20]).unwrap();+ let out = tmp.path().join("bomb.hubpack.tar.zst");+ let (seed, public) = generate_keypair().unwrap();+ let (sha, bytes) = write_pack(+ &out,+ &sample_manifest(),+ &sample_defs(),+ &sample_files(),+ &snap,+ &seed,+ )+ .unwrap();+ assert!(bytes < 64 * 1024, "the archive is tiny: {bytes} bytes");+ let sig = sig_path_for(&out);++ let dest = tmp.path().join("dest");+ let err =+ read_and_verify_pack_bounded(&out, &sig, &sha, &public, &dest, 1 << 20).unwrap_err();+ assert!(+ format!("{err:#}").contains("decompresses to more than"),+ "{err:#}"+ );+ assert!(dir_is_empty_or_absent(&dest), "nothing extracted");++ // The same pack under a bound it fits in still verifies and extracts.+ read_and_verify_pack_bounded(&out, &sig, &sha, &public, &dest, 16 << 20).unwrap();+ assert!(dest.join("snapshot/idx/zeros.bin").exists());+ }}