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: set HUB_PUBKEY_HEX to the public half of HUB_SIGNING_SEED (#1505)
xerj-org5bb9e17ebea4
diff --git a/.github/workflows/hub-packs.yml b/.github/workflows/hub-packs.ymlindex 101380983..d75b8f07b 100644--- a/.github/workflows/hub-packs.yml+++ b/.github/workflows/hub-packs.yml@@ -39,10 +39,13 @@# verify; clients independently refuse any pack whose sha256 or signature fails# (`xerj hub pull`), and extract nothing before both pass.#-# DORMANT UNTIL THE KEY EXISTS-# HUB_PUBKEY_HEX is "" until the hub signing key is generated and committed.-# Until then the `preflight` job reports "dormant" and every publishing job is-# skipped; the re-pin job does not need the key and runs regardless.+# DORMANT WITHOUT A KEY+# HUB_PUBKEY_HEX holds the public half of HUB_SIGNING_SEED (derived by+# hub-pubkey.yml, committed in #1505). On a branch where it is empty (one+# that predates that commit) the `preflight` job reports "dormant" and every+# publishing job is skipped; the re-pin job does not need the key and runs+# regardless. The key and the secret change only together; preflight fails+# if they disagree.## DEPLOY (opt-in)# The catalogue job always builds, checks and uploads the signed catalogue as an@@ -288,8 +291,8 @@ jobs:if: needs.plan.result == 'success' && needs.plan.outputs.count != '0'runs-on: ubuntu-latest# The repo-wide ceiling (.github/scripts/workflow-timeout-guard.py, 1..90).- # This pipeline has not run for real yet (HUB_PUBKEY_HEX is unset), so there- # is no measured job time to justify more; if a real pack needs longer, that+ # This pipeline had never run for real before HUB_PUBKEY_HEX was committed,+ # so there is no measured job time to justify more; if a real pack needs longer, that# is a measured case for raising MAX_TIMEOUT there, not an exception here.timeout-minutes: 90permissions:diff --git a/engine/crates/xerj-common/src/hub.rs b/engine/crates/xerj-common/src/hub.rsindex cbe235940..f9b0959e3 100644--- a/engine/crates/xerj-common/src/hub.rs+++ b/engine/crates/xerj-common/src/hub.rs@@ -36,21 +36,44 @@ pub const AUTO_PULL_MAX_BYTES: u64 = 50 * 1024 * 1024;/// The local pack cache is pruned (least-recently-used) to stay under this.pub const DISK_BUDGET_BYTES: u64 = 4 * 1024 * 1024 * 1024;-/// Hex of the ed25519 public key the hub signs catalogues and packs with.-/// Filled when the hub signing key is generated (Step 2 / CI). Overridable by-/// the `XERJ_HUB_PUBKEY` environment variable for tests only.-pub const HUB_PUBKEY_HEX: &str = "";--/// True when this build can verify hub catalogues and packs: a key is compiled-/// in ([`HUB_PUBKEY_HEX`]) or supplied through `XERJ_HUB_PUBKEY` (tests). A-/// build without one cannot use Corpus Hub packs at all, so the hub surfaces-/// (`xerj ask`, `xerj hub sync|pull`, the MCP hub tools, `xerj init`'s hub-/// skill) say so plainly instead of failing on whatever the network returns.+/// Hex of the ed25519 public key every hub catalogue and pack must verify+/// against: the public half of the `HUB_SIGNING_SEED` CI secret, derived from+/// it by `.github/workflows/hub-pubkey.yml` (run 38869497662, #1494).+///+/// It changes ONLY together with that secret. Rotating the seed without this+/// constant (or the other way round) makes every client refuse every pack;+/// `hub-packs.yml` and `hub-pubkey.yml` both compare the two and fail loudly on+/// a mismatch. Tests point the client at a throwaway key with the+/// `XERJ_HUB_PUBKEY` environment variable — see [`hub_pubkey`].+pub const HUB_PUBKEY_HEX: &str = "b68899321ec01ad8d0130d6e4790d9c75ffbc03bb0271f0a1522114c43562936";++/// The `XERJ_HUB_PUBKEY` value that makes this process behave as a build with+/// no hub key (tests only): the no-key paths stay reachable now that a real key+/// is compiled in. It can only take capability away — with no key every hub+/// surface refuses to fetch or extract anything, it never skips a check.+pub const HUB_PUBKEY_NONE: &str = "none";++/// The key to verify hub catalogues and packs with: a non-empty+/// `XERJ_HUB_PUBKEY` (tests) wins over the compiled-in [`HUB_PUBKEY_HEX`].+/// `None` means "this build cannot verify anything": the override is+/// [`HUB_PUBKEY_NONE`], or no key is compiled in. Callers refuse rather than+/// proceed unverified.+pub fn hub_pubkey() -> Option<String> {+ match std::env::var("XERJ_HUB_PUBKEY") {+ Ok(k) if k.trim().eq_ignore_ascii_case(HUB_PUBKEY_NONE) => None,+ Ok(k) if !k.trim().is_empty() => Some(k.trim().to_string()),+ _ => Some(HUB_PUBKEY_HEX.to_string()).filter(|k| !k.is_empty()),+ }+}++/// True when this build can verify hub catalogues and packs, i.e. when+/// [`hub_pubkey`] has a key: the compiled-in [`HUB_PUBKEY_HEX`], or a test+/// `XERJ_HUB_PUBKEY`. With `XERJ_HUB_PUBKEY=none` ([`HUB_PUBKEY_NONE`]) it is+/// false, and the hub surfaces (`xerj ask`, `xerj hub sync|pull`, the MCP hub+/// tools, `xerj init`'s hub skill) say plainly that the hub is unavailable+/// instead of failing on whatever the network returns.pub fn hub_key_configured() -> bool {- !HUB_PUBKEY_HEX.is_empty()- || std::env::var("XERJ_HUB_PUBKEY")- .map(|k| !k.trim().is_empty())- .unwrap_or(false)+ hub_pubkey().is_some()}/// What every hub surface says in a build with no hub key.@@ -318,6 +341,28 @@ mod tests {use super::*;use serde_json::json;+ #[test]+ fn the_compiled_in_hub_key_is_32_bytes_of_lower_hex() {+ // The workflows read it with a `[0-9a-fA-F]*` sed and compare lower-case;+ // ed25519.sh and verify_bytes both want exactly 64 hex characters.+ assert_eq!(HUB_PUBKEY_HEX.len(), 64, "{HUB_PUBKEY_HEX}");+ assert!(+ HUB_PUBKEY_HEX+ .bytes()+ .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),+ "{HUB_PUBKEY_HEX}"+ );+ }++ #[test]+ fn the_hub_key_stays_on_the_one_line_the_workflows_read() {+ // hub-packs.yml and hub-pubkey.yml extract the key with a single-line+ // sed over this file. If a reformat ever wrapped the declaration, they+ // would read "" and go quietly dormant instead of publishing.+ let line = format!("\npub const HUB_PUBKEY_HEX: &str = \"{HUB_PUBKEY_HEX}\";\n");+ assert!(include_str!("hub.rs").contains(&line), "{line}");+ }+#[test]fn licence_class_is_kebab_case() {assert_eq!(diff --git a/engine/crates/xerj-hub/src/catalogue.rs b/engine/crates/xerj-hub/src/catalogue.rsindex 59c289cfb..1bc8b0873 100644--- a/engine/crates/xerj-hub/src/catalogue.rs+++ b/engine/crates/xerj-hub/src/catalogue.rs@@ -31,7 +31,7 @@ use anyhow::{anyhow, bail, Context, Result};use serde::Deserialize;use xerj_autoindex::harvest::sign::{sign_bytes, verify_bytes};use xerj_common::hub::{- Catalogue, CatalogueEntry, LicenceClass, CATALOGUE_FORMAT_VERSION, HUB_PUBKEY_HEX,+ hub_pubkey, Catalogue, CatalogueEntry, LicenceClass, CATALOGUE_FORMAT_VERSION,};/// Path of the catalogue under the hub's API root.@@ -415,17 +415,6 @@ fn cache_is_fresh(cache_file: &Path) -> bool {}}-/// The pubkey to verify with: `XERJ_HUB_PUBKEY` (tests), else the compiled-in-/// [`HUB_PUBKEY_HEX`]. `None` when neither is set — the real key lands later, so-/// an empty configured key means "skip verification with a warning", never a-/// hard failure.-fn configured_pubkey() -> Option<String> {- std::env::var("XERJ_HUB_PUBKEY")- .ok()- .and_then(|s| non_empty(Some(&s)))- .or_else(|| non_empty(Some(HUB_PUBKEY_HEX)))-}-/// Warn when the cached copy being served is a day or more old.fn warn_if_old(cat: &Catalogue) {if let Ok(generated) = chrono::DateTime::parse_from_rfc3339(&cat.generated_at) {@@ -442,9 +431,16 @@ fn warn_if_old(cat: &Catalogue) {}/// Fetch, verify and cache the catalogue. The signature guards the replacement:-/// the fetched bytes are only written to the cache after they verify (or after a-/// deliberate, warned skip when no key is configured).+/// the fetched bytes are only written to the cache after they verify against+/// [`hub_pubkey`]. With no key (`XERJ_HUB_PUBKEY=none`, or a build without one)+/// nothing is fetched at all: there is no unverified path into the cache.fn fetch_and_store(hub_url: &str, cache_file: &Path, etag_file: &Path) -> Result<Catalogue> {+ let Some(pubkey) = hub_pubkey() else {+ bail!(+ "no hub public key is configured, so the hub catalogue cannot be verified; \+ nothing was fetched"+ );+ };let base = hub_url.trim_end_matches('/');let cat_url = format!("{base}/{CATALOGUE_API_PATH}");let sig_url = format!("{cat_url}.sig");@@ -504,14 +500,8 @@ fn fetch_and_store(hub_url: &str, cache_file: &Path, etag_file: &Path) -> Result.to_string();// Verify BEFORE these bytes are allowed anywhere near the cache.- match configured_pubkey() {- Some(key) => verify_bytes(&body, &sig_hex, &key)- .context("catalogue signature did not verify; refusing to replace the cache")?,- None => eprintln!(- "xerj hub: no hub public key configured (HUB_PUBKEY_HEX empty, XERJ_HUB_PUBKEY \- unset) — caching the catalogue WITHOUT verifying its signature"- ),- }+ verify_bytes(&body, &sig_hex, &pubkey)+ .context("catalogue signature did not verify; refusing to replace the cache")?;// Only trusted bytes get parsed and cached.let cat = parse_catalogue(&body)?;@@ -972,25 +962,49 @@ mod tests {}#[test]- fn load_without_a_key_skips_verification_rather_than_failing() {+ fn load_with_no_key_fetches_nothing_and_caches_nothing() {let _guard = ENV_LOCK.lock().unwrap();- // no XERJ_HUB_PUBKEY, and HUB_PUBKEY_HEX is empty on this branch, so the- // loader must cache the fetched copy WITHOUT verifying — not hard-fail.+ // The loader used to fail OPEN here (cache the fetched copy unverified,+ // with a warning). With no key it now refuses before dialing the hub.+ std::env::set_var("XERJ_HUB_PUBKEY", xerj_common::hub::HUB_PUBKEY_NONE);+ let hub = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ hub.set_nonblocking(true).unwrap();+ let url = format!("http://{}", hub.local_addr().unwrap());+ let cache = tempfile::tempdir().unwrap();++ let err = load_catalogue(&url, cache.path(), false).unwrap_err();std::env::remove_var("XERJ_HUB_PUBKEY");++ assert!(+ format!("{err:#}").contains("no hub public key"),+ "the error says why: {err:#}"+ );assert!(- HUB_PUBKEY_HEX.is_empty(),- "precondition: no compiled-in key"+ matches!(hub.accept(), Err(e) if e.kind() == std::io::ErrorKind::WouldBlock),+ "nothing may be fetched without a key");+ assert!(!cache.path().join(CACHE_FILE).exists(), "nothing cached");+ }+ #[test]+ fn the_compiled_in_key_verifies_and_refuses_a_test_signed_catalogue() {+ let _guard = ENV_LOCK.lock().unwrap();+ // No override: the shipping key (HUB_PUBKEY_HEX) is what verifies. A+ // catalogue signed by any other key — here a throwaway test key — must be+ // refused and must not reach the cache.+ std::env::remove_var("XERJ_HUB_PUBKEY");let fx = tempfile::tempdir().unwrap();- let (good_bytes, _good_sig, _public) = fixture_bytes(fx.path());+ let (good_bytes, good_sig, _public) = fixture_bytes(fx.path());let cache = tempfile::tempdir().unwrap();- // the sig is irrelevant here: with no key we never check it- let (url, handle) = spawn_hub(good_bytes.clone(), "00".repeat(64));+ let (url, handle) = spawn_hub(good_bytes, good_sig);- let cat = load_catalogue(&url, cache.path(), false).expect("unverified fetch is allowed");+ let err = load_catalogue(&url, cache.path(), false).unwrap_err();handle.join().unwrap();- assert_eq!(cat.corpora.len(), 2);+ let msg = format!("{err:#}");+ // "does not verify" (not a parse error) also proves the constant parses+ // as a 32-byte key in the very function the client verifies with.+ assert!(msg.contains("signature does not verify"), "{msg}");+ assert!(!cache.path().join(CACHE_FILE).exists(), "nothing cached");}}diff --git a/engine/crates/xerj-hub/src/cli.rs b/engine/crates/xerj-hub/src/cli.rsindex 5b16fd526..a10e97b5d 100644--- a/engine/crates/xerj-hub/src/cli.rs+++ b/engine/crates/xerj-hub/src/cli.rs@@ -32,7 +32,7 @@ use serde_json::{json, Value};use xerj_common::hub::{render, Answer, CatalogueEntry, LicenceClass, PackIndex, PackManifest, PackSource,- AUTO_PULL_MAX_BYTES, DEFAULT_HUB_URL, DISK_BUDGET_BYTES, HUB_PUBKEY_HEX, PACK_FORMAT_VERSION,+ AUTO_PULL_MAX_BYTES, DEFAULT_HUB_URL, DISK_BUDGET_BYTES, PACK_FORMAT_VERSION,};use xerj_common::xccode::manifest::read_hub_manifest;use xerj_common::xccode::state;@@ -1379,23 +1379,18 @@ pub(crate) fn hub_home() -> PathBuf {lockfile::default_hub_root()}-/// The hub's ed25519 public key: `XERJ_HUB_PUBKEY` (tests) else the compiled-in-/// [`HUB_PUBKEY_HEX`]. An empty key is a hard error — an unverifiable pack is-/// never extracted.+/// The hub's ed25519 public key ([`xerj_common::hub::hub_pubkey`]: a test+/// `XERJ_HUB_PUBKEY` override, else the compiled-in+/// [`xerj_common::hub::HUB_PUBKEY_HEX`]). No key+/// is a hard error — an unverifiable pack is never extracted.fn hub_pubkey() -> Result<String> {- if let Ok(k) = std::env::var("XERJ_HUB_PUBKEY") {- if !k.is_empty() {- return Ok(k);- }- }- if !HUB_PUBKEY_HEX.is_empty() {- return Ok(HUB_PUBKEY_HEX.to_string());- }- bail!(- "no hub public key is configured in this build (HUB_PUBKEY_HEX is empty and \- XERJ_HUB_PUBKEY is unset), so a pack's signature cannot be verified; nothing was \- downloaded"- )+ xerj_common::hub::hub_pubkey().ok_or_else(|| {+ anyhow!(+ "no hub public key is configured in this build (or XERJ_HUB_PUBKEY={}), so a \+ pack's signature cannot be verified; nothing was downloaded",+ xerj_common::hub::HUB_PUBKEY_NONE+ )+ })}/// First 8 hex chars of a 40-hex commit — the `pin8` in pack names.@@ -1692,7 +1687,7 @@ mod tests {// `catalogue` test module already mutates under its own `ENV_LOCK`. A unit// test here that set/removed that var would race those tests (lib tests share// one process and run in parallel, and the lock is private to that module).- // The empty-key path — no key => its own exit code (5), with no `.tmp` leaked+ // The no-key path (`XERJ_HUB_PUBKEY=none`) — its own exit code (5), no `.tmp` leaked// and no node started — is covered end to end by the `nokey` scenario in// `tests/pack_roundtrip.rs` instead. Everything below refuses BEFORE the key is// looked at, so it needs no environment.diff --git a/engine/crates/xerj-hub/tests/ed25519_sh_agrees.rs b/engine/crates/xerj-hub/tests/ed25519_sh_agrees.rsnew file mode 100644index 000000000..5ccc075c2--- /dev/null+++ b/engine/crates/xerj-hub/tests/ed25519_sh_agrees.rs@@ -0,0 +1,89 @@+//! The CI-side verifier (`tools/hub-packs/ed25519.sh`, openssl) and the client+//! (`verify_bytes`, ring) must agree on the key and signature formats, or the+//! workflows could prove a signature no client accepts (or refuse one every+//! client accepts). Checked with a throwaway keypair: the real seed lives only in+//! the `HUB_SIGNING_SEED` secret.+//!+//! Skipped (with a note) where `bash`, `openssl` or `xxd` is missing — the+//! workflows that use the script run on ubuntu, where all three are present.+#![cfg(unix)]++use std::path::{Path, PathBuf};+use std::process::Command;++use xerj_autoindex::harvest::sign::{generate_keypair, sign_bytes, verify_bytes};+use xerj_hub::HUB_PUBKEY_HEX;++fn script() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../tools/hub-packs/ed25519.sh")+}++fn have(tool: &str) -> bool {+ Command::new("sh")+ .args(["-c", &format!("command -v {tool}")])+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++fn sh(args: &[&str]) -> (bool, String) {+ let out = Command::new("bash")+ .arg(script())+ .args(args)+ .output()+ .unwrap();+ (+ out.status.success(),+ String::from_utf8_lossy(&out.stdout).trim().to_string(),+ )+}++#[test]+fn ed25519_sh_and_verify_bytes_agree() {+ if !["bash", "openssl", "xxd"].iter().all(|t| have(t)) {+ eprintln!("skipped: needs bash, openssl and xxd");+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let (seed, public) = generate_keypair().unwrap();+ let seed_file = dir.path().join("hub.key");+ std::fs::write(&seed_file, &seed).unwrap();++ // derive: the script gets the same public half from the seed as ring does.+ let (ok, derived) = sh(&["derive", seed_file.to_str().unwrap()]);+ assert!(ok, "derive failed");+ assert_eq!(+ derived, public,+ "openssl and ring derive different public keys"+ );++ // A signature from the client's signer verifies in the script…+ let msg = dir.path().join("catalogue.json");+ std::fs::write(&msg, br#"{"format_version":1}"#).unwrap();+ let sig = sign_bytes(&std::fs::read(&msg).unwrap(), &seed).unwrap();+ let sig_file = dir.path().join("catalogue.json.sig");+ std::fs::write(&sig_file, format!("{sig}\n")).unwrap();+ let (m, s) = (msg.to_str().unwrap(), sig_file.to_str().unwrap());+ assert!(+ sh(&["verify", &public, m, s]).0,+ "script rejects a good sig"+ );+ verify_bytes(&std::fs::read(&msg).unwrap(), &sig, &public).unwrap();++ // …and both refuse it under the compiled-in hub key and after a flipped byte.+ assert!(+ !sh(&["verify", HUB_PUBKEY_HEX, m, s]).0,+ "script accepts a test-key signature under HUB_PUBKEY_HEX"+ );+ let err = verify_bytes(&std::fs::read(&msg).unwrap(), &sig, HUB_PUBKEY_HEX).unwrap_err();+ assert!(+ format!("{err:#}").contains("does not verify"),+ "HUB_PUBKEY_HEX must parse as a key and fail only the signature check: {err:#}"+ );+ std::fs::write(&msg, br#"{"format_version":2}"#).unwrap();+ assert!(+ !sh(&["verify", &public, m, s]).0,+ "script accepts a flipped byte"+ );+ assert!(verify_bytes(&std::fs::read(&msg).unwrap(), &sig, &public).is_err());+}diff --git a/engine/crates/xerj-hub/tests/no_hub_key.rs b/engine/crates/xerj-hub/tests/no_hub_key.rsindex 1cda6b7e8..a2e10d08e 100644--- a/engine/crates/xerj-hub/tests/no_hub_key.rs+++ b/engine/crates/xerj-hub/tests/no_hub_key.rs@@ -1,5 +1,6 @@-//! A build with no hub signing key (`HUB_PUBKEY_HEX` empty, `XERJ_HUB_PUBKEY`-//! unset) can verify no catalogue and no pack. Every hub surface must say so+//! A build with no hub signing key can verify no catalogue and no pack. A real+//! key is compiled in now, so the test asks for that state explicitly with+//! `XERJ_HUB_PUBKEY=none` (`HUB_PUBKEY_NONE`). Every hub surface must say so//! plainly with exit 5 — not fail on whatever the hub URL serves (a 200 HTML//! page made `xerj ask` print "parse catalogue JSON: expected value at line 1//! column 1", exit 1) and not send an MCP agent to `xerj hub sync`, which@@ -12,11 +13,11 @@ use xerj_hub::cli::{run_ask, run_hub_cli};#[test]fn every_hub_surface_says_the_build_has_no_key() {+ std::env::set_var("XERJ_HUB_PUBKEY", xerj_common::hub::HUB_PUBKEY_NONE);assert!(- xerj_hub::HUB_PUBKEY_HEX.is_empty(),- "precondition: no compiled-in key"+ !xerj_common::hub::hub_key_configured(),+ "precondition: the override takes the key away");- std::env::remove_var("XERJ_HUB_PUBKEY");let home = tempfile::tempdir().unwrap();std::env::set_var("XERJ_HUB_HOME", home.path());// A hub that serves a 200 HTML page for every path, like hub.xerj.org'sdiff --git a/engine/crates/xerj-hub/tests/pack_roundtrip.rs b/engine/crates/xerj-hub/tests/pack_roundtrip.rsindex f26d014f2..207d3f8be 100644--- a/engine/crates/xerj-hub/tests/pack_roundtrip.rs+++ b/engine/crates/xerj-hub/tests/pack_roundtrip.rs@@ -578,8 +578,14 @@ async fn pack_build_pull_def_roundtrip() {{let hh = work.join("hub-nokey");write_catalogue(&hh, &archive, &good_sha);- // HUB_PUBKEY_HEX is "" in this build, so an unset env var leaves no key.- let rc = run_pull(&work.join("code-nokey"), &hh, None, &url_b).await;+ // A real key is compiled in, so "no key" is the explicit test override.+ let rc = run_pull(+ &work.join("code-nokey"),+ &hh,+ Some(xerj_common::hub::HUB_PUBKEY_NONE),+ &url_b,+ )+ .await;assert_eq!(rc, 5,"no key → \"this build cannot verify anything\" (5), which is not exit 3: the \diff --git a/engine/crates/xerj-mcp/tests/hub_tools.rs b/engine/crates/xerj-mcp/tests/hub_tools.rsindex b86ff93c7..88def1661 100644--- a/engine/crates/xerj-mcp/tests/hub_tools.rs+++ b/engine/crates/xerj-mcp/tests/hub_tools.rs@@ -441,9 +441,10 @@ async fn hub_tools_answer_from_a_local_pack_and_never_download() {);// No cache at all: every tool says what would help, and still fetches- // nothing. With a hub key that is `xerj hub sync`; in a build with no key- // (HUB_PUBKEY_HEX empty) sync cannot help, so the tools say the hub is not- // available in this build instead of sending the agent round a loop.+ // nothing. With a hub key (the compiled-in one, here) that is `xerj hub+ // sync`; with no key (`XERJ_HUB_PUBKEY=none`, see xerj-hub's no_hub_key.rs)+ // sync cannot help, so the tools say the hub is not available in this build+ // instead of sending the agent round a loop.std::fs::remove_file(hub.join("catalogue.json")).unwrap();let wanted = if xerj_common::hub::hub_key_configured() {"xerj hub sync"