Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

feat(hub): hosted read-only /_hub/v1 endpoints + hub.public (plan §6)

xerj-orgbe828288e017
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index cf32b18e5..6d14d40b5 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -7381,8 +7381,10 @@ dependencies = [
"tracing-subscriber",
"uuid",
"xerj-ai",
+ "xerj-autoindex",
"xerj-common",
"xerj-engine",
+ "xerj-hub",
"xerj-query",
"xerj-rerank",
"xerj-wasm",
diff --git a/engine/crates/xerj-api/Cargo.toml b/engine/crates/xerj-api/Cargo.toml
index 5cd543d8c..ce7e0800e 100644
--- a/engine/crates/xerj-api/Cargo.toml
+++ b/engine/crates/xerj-api/Cargo.toml
@@ -25,6 +25,12 @@ xerj-common = { path = "../xerj-common" }
xerj-engine = { path = "../xerj-engine" }
xerj-query = { path = "../xerj-query" }
xerj-rerank = { path = "../xerj-rerank" }
+# Corpus Hub hosted endpoints (`hub_api.rs`): `def::lookup_in` is the one `def`
+# function every surface calls, and `xerj_autoindex::xc::code_root` is where its
+# state ledger lives. `xerj-hub` dev-depends on this crate (its pack roundtrip
+# test boots a node); Cargo accepts a cycle that runs through a dev-dependency.
+xerj-hub = { path = "../xerj-hub" }
+xerj-autoindex = { path = "../xerj-autoindex" }
xerj-wasm = { path = "../xerj-wasm" }
# Local decision head (feature `decide-local`); no other purpose, so the
# dependency itself is optional.
@@ -37,7 +43,7 @@ xerj-ai = { path = "../xerj-ai", optional = true }
tokio = { workspace = true }
axum = { workspace = true }
-tower = { workspace = true }
+tower = { workspace = true, features = ["util"] }
tower-http = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/engine/crates/xerj-api/src/hub_api.rs b/engine/crates/xerj-api/src/hub_api.rs
new file mode 100644
index 000000000..b1cf4422b
--- /dev/null
+++ b/engine/crates/xerj-api/src/hub_api.rs
@@ -0,0 +1,1720 @@
+//! Corpus Hub v2 — the hosted, read-only endpoints (plan §6,
+//! `docs/CORPUS_HUB_V2_IMPLEMENTATION.md`).
+//!
+//! Four `GET` routes under `/_hub/v1/` answer from the pre-indexed packs that
+//! `xerj hub pull` restored on this node, so an agent with no clone and no
+//! local index still gets an answer in one request:
+//!
+//! | Route | Answer |
+//! |---|---|
+//! | `GET /_hub/v1/catalogue` | the bytes of the file at `hub.catalogue_path`, `ETag` = its sha256, `Cache-Control: public, max-age=3600`, `304` on a matching `If-None-Match` |
+//! | `GET /_hub/v1/def/{slug}/{symbol}?k=` | an [`Answer`] from [`xerj_hub::def::lookup_in`] (the one `def` function the CLI uses) |
+//! | `GET /_hub/v1/code/{slug}?q=&k=&max_tokens=&mode=` | an [`Answer`] built from [`xerj_common::xccode::run_code_query`] (the pipeline `xerj code` uses) |
+//! | `GET /_hub/v1/search?q=&k=` | `{corpora:[{slug,best_score,best_hit}]}`, `multi_match` on `body,defs,symbol_text` across every pack index, grouped by corpus, best first, at most 10 |
+//!
+//! ## Limits (all four routes)
+//!
+//! `GET` only — any other method is `405` (behind authentication, unless
+//! `hub.public` opens the route). Read-only: nothing here writes.
+//! A corpus name must be in the catalogue (`404` otherwise, also for a name in
+//! the catalogue with the `excluded` licence class — never served). `symbol`
+//! and `q` are limited to [`MAX_INPUT_BYTES`] (`400`); `k` is clamped to
+//! [`MAX_K`]. An unrecognised query parameter is a `400`, the way Elasticsearch
+//! treats one, so a typo is never silently ignored.
+//!
+//! ## `hub.public` and the rate limit
+//!
+//! With `hub.public = true` exactly the four routes above — by exact path
+//! shape, see [`is_public_path`] — skip authentication, authorization and the
+//! audit log; `router.rs` wraps those three layers with a check that calls
+//! [`is_public_request`]. Everything else on the node keeps all three. The
+//! audit layer is skipped on purpose: it records every unauthenticated write-
+//! shaped request, and a public route must not be a way to flush a bounded
+//! evidence ring.
+//!
+//! `hub.public` makes the routes reachable by anyone, so they are rate-limited
+//! per client address ([`RATE_LIMIT`] requests per [`RATE_WINDOW`], `429` with
+//! `Retry-After`) — in both modes, so the limit never depends on how the node is
+//! configured. `xerj-api` has no per-API-key limiter to reuse — the only
+//! limiter in the crate is the share-claim one, which is private to
+//! [`crate::share::ShareStore`] and shares a bounded table with claim
+//! attempts, so hub traffic would throttle share claims. This module has its
+//! own [`RateLimiter`]. The client address is [`crate::share::ClaimSource`]:
+//! the TCP peer, believing `X-Forwarded-For` only from `server.trusted_proxies`.
+//!
+//! ## How a query reaches the engine — and why it is not a loopback call
+//!
+//! `lookup` and `run_code_query` are written against [`XcHttp`], a three-method
+//! HTTP shell (`search`, `get_mapping`, `cat_indices_json`). The plan suggests
+//! implementing it for the in-process case by calling the node's own loopback
+//! address with the admin key. This module implements it **in-process
+//! instead**: [`InProcessNode`] hands each call to a private router that holds
+//! exactly the three read routes (`internal_router`) — the same handlers,
+//! extractors and response encoding the real HTTP routes use, with no socket.
+//! Reasons:
+//!
+//! * the node cannot reliably name its own address: `server.es_compat_port = 0`
+//! (ephemeral) is a supported configuration, `--port` rewrites ports, TLS may
+//! be on, and the bind address need not be loopback;
+//! * no credential is needed, so no admin key is read from config or sent
+//! anywhere on a path a stranger can reach;
+//! * the blocking client in `xerj-hub` (`HubNode`) has a 300 s timeout — far too
+//! long on a path a stranger can hold open — and would make the node an HTTP
+//! client of itself, a new kind of outbound connection for a server that
+//! publishes an inventory of every way data leaves it (`docs/RERANK.md`);
+//! * the private router offers three read routes and nothing else, which is a
+//! smaller surface than "the admin key against the whole API".
+//!
+//! Three further guards bound what a hosted query can touch, even if a bug let
+//! an unexpected name through: [`InProcessNode`] refuses any index expression
+//! that is not made of `xc-` names in a conservative character set, every call
+//! runs under an engine-level [`index_guard`] that hides every index outside
+//! `xc-*`, and the corpus name is checked against the catalogue before any
+//! filesystem path is built from it.
+//!
+//! The `XcHttp` methods are synchronous and the handlers async, so each query
+//! runs on the blocking pool (`run_query`) under a global concurrency cap
+//! ([`MAX_CONCURRENT_QUERIES`], `503` + `Retry-After` when full) and a wall
+//! clock timeout ([`QUERY_TIMEOUT`], `504`).
+//!
+//! ## Known limits, stated so they are not rediscovered
+//!
+//! * Every hosted search appends an entry to the node's audit ring (the
+//! `_search` handler does so unconditionally). On a dedicated hub node that is
+//! harmless; on a node that also holds data worth auditing, a flood of
+//! rate-limited-but-distinct clients can age out older entries.
+//! * `Answer.answered_from` is always `hosted` here: that is where the answer
+//! came from as far as the client is concerned, even though the server read a
+//! local pack.
+//! * The shared query pipeline's JSON output does not report which arms ran for
+//! `mode=semantic|hybrid` (its "BM25 only" note is prose-only), so those
+//! modes carry a warning saying so instead of a silent fallback.
+//! * `search` queries `xc-*`, not the plan's `xc-*-docs,xc-*-defs`. This engine
+//! resolves index-name wildcards only as `*`, `prefix*` or `*suffix`
+//! (`glob_match_simple`, `es_compat.rs`), so a `*` in the middle of a name
+//! matches nothing: measured on this build, `xc-*-docs`, `xc-*-defs` and
+//! `xc-mini-*-docs` return zero hits where `xc-*`, `xc-m*` and an explicit
+//! list return the documents. The plan's pattern would make `search` answer
+//! "nothing matches" for everything, with a `200`. `xc-*` also covers every
+//! dataset index of a pack (autoindex names them after the repo's
+//! directories, not `docs`), so the route sees more of a pack than the plan's
+//! two suffixes would have. Hits that belong to no listed corpus are skipped.
+
+use std::collections::{HashMap, VecDeque};
+use std::net::IpAddr;
+use std::path::{Path as FsPath, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant, SystemTime};
+
+use axum::body::{Body, Bytes};
+use axum::extract::{FromRequestParts, Path, Query, Request, State};
+use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode};
+use axum::middleware::{self, Next};
+use axum::response::{IntoResponse, Response};
+use axum::routing::{get, post};
+use axum::{Json, Router};
+use chrono::NaiveDate;
+use serde_json::{json, Value};
+use sha2::{Digest, Sha256};
+use tower::ServiceExt;
+use xerj_common::hub::{
+ Answer, AnswerMode, AnsweredFrom, Catalogue, Hit, LicenceClass, CATALOGUE_FORMAT_VERSION,
+};
+use xerj_common::xccode::{self, passage, state as ledger, CodeParams, Mode, XcHttp};
+use xerj_engine::index_guard::{self, IndexVisibility};
+
+use crate::error::{EsErrorBody, EsErrorResponse, EsRootCause};
+use crate::es_compat;
+use crate::share::ClaimSource;
+use crate::state::AppState;
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Limits
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// `symbol` and `q` may be at most this many bytes (after percent-decoding).
+pub const MAX_INPUT_BYTES: usize = 512;
+/// `k` is clamped to this.
+pub const MAX_K: usize = 50;
+/// `k` when the request names none (`def` and `code`).
+pub const DEFAULT_K: usize = 5;
+/// `k` when the request names none (`search`).
+pub const SEARCH_DEFAULT_K: usize = 10;
+/// `search` returns at most this many corpora, whatever `k` says.
+pub const MAX_SEARCH_CORPORA: usize = 10;
+/// Requests one client address may make per [`RATE_WINDOW`].
+pub const RATE_LIMIT: usize = 60;
+/// The sliding window [`RATE_LIMIT`] is counted over.
+pub const RATE_WINDOW: Duration = Duration::from_secs(60);
+/// Hard ceiling on tracked client addresses. Past it, addresses not yet seen
+/// share one overflow bucket — throttled together rather than tracked without
+/// bound, because this table is fed by unauthenticated callers.
+pub const MAX_TRACKED_CLIENTS: usize = 10_000;
+/// Engine-backed queries allowed in flight at once.
+pub const MAX_CONCURRENT_QUERIES: usize = 16;
+/// Wall-clock budget for one engine-backed query.
+pub const QUERY_TIMEOUT: Duration = Duration::from_secs(20);
+/// `max_tokens` is refused above this.
+pub const MAX_TOKENS_CAP: u64 = 8192;
+/// How many characters one token is taken to be when `max_tokens` is applied.
+/// An approximation, stated in the response warning when it binds.
+pub const CHARS_PER_TOKEN: usize = 4;
+
+/// Passage width when the request names no `max_tokens` (the CLI's default).
+const DEFAULT_PASSAGE_CHARS: usize = 800;
+/// Cap on any single internal response, so one hosted query cannot pull an
+/// unbounded body into memory.
+const MAX_INTERNAL_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
+/// Cap on the catalogue file the node will read and serve.
+const MAX_CATALOGUE_BYTES: u64 = 16 * 1024 * 1024;
+/// What `search` queries. Not the plan's `xc-*-docs,xc-*-defs`: this engine
+/// resolves only `*`, `prefix*` and `*suffix`, so a `*` mid-name matches no
+/// index (see the module docs, "Known limits").
+const SEARCH_INDEX_EXPR: &str = "xc-*";
+/// The fields `search` matches on, before the mapping gate drops any no
+/// searched index maps (see [`HubShared::search_fields_blocking`]).
+const SEARCH_FIELDS: [&str; 3] = ["body", "defs", "symbol_text"];
+/// Hits fetched so that grouping by corpus still has ten corpora to pick from.
+const SEARCH_POOL: usize = 100;
+/// How long a resolved `search` field list is reused.
+const SEARCH_FIELDS_TTL: Duration = Duration::from_secs(60);
+/// Longest excerpt carried by a `search` best hit built from a docs record.
+const EXCERPT_CHARS: usize = 240;
+/// `_source` fields `search` asks the engine for — everything a best hit needs,
+/// and none of the (large) `body`.
+const SEARCH_SOURCE_FIELDS: [&str; 14] = [
+ "symbol",
+ "kind",
+ "file",
+ "line",
+ "text",
+ "value",
+ "ax_path",
+ "ax_file",
+ "path",
+ "lineno",
+ "start_line",
+ "title",
+ "defs",
+ "code",
+];
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Shared state
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Everything the four routes share, built once per router.
+///
+/// Held per router rather than in a `static` so two routers in one process
+/// (every test file) never share a rate-limit budget or a catalogue.
+pub struct HubShared {
+ app: AppState,
+ limiter: RateLimiter,
+ slots: Arc<tokio::sync::Semaphore>,
+ catalogue: Mutex<Option<CachedCatalogue>>,
+ search_fields: Mutex<Option<(Instant, Vec<&'static str>)>>,
+}
+
+impl HubShared {
+ /// State for one router, over the node's [`AppState`].
+ pub fn new(app: AppState) -> Arc<Self> {
+ Arc::new(Self {
+ app,
+ limiter: RateLimiter::new(RATE_LIMIT, RATE_WINDOW, MAX_TRACKED_CLIENTS),
+ slots: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_QUERIES)),
+ catalogue: Mutex::new(None),
+ search_fields: Mutex::new(None),
+ })
+ }
+
+ /// Test seam: take `n` query slots, as `n` slow queries would. Not
+ /// reachable over HTTP.
+ #[doc(hidden)]
+ pub fn hold_slots_for_test(&self, n: usize) -> Vec<tokio::sync::OwnedSemaphorePermit> {
+ (0..n)
+ .filter_map(|_| self.slots.clone().try_acquire_owned().ok())
+ .collect()
+ }
+
+ /// The catalogue, re-read only when the file's size or modification time
+ /// changed. Blocking (a `stat`, and a read on change) — call from the
+ /// blocking pool.
+ fn catalogue_blocking(&self) -> Result<Arc<CatalogueData>, CatalogueError> {
+ let configured = self.app.config.hub.catalogue_path.trim();
+ if configured.is_empty() {
+ return Err(CatalogueError::NotConfigured);
+ }
+ let path = PathBuf::from(configured);
+ let meta = std::fs::metadata(&path)
+ .map_err(|e| CatalogueError::Unavailable(format!("stat {}: {e}", path.display())))?;
+ if !meta.is_file() {
+ return Err(CatalogueError::Unavailable(format!(
+ "{} is not a regular file",
+ path.display()
+ )));
+ }
+ if meta.len() > MAX_CATALOGUE_BYTES {
+ return Err(CatalogueError::Unavailable(format!(
+ "{} is {} bytes, over the {MAX_CATALOGUE_BYTES}-byte cap",
+ path.display(),
+ meta.len()
+ )));
+ }
+ let modified = meta.modified().ok();
+ let mut cache = self.catalogue.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(c) = cache.as_ref() {
+ if c.path == path && c.len == meta.len() && c.modified == modified {
+ return Ok(c.data.clone());
+ }
+ }
+ let bytes = std::fs::read(&path)
+ .map_err(|e| CatalogueError::Unavailable(format!("read {}: {e}", path.display())))?;
+ let data = Arc::new(CatalogueData::from_bytes(Bytes::from(bytes)));
+ *cache = Some(CachedCatalogue {
+ path,
+ len: meta.len(),
+ modified,
+ data: data.clone(),
+ });
+ Ok(data)
+ }
+
+ async fn catalogue(self: &Arc<Self>) -> Result<Arc<CatalogueData>, CatalogueError> {
+ let me = self.clone();
+ match tokio::task::spawn_blocking(move || me.catalogue_blocking()).await {
+ Ok(r) => r,
+ Err(e) => Err(CatalogueError::Unavailable(format!(
+ "catalogue task failed: {e}"
+ ))),
+ }
+ }
+
+ /// `Ok` when `slug` is a corpus the catalogue lists and permits serving,
+ /// else the response to send instead.
+ ///
+ /// Everything that is not a servable corpus — a malformed name, a name the
+ /// catalogue does not list, a listed name with the `excluded` licence class
+ /// — is the same `404`: the caller learns nothing about which it was.
+ async fn resolve_corpus(self: &Arc<Self>, slug: &str) -> Result<(), Response> {
+ if !valid_slug(slug) {
+ return Err(unknown_corpus());
+ }
+ let data = self
+ .catalogue()
+ .await
+ .map_err(CatalogueError::into_response)?;
+ let index = match &data.index {
+ Ok(index) => index,
+ Err(why) => {
+ tracing::warn!(error = %why, "hub catalogue does not parse");
+ return Err(error(
+ StatusCode::SERVICE_UNAVAILABLE,
+ "hub_unavailable",
+ "the hub catalogue cannot be read right now",
+ ));
+ }
+ };
+ match index.corpora.get(slug) {
+ Some(rule) if rule.licence_class != LicenceClass::Excluded => Ok(()),
+ _ => Err(unknown_corpus()),
+ }
+ }
+
+ /// The `search` fields that at least one searched index maps.
+ ///
+ /// This engine does not ignore an unmapped `multi_match` field the way
+ /// Elasticsearch does: a field that NO searched index maps collapses a
+ /// multi-token query to zero hits (`xccode::fields::resolve_fields` has the
+ /// measurement). So the fixed list is intersected with the mappings'
+ /// union — the same gate the CLI applies — and the answer is reused for
+ /// [`SEARCH_FIELDS_TTL`], since reading the mappings of every pack is far
+ /// more expensive than a search. Blocking.
+ fn search_fields_blocking(&self, node: &InProcessNode) -> Vec<&'static str> {
+ {
+ let cache = self.search_fields.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some((at, fields)) = cache.as_ref() {
+ if at.elapsed() < SEARCH_FIELDS_TTL {
+ return fields.clone();
+ }
+ }
+ }
+ let path = format!("/{SEARCH_INDEX_EXPR}/_mapping");
+ let fields = match node.get_mapping(&path) {
+ Ok(mapping) => mapped_search_fields(&mapping),
+ // No `xc-*` index yet: nothing to search, and not an error. Not
+ // remembered, so the first pack restored is searchable on the next
+ // request rather than a minute later.
+ Err(e) if e.contains("__404__") => return Vec::new(),
+ // A failed read is not remembered either: one transient fault must
+ // not blank `search` for the whole TTL.
+ Err(e) => {
+ tracing::warn!(error = ?truncate_chars(&e, 500), "hub search: cannot read mappings");
+ return Vec::new();
+ }
+ };
+ *self.search_fields.lock().unwrap_or_else(|e| e.into_inner()) =
+ Some((Instant::now(), fields.clone()));
+ fields
+ }
+}
+
+struct CachedCatalogue {
+ path: PathBuf,
+ len: u64,
+ modified: Option<SystemTime>,
+ data: Arc<CatalogueData>,
+}
+
+/// The catalogue file as read: its bytes and etag (what `GET /catalogue`
+/// serves), and the corpora it lists (what every other route validates against).
+struct CatalogueData {
+ bytes: Bytes,
+ etag: String,
+ index: Result<CatalogueIndex, String>,
+}
+
+struct CatalogueIndex {
+ corpora: HashMap<String, CorpusRule>,
+}
+
+/// What the catalogue says about one corpus that a route needs.
+#[derive(Clone)]
+struct CorpusRule {
+ licence_spdx: String,
+ licence_class: LicenceClass,
+}
+
+impl CatalogueData {
+ fn from_bytes(bytes: Bytes) -> Self {
+ let etag = format!("\"{}\"", hex(&Sha256::digest(&bytes)));
+ let index = serde_json::from_slice::<Catalogue>(&bytes)
+ .map_err(|e| e.to_string())
+ .and_then(|c| {
+ if c.format_version != CATALOGUE_FORMAT_VERSION {
+ return Err(format!(
+ "catalogue format_version {} (this build reads {CATALOGUE_FORMAT_VERSION})",
+ c.format_version
+ ));
+ }
+ Ok(CatalogueIndex {
+ corpora: c
+ .corpora
+ .into_iter()
+ .map(|e| {
+ (
+ e.slug,
+ CorpusRule {
+ licence_spdx: e.licence_spdx,
+ licence_class: e.licence_class,
+ },
+ )
+ })
+ .collect(),
+ })
+ });
+ Self { bytes, etag, index }
+ }
+}
+
+enum CatalogueError {
+ /// `hub.catalogue_path` is empty.
+ NotConfigured,
+ /// Configured, but the file cannot be used; the detail is for the log only.
+ Unavailable(String),
+}
+
+impl CatalogueError {
+ fn into_response(self) -> Response {
+ match self {
+ CatalogueError::NotConfigured => error(
+ StatusCode::NOT_FOUND,
+ "resource_not_found_exception",
+ "this node has no hub catalogue (hub.catalogue_path is not set)",
+ ),
+ CatalogueError::Unavailable(detail) => {
+ tracing::warn!(error = %detail, "hub catalogue unavailable");
+ error(
+ StatusCode::SERVICE_UNAVAILABLE,
+ "hub_unavailable",
+ "the hub catalogue cannot be read right now",
+ )
+ }
+ }
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Which requests are public
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Is `path` exactly one of the four hosted routes?
+///
+/// By shape, never by prefix: `/_hub/v1/catalogue`, `/_hub/v1/search`,
+/// `/_hub/v1/code/{slug}` and `/_hub/v1/def/{slug}/{symbol}`, each segment
+/// non-empty and nothing after the last one. A trailing slash, an extra
+/// segment, a different case or an empty segment is NOT public — it falls
+/// through to authentication like any other path, which is the safe direction
+/// for a predicate that grants access.
+pub fn is_public_path(path: &str) -> bool {
+ let Some(rest) = path.strip_prefix("/_hub/v1/") else {
+ return false;
+ };
+ let parts: Vec<&str> = rest.split('/').collect();
+ match parts.as_slice() {
+ ["catalogue"] | ["search"] => true,
+ ["code", slug] => !slug.is_empty(),
+ ["def", slug, symbol] => !slug.is_empty() && !symbol.is_empty(),
+ _ => false,
+ }
+}
+
+/// Should this request skip authentication, authorization and the audit log?
+///
+/// True only when the node is configured `hub.public = true` AND the path is
+/// one of the four hosted routes ([`is_public_path`]). Any method: a `POST` to
+/// one of them reaches the router and gets its `405`, and it must not reach the
+/// audit layer, which would record the unauthenticated attempt.
+pub fn is_public_request(state: &AppState, req: &Request) -> bool {
+ state.config.hub.public && is_public_path(req.uri().path())
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Rate limiting
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// A per-client sliding-window limiter: at most `limit` requests in any
+/// `window`, and `Retry-After` is the time until the oldest of them ages out.
+///
+/// A sliding window rather than a refilling token bucket: the plan asks for
+/// "60 requests/minute, the 61st in a minute is `429`", and a token bucket
+/// that refills continuously lets a client make `limit` requests at once and
+/// then more as tokens trickle back — up to twice the stated rate over the same
+/// minute — so the 61st request could succeed when the machine is slow.
+///
+/// Memory is bounded: each client holds at most `limit` timestamps, and at most
+/// `max_clients` clients are tracked; past that, new addresses share one
+/// overflow bucket.
+pub struct RateLimiter {
+ limit: usize,
+ window: Duration,
+ max_clients: usize,
+ inner: Mutex<LimiterInner>,
+}
+
+struct LimiterInner {
+ clients: HashMap<String, VecDeque<Instant>>,
+ calls: u64,
+}
+
+const OVERFLOW_KEY: &str = "overflow";
+/// Expired clients are swept every this-many calls.
+const SWEEP_EVERY: u64 = 256;
+
+impl RateLimiter {
+ pub fn new(limit: usize, window: Duration, max_clients: usize) -> Self {
+ Self {
+ limit,
+ window,
+ max_clients,
+ inner: Mutex::new(LimiterInner {
+ clients: HashMap::new(),
+ calls: 0,
+ }),
+ }
+ }
+
+ /// Admit one request from `client` at `now`, or say how many whole seconds
+ /// (at least one) until a slot frees. A refused request is not recorded:
+ /// hammering a `429` does not extend it.
+ pub fn admit(&self, client: &str, now: Instant) -> Result<(), u64> {
+ let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ inner.calls = inner.calls.wrapping_add(1);
+ let window = self.window;
+ let live = |q: &VecDeque<Instant>| {
+ q.back()
+ .is_some_and(|t| now.saturating_duration_since(*t) < window)
+ };
+ if inner.calls.is_multiple_of(SWEEP_EVERY) {
+ inner.clients.retain(|_, q| live(q));
+ }
+ let mut key = client;
+ if !inner.clients.contains_key(key) && inner.clients.len() >= self.max_clients {
+ // Table full: reclaim what has expired before conceding to the
+ // shared overflow bucket.
+ inner.clients.retain(|_, q| live(q));
+ if inner.clients.len() >= self.max_clients {
+ key = OVERFLOW_KEY;
+ }
+ }
+ let q = inner.clients.entry(key.to_string()).or_default();
+ while q
+ .front()
+ .is_some_and(|t| now.saturating_duration_since(*t) >= window)
+ {
+ q.pop_front();
+ }
+ if q.len() >= self.limit {
+ let oldest = q.front().copied().unwrap_or(now);
+ let wait = window.saturating_sub(now.saturating_duration_since(oldest));
+ let secs = wait.as_secs() + u64::from(wait.subsec_nanos() > 0);
+ return Err(secs.max(1));
+ }
+ q.push_back(now);
+ Ok(())
+ }
+}
+
+/// The rate-limit key for a client address: the address itself for IPv4, the
+/// enclosing /64 for IPv6 (one host is routinely delegated a whole /64 and can
+/// take a fresh address per request, so per-address buckets there are no
+/// throttle at all), and anything that is not an address as its own bucket.
+/// Mirrors `share::source_bucket`, which is private to that module.
+pub fn client_bucket(source: &str) -> String {
+ match source.parse::<IpAddr>() {
+ Ok(IpAddr::V6(v6)) => {
+ let mut seg = v6.segments();
+ seg[4..].fill(0);
+ format!("{}/64", std::net::Ipv6Addr::from(seg))
+ }
+ _ => source.to_string(),
+ }
+}
+
+async fn rate_limit(State(shared): State<Arc<HubShared>>, req: Request, next: Next) -> Response {
+ let (mut parts, body) = req.into_parts();
+ let source = match ClaimSource::from_request_parts(&mut parts, &shared.app).await {
+ Ok(ClaimSource(source)) => source,
+ Err(never) => match never {},
+ };
+ let req = Request::from_parts(parts, body);
+ match shared
+ .limiter
+ .admit(&client_bucket(&source), Instant::now())
+ {
+ Ok(()) => next.run(req).await,
+ Err(retry_after) => {
+ let mut resp = error(
+ StatusCode::TOO_MANY_REQUESTS,
+ "too_many_requests",
+ format!(
+ "more than {RATE_LIMIT} requests in {} seconds from this address; \
+ retry in {retry_after}s",
+ RATE_WINDOW.as_secs()
+ ),
+ );
+ if let Ok(v) = HeaderValue::from_str(&retry_after.to_string()) {
+ resp.headers_mut().insert(header::RETRY_AFTER, v);
+ }
+ resp
+ }
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// The in-process XcHttp
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Engine-level visibility for hosted queries: `xc-*` indices only.
+///
+/// Installed around every internal call. The engine consults it at the
+/// funnel every name passes through (`Engine::get_index`, `list_indices`), so
+/// an alias, a wildcard or a bug upstream of this module still cannot reach an
+/// index outside the hub namespace.
+struct HubVisibility;
+
+impl IndexVisibility for HubVisibility {
+ fn visible(&self, index: &str) -> bool {
+ index.starts_with("xc-")
+ }
+}
+
+/// The three read routes `lookup` and `run_code_query` need, and nothing else,
+/// with no middleware: reachable only from [`InProcessNode`], never from a
+/// socket.
+fn internal_router(app: &AppState) -> Router {
+ Router::new()
+ .route(
+ "/_cat/indices/:pattern",
+ get(es_compat::cat_indices_pattern),
+ )
+ .route("/:index/_mapping", get(es_compat::get_mapping))
+ .route("/:index/_search", post(es_compat::search))
+ .with_state(app.clone())
+}
+
+/// Is `expr` a comma list of `xc-` index names in a character set that cannot
+/// change the meaning of a URL path? Anything else is refused before a request
+/// is built.
+fn hub_index_expr_ok(expr: &str) -> bool {
+ !expr.is_empty()
+ && expr.len() <= 4096
+ && expr.split(',').all(|part| {
+ part.starts_with("xc-")
+ && part.bytes().all(|b| {
+ b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'*' | b'-')
+ })
+ })
+}
+
+/// [`XcHttp`] over the node's own engine, in-process (see the module docs).
+///
+/// Methods block; call from the blocking pool, never from an async task.
+pub struct InProcessNode {
+ router: Router,
+ rt: tokio::runtime::Handle,
+ /// The caller's `Authorization` header, forwarded only so the audit entry a
+ /// search writes names the right principal. The private router has no
+ /// authentication layer; nothing here grants anything.
+ auth: Option<HeaderValue>,
+}
+
+impl InProcessNode {
+ fn new(app: &AppState, auth: Option<HeaderValue>) -> Self {
+ Self {
+ router: internal_router(app),
+ rt: tokio::runtime::Handle::current(),
+ auth,
+ }
+ }
+
+ fn send(
+ &self,
+ method: Method,
+ path: &str,
+ body: Option<&Value>,
+ ) -> Result<(u16, Bytes), String> {
+ let mut builder = Request::builder().method(method).uri(path);
+ if let Some(a) = &self.auth {
+ builder = builder.header(header::AUTHORIZATION, a.clone());
+ }
+ let req = match body {
+ Some(b) => builder
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(Body::from(
+ serde_json::to_vec(b).map_err(|e| e.to_string())?,
+ )),
+ None => builder.body(Body::empty()),
+ }
+ .map_err(|e| format!("cannot build the internal request: {e}"))?;
+ let router = self.router.clone();
+ let call = async move {
+ let resp = match router.oneshot(req).await {
+ Ok(resp) => resp,
+ Err(never) => match never {},
+ };
+ let status = resp.status().as_u16();
+ let bytes = axum::body::to_bytes(resp.into_body(), MAX_INTERNAL_RESPONSE_BYTES)
+ .await
+ .map_err(|_| {
+ format!("internal response over {MAX_INTERNAL_RESPONSE_BYTES} bytes")
+ })?;
+ Ok::<_, String>((status, bytes))
+ };
+ // `block_on` is legal here: this runs on a blocking-pool thread, never
+ // on an async worker. The visibility guard is a task-local, so it must
+ // be installed inside the future this thread drives.
+ self.rt
+ .block_on(index_guard::scoped(Arc::new(HubVisibility), call))
+ }
+
+ fn json(
+ &self,
+ method: Method,
+ path: &str,
+ body: Option<&Value>,
+ ) -> Result<(u16, Value), String> {
+ let (status, bytes) = self.send(method, path, body)?;
+ let value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
+ Ok((status, value))
+ }
+}
+
+impl XcHttp for InProcessNode {
+ fn get_mapping(&self, path: &str) -> Result<Value, String> {
+ let expr = path
+ .strip_prefix('/')
+ .and_then(|p| p.strip_suffix("/_mapping"))
+ .filter(|e| hub_index_expr_ok(e))
+ .ok_or_else(|| "refused: not a hub mapping path".to_string())?;
+ match self.json(Method::GET, &format!("/{expr}/_mapping"), None)? {
+ (s, v) if (200..300).contains(&s) => Ok(v),
+ (404, _) => Err("__404__".to_string()),
+ (s, v) => Err(format!("HTTP {s}: {v}")),
+ }
+ }
+
+ fn cat_indices_json(&self, pattern: &str) -> Result<Vec<String>, String> {
+ if !hub_index_expr_ok(pattern) {
+ return Err("refused: not a hub index pattern".to_string());
+ }
+ let path = format!("/_cat/indices/{pattern}?format=json&h=index");
+ match self.json(Method::GET, &path, None)? {
+ // A wildcard matching no index is "none", not an error.
+ (404, _) => Ok(Vec::new()),
+ (s, v) if (200..300).contains(&s) => v
+ .as_array()
+ .map(|rows| {
+ rows.iter()
+ .filter_map(|r| r.get("index").and_then(Value::as_str))
+ .map(str::to_string)
+ .collect()
+ })
+ .ok_or_else(|| "non-array _cat reply".to_string()),
+ (s, v) => Err(format!("HTTP {s}: {v}")),
+ }
+ }
+
+ fn search(&self, index: &str, body: &Value) -> Result<Value, String> {
+ if !hub_index_expr_ok(index) {
+ return Err("refused: not a hub index expression".to_string());
+ }
+ match self.json(Method::POST, &format!("/{index}/_search"), Some(body))? {
+ (s, v) if (200..300).contains(&s) => Ok(v),
+ (404, _) => Err("__404__".to_string()),
+ (s, v) => Err(format!("HTTP {s}: {v}")),
+ }
+ }
+}
+
+/// Run `work` on the blocking pool with an [`InProcessNode`], under the global
+/// concurrency cap and the wall-clock timeout.
+///
+/// The permit is held by the blocking closure, not by this future, so a query
+/// that outlives its timeout keeps counting against the cap until it really
+/// finishes — the cap bounds blocking threads, not just waiting requests.
+async fn run_query<T, F>(
+ shared: &Arc<HubShared>,
+ headers: &HeaderMap,
+ work: F,
+) -> Result<T, Response>
+where
+ T: Send + 'static,
+ F: FnOnce(&InProcessNode) -> T + Send + 'static,
+{
+ let Ok(permit) = shared.slots.clone().try_acquire_owned() else {
+ let mut resp = error(
+ StatusCode::SERVICE_UNAVAILABLE,
+ "hub_busy",
+ "the hub is answering as many queries as it can; retry shortly",
+ );
+ resp.headers_mut()
+ .insert(header::RETRY_AFTER, HeaderValue::from_static("1"));
+ return Err(resp);
+ };
+ let node = InProcessNode::new(&shared.app, headers.get(header::AUTHORIZATION).cloned());
+ let job = tokio::task::spawn_blocking(move || {
+ let _permit = permit;
+ work(&node)
+ });
+ match tokio::time::timeout(QUERY_TIMEOUT, job).await {
+ Ok(Ok(out)) => Ok(out),
+ Ok(Err(e)) => {
+ tracing::warn!(error = %e, "hub query task failed");
+ Err(error(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "hub_internal_error",
+ "the hub could not answer this request",
+ ))
+ }
+ Err(_) => Err(error(
+ StatusCode::GATEWAY_TIMEOUT,
+ "hub_timeout",
+ format!("the hub did not answer within {}s", QUERY_TIMEOUT.as_secs()),
+ )),
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Request validation
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// A corpus name the catalogue could legitimately hold, and one that is safe to
+/// put in a filesystem path and an index pattern: ASCII alphanumeric first,
+/// then alphanumerics and `. _ + -`, at most 64 bytes. Checked before the
+/// catalogue is consulted, so nothing else is ever looked up or built from it.
+pub fn valid_slug(slug: &str) -> bool {
+ let mut bytes = slug.bytes();
+ slug.len() <= 64
+ && bytes.next().is_some_and(|b| b.is_ascii_alphanumeric())
+ && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'-'))
+}
+
+/// Collect the query string into a map, refusing a parameter this route does
+/// not take and a parameter given twice.
+fn collect_params(
+ pairs: Vec<(String, String)>,
+ allowed: &[&str],
+) -> Result<HashMap<String, String>, Response> {
+ let mut out = HashMap::new();
+ for (key, value) in pairs {
+ if !allowed.contains(&key.as_str()) {
+ return Err(bad_request(format!(
+ "request contains unrecognized parameter [{}]; this route takes {}",
+ truncate_chars(&key, 32),
+ allowed.join(", ")
+ )));
+ }
+ if out.insert(key.clone(), value).is_some() {
+ return Err(bad_request(format!(
+ "parameter [{key}] given more than once"
+ )));
+ }
+ }
+ Ok(out)
+}
+
+/// A required text parameter: present, non-blank, at most [`MAX_INPUT_BYTES`].
+fn text_param(raw: Option<&str>, name: &str) -> Result<String, Response> {
+ let raw = raw.ok_or_else(|| bad_request(format!("`{name}` is required")))?;
+ check_text(raw, name)
+}
+
+/// The same limit for a value that arrived as a path segment.
+fn check_text(raw: &str, name: &str) -> Result<String, Response> {
+ if raw.len() > MAX_INPUT_BYTES {
+ return Err(bad_request(format!(
+ "`{name}` is limited to {MAX_INPUT_BYTES} bytes, got {}",
+ raw.len()
+ )));
+ }
+ let trimmed = raw.trim();
+ if trimmed.is_empty() {
+ return Err(bad_request(format!("`{name}` must not be blank")));
+ }
+ Ok(trimmed.to_string())
+}
+
+/// `k`: absent is `default`; otherwise an integer of at least 1, clamped to
+/// [`MAX_K`]. Zero and non-numbers are a `400`, not a silent default.
+pub fn parse_k(raw: Option<&str>, default: usize) -> Result<usize, String> {
+ let Some(raw) = raw else {
+ return Ok(default);
+ };
+ match raw.trim().parse::<u64>() {
+ Ok(0) | Err(_) => Err(format!(
+ "`k` must be an integer from 1 to {MAX_K}, got [{}]",
+ truncate_chars(raw, 32)
+ )),
+ Ok(n) => Ok(usize::try_from(n).unwrap_or(MAX_K).min(MAX_K)),
+ }
+}
+
+/// `max_tokens`: absent is no budget; otherwise an integer from 1 to
+/// [`MAX_TOKENS_CAP`].
+pub fn parse_max_tokens(raw: Option<&str>) -> Result<Option<u64>, String> {
+ let Some(raw) = raw else {
+ return Ok(None);
+ };
+ match raw.trim().parse::<u64>() {
+ Ok(n) if (1..=MAX_TOKENS_CAP).contains(&n) => Ok(Some(n)),
+ _ => Err(format!(
+ "`max_tokens` must be an integer from 1 to {MAX_TOKENS_CAP}, got [{}]",
+ truncate_chars(raw, 32)
+ )),
+ }
+}
+
+/// `mode`: the retrieval arm, as `xerj code --mode` spells it.
+pub fn parse_mode(raw: Option<&str>) -> Result<Mode, String> {
+ match raw {
+ None => Ok(Mode::Bm25),
+ Some(s) => Mode::parse(s.trim()).ok_or_else(|| {
+ format!(
+ "`mode` must be bm25, semantic or hybrid, got [{}]",
+ truncate_chars(s, 32)
+ )
+ }),
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Responses
+// ─────────────────────────────────────────────────────────────────────────────
+
+fn error(status: StatusCode, error_type: &str, reason: impl Into<String>) -> Response {
+ let reason = reason.into();
+ let body = EsErrorResponse {
+ error: EsErrorBody {
+ root_cause: vec![EsRootCause {
+ error_type: error_type.to_string(),
+ reason: reason.clone(),
+ resource_type: None,
+ resource_id: None,
+ index_uuid: None,
+ index: None,
+ }],
+ error_type: error_type.to_string(),
+ reason,
+ resource_type: None,
+ resource_id: None,
+ index_uuid: None,
+ index: None,
+ request_id: None,
+ },
+ status: status.as_u16(),
+ xerj_hint: None,
+ };
+ (status, Json(body)).into_response()
+}
+
+fn bad_request(reason: impl Into<String>) -> Response {
+ error(
+ StatusCode::BAD_REQUEST,
+ "illegal_argument_exception",
+ reason,
+ )
+}
+
+fn unknown_corpus() -> Response {
+ error(
+ StatusCode::NOT_FOUND,
+ "resource_not_found_exception",
+ "no such corpus in this hub's catalogue",
+ )
+}
+
+fn not_loaded() -> Response {
+ error(
+ StatusCode::NOT_FOUND,
+ "corpus_not_loaded",
+ "this corpus is in the catalogue but is not loaded on this node",
+ )
+}
+
+/// A backend failure. The detail goes to the log; the client gets a fixed
+/// sentence, because the detail can name filesystem paths and engine internals.
+fn unavailable(detail: &str) -> Response {
+ // Debug formatting escapes control characters: the detail can echo what the
+ // caller sent, and a raw newline in it would forge log lines. Bounded, so
+ // an engine error carrying a large body cannot flood the log either.
+ tracing::warn!(error = ?truncate_chars(detail, 500), "hub query failed");
+ error(
+ StatusCode::SERVICE_UNAVAILABLE,
+ "hub_unavailable",
+ "the hub could not answer from this corpus right now",
+ )
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Routes
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// The four routes, with their own state and the rate limit in front of all of
+/// them (a layer, not a per-handler call, so a route added here cannot forget
+/// it). Generic over the outer router's state: this router carries its own.
+pub fn routes<S>(shared: Arc<HubShared>) -> Router<S>
+where
+ S: Clone + Send + Sync + 'static,
+{
+ Router::<Arc<HubShared>>::new()
+ .route("/_hub/v1/catalogue", get(catalogue_route))
+ .route("/_hub/v1/def/:slug/:symbol", get(def_route))
+ .route("/_hub/v1/code/:slug", get(code_route))
+ .route("/_hub/v1/search", get(search_route))
+ .layer(middleware::from_fn_with_state(shared.clone(), rate_limit))
+ .with_state(shared)
+}
+
+/// `GET /_hub/v1/catalogue`.
+async fn catalogue_route(State(shared): State<Arc<HubShared>>, headers: HeaderMap) -> Response {
+ let data = match shared.catalogue().await {
+ Ok(d) => d,
+ Err(e) => return e.into_response(),
+ };
+ let mut resp = if etag_matches(headers.get(header::IF_NONE_MATCH), &data.etag) {
+ StatusCode::NOT_MODIFIED.into_response()
+ } else {
+ (
+ [(header::CONTENT_TYPE, "application/json")],
+ data.bytes.clone(),
+ )
+ .into_response()
+ };
+ if let Ok(v) = HeaderValue::from_str(&data.etag) {
+ resp.headers_mut().insert(header::ETAG, v);
+ }
+ resp.headers_mut().insert(
+ header::CACHE_CONTROL,
+ HeaderValue::from_static("public, max-age=3600"),
+ );
+ resp
+}
+
+/// Does an `If-None-Match` header match `etag`? Handles `*`, a comma list, and
+/// weak (`W/`) validators, which compare equal for a conditional GET.
+pub fn etag_matches(header: Option<&HeaderValue>, etag: &str) -> bool {
+ let Some(value) = header.and_then(|h| h.to_str().ok()) else {
+ return false;
+ };
+ value.split(',').map(str::trim).any(|candidate| {
+ candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag
+ })
+}
+
+/// What a blocking query reports back.
+enum Outcome {
+ Done(Box<Answer>),
+ NotLoaded,
+ /// The corpus's own ledger says `excluded`, whatever the catalogue lists:
+ /// both must permit serving, and either can refuse.
+ NotServed,
+ Failed(String),
+}
+
+fn respond(outcome: Result<Outcome, Response>) -> Response {
+ match outcome {
+ Ok(Outcome::Done(answer)) => Json(*answer).into_response(),
+ Ok(Outcome::NotLoaded) => not_loaded(),
+ Ok(Outcome::NotServed) => unknown_corpus(),
+ Ok(Outcome::Failed(detail)) => unavailable(&detail),
+ Err(resp) => resp,
+ }
+}
+
+/// `GET /_hub/v1/def/{slug}/{symbol}?k=`.
+async fn def_route(
+ State(shared): State<Arc<HubShared>>,
+ Path((slug, symbol)): Path<(String, String)>,
+ Query(pairs): Query<Vec<(String, String)>>,
+ headers: HeaderMap,
+) -> Response {
+ let params = match collect_params(pairs, &["k"]) {
+ Ok(p) => p,
+ Err(resp) => return resp,
+ };
+ let symbol = match check_text(&symbol, "symbol") {
+ Ok(s) => s,
+ Err(resp) => return resp,
+ };
+ let k = match parse_k(params.get("k").map(String::as_str), DEFAULT_K) {
+ Ok(k) => k,
+ Err(why) => return bad_request(why),
+ };
+ if let Err(resp) = shared.resolve_corpus(&slug).await {
+ return resp;
+ }
+ let outcome = run_query(&shared, &headers, move |node| {
+ let root = hub_root();
+ let facts = match corpus_facts(&root, &slug) {
+ Ok(f) => f,
+ Err(_) => return Outcome::NotLoaded,
+ };
+ if facts.licence_class == LicenceClass::Excluded {
+ return Outcome::NotServed;
+ }
+ // Mirror the CLI's refusals: a corpus the ledger knows but this node
+ // holds no index for is "not loaded", not "no such definition".
+ match node.cat_indices_json(&format!("{}*", facts.index_prefix)) {
+ Ok(live) if live.is_empty() => return Outcome::NotLoaded,
+ Ok(_) => {}
+ Err(e) => return Outcome::Failed(format!("listing indices: {e}")),
+ }
+ let mut answer = xerj_hub::def::lookup_in(node, &root, &slug, &symbol, k);
+ // `lookup` reports a failed query as a warning on an empty answer. The
+ // CLI maps that to an exit code earlier; over HTTP a failure must not
+ // read as "no such definition".
+ if let Some(w) = answer
+ .warnings
+ .iter()
+ .find(|w| w.starts_with("defs query failed"))
+ {
+ return Outcome::Failed(w.clone());
+ }
+ answer.answered_from = AnsweredFrom::Hosted;
+ Outcome::Done(Box::new(answer))
+ })
+ .await;
+ respond(outcome)
+}
+
+/// `GET /_hub/v1/code/{slug}?q=&k=&max_tokens=&mode=`.
+async fn code_route(
+ State(shared): State<Arc<HubShared>>,
+ Path(slug): Path<String>,
+ Query(pairs): Query<Vec<(String, String)>>,
+ headers: HeaderMap,
+) -> Response {
+ let params = match collect_params(pairs, &["q", "k", "max_tokens", "mode"]) {
+ Ok(p) => p,
+ Err(resp) => return resp,
+ };
+ let query = match text_param(params.get("q").map(String::as_str), "q") {
+ Ok(q) => q,
+ Err(resp) => return resp,
+ };
+ let k = match parse_k(params.get("k").map(String::as_str), DEFAULT_K) {
+ Ok(k) => k,
+ Err(why) => return bad_request(why),
+ };
+ let max_tokens = match parse_max_tokens(params.get("max_tokens").map(String::as_str)) {
+ Ok(m) => m,
+ Err(why) => return bad_request(why),
+ };
+ let mode = match parse_mode(params.get("mode").map(String::as_str)) {
+ Ok(m) => m,
+ Err(why) => return bad_request(why),
+ };
+ if let Err(resp) = shared.resolve_corpus(&slug).await {
+ return resp;
+ }
+ let width = passage_width(max_tokens);
+ let outcome = run_query(&shared, &headers, move |node| {
+ let root = hub_root();
+ let facts = match corpus_facts(&root, &slug) {
+ Ok(f) => f,
+ Err(_) => return Outcome::NotLoaded,
+ };
+ if facts.licence_class == LicenceClass::Excluded {
+ return Outcome::NotServed;
+ }
+ let mut params = CodeParams::new(&slug, &query);
+ params.k = k;
+ params.mode = mode;
+ params.full = width;
+ // The raw server response, patched with the diversified page: the
+ // same list the prose renderer prints, as data.
+ params.as_json = true;
+ let out = xccode::run_code_query(
+ &root,
+ node,
+ "in-process",
+ &params,
+ "not available on the hosted route",
+ );
+ match out.exit {
+ 0 | 1 => {
+ let resp = out.json.unwrap_or(Value::Null);
+ let mut hits = record_hits(&resp, &query, width);
+ let mut warnings = out.warnings;
+ if let Some(note) = approach_only_note(&facts) {
+ for hit in &mut hits {
+ hit.licence_warning = Some(note.clone());
+ }
+ }
+ if mode != Mode::Bm25 {
+ warnings.push(
+ "mode semantic/hybrid falls back to BM25 when the corpus has no \
+ semantic_text mapping, and this response does not say which arms ran"
+ .to_string(),
+ );
+ }
+ let truncated = match max_tokens {
+ Some(budget) => apply_token_budget(&mut hits, budget, &mut warnings),
+ None => false,
+ };
+ Outcome::Done(Box::new(facts.into_answer(
+ AnswerMode::How,
+ hits,
+ truncated,
+ warnings,
+ )))
+ }
+ 3 => Outcome::NotLoaded,
+ _ => Outcome::Failed(out.text),
+ }
+ })
+ .await;
+ respond(outcome)
+}
+
+/// `GET /_hub/v1/search?q=&k=`.
+async fn search_route(
+ State(shared): State<Arc<HubShared>>,
+ Query(pairs): Query<Vec<(String, String)>>,
+ headers: HeaderMap,
+) -> Response {
+ let params = match collect_params(pairs, &["q", "k"]) {
+ Ok(p) => p,
+ Err(resp) => return resp,
+ };
+ let query = match text_param(params.get("q").map(String::as_str), "q") {
+ Ok(q) => q,
+ Err(resp) => return resp,
+ };
+ let k = match parse_k(params.get("k").map(String::as_str), SEARCH_DEFAULT_K) {
+ Ok(k) => k.min(MAX_SEARCH_CORPORA),
+ Err(why) => return bad_request(why),
+ };
+ let data = match shared.catalogue().await {
+ Ok(d) => d,
+ Err(e) => return e.into_response(),
+ };
+ if let Err(why) = &data.index {
+ tracing::warn!(error = %why, "hub catalogue does not parse");
+ return error(
+ StatusCode::SERVICE_UNAVAILABLE,
+ "hub_unavailable",
+ "the hub catalogue cannot be read right now",
+ );
+ }
+ let blocking_shared = shared.clone();
+ let outcome = run_query(&shared, &headers, move |node| {
+ let fields = blocking_shared.search_fields_blocking(node);
+ if fields.is_empty() {
+ return Ok(Vec::new());
+ }
+ // Only the top hits are read, never a total: with the fan-out over every
+ // pack index, counting matches is work nobody asked for.
+ let body = json!({
+ "size": SEARCH_POOL,
+ "track_total_hits": false,
+ "_source": SEARCH_SOURCE_FIELDS,
+ "query": { "multi_match": { "query": query, "fields": fields } },
+ });
+ let resp = match node.search(SEARCH_INDEX_EXPR, &body) {
+ Ok(r) => r,
+ Err(e) if e.contains("__404__") => return Ok(Vec::new()),
+ Err(e) => return Err(format!("search failed: {e}")),
+ };
+ let corpora = match &data.index {
+ Ok(index) => group_by_corpus(&resp, &index.corpora, k),
+ Err(_) => Vec::new(),
+ };
+ Ok(corpora)
+ })
+ .await;
+ match outcome {
+ Ok(Ok(corpora)) => {
+ let rows: Vec<Value> = corpora
+ .into_iter()
+ .map(|c| json!({ "slug": c.slug, "best_score": c.hit.score, "best_hit": c.hit }))
+ .collect();
+ Json(json!({ "corpora": rows })).into_response()
+ }
+ Ok(Err(detail)) => unavailable(&detail),
+ Err(resp) => resp,
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Facts about a loaded corpus
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// Where the state ledger lives — the same root `xerj hub pull` writes and
+/// `xerj_hub::def::lookup` reads.
+fn hub_root() -> PathBuf {
+ xerj_autoindex::xc::code_root()
+}
+
+/// What an [`Answer`] says about the corpus it came from, from the ledger the
+/// pull wrote. Mirrors `xerj_hub::def`'s private `DefMeta` so a `def` answer
+/// and a `code` answer for the same corpus carry the same header; a test pins
+/// the two together.
+struct CorpusFacts {
+ corpus: String,
+ index_prefix: String,
+ pin_sha: String,
+ pin_date: String,
+ age_days: u32,
+ licence_spdx: String,
+ licence_class: LicenceClass,
+}
+
+fn corpus_facts(root: &FsPath, slug: &str) -> Result<CorpusFacts, String> {
+ let st = ledger::load_state(root, slug)?;
+ let pin_date = st.pin_date.clone().unwrap_or_default();
+ Ok(CorpusFacts {
+ corpus: st.name(slug),
+ index_prefix: ledger::query_prefix(&st),
+ age_days: age_days_from(&pin_date, st.indexed_at.as_deref()),
+ pin_sha: st.pin_sha.clone().unwrap_or_default(),
+ pin_date,
+ licence_spdx: st.licence_spdx.clone().unwrap_or_default(),
+ licence_class: parse_licence_class(st.licence_class.as_deref()),
+ })
+}
+
+impl CorpusFacts {
+ fn into_answer(
+ self,
+ mode: AnswerMode,
+ hits: Vec<Hit>,
+ truncated: bool,
+ warnings: Vec<String>,
+ ) -> Answer {
+ Answer {
+ corpus: self.corpus,
+ pin_sha: self.pin_sha,
+ pin_date: self.pin_date,
+ age_days: self.age_days,
+ licence_spdx: self.licence_spdx,
+ licence_class: self.licence_class,
+ answered_from: AnsweredFrom::Hosted,
+ mode,
+ hits,
+ truncated,
+ warnings,
+ }
+ }
+}
+
+/// An unknown or absent class never upgrades to a stricter one by surprise.
+fn parse_licence_class(s: Option<&str>) -> LicenceClass {
+ match s {
+ Some("approach-only") => LicenceClass::ApproachOnly,
+ Some("excluded") => LicenceClass::Excluded,
+ _ => LicenceClass::AdaptWithAttribution,
+ }
+}
+
+/// Days from the pin date (else the index stamp) to today, never negative.
+fn age_days_from(pin_date: &str, indexed_at: Option<&str>) -> u32 {
+ if let Ok(d) = NaiveDate::parse_from_str(pin_date, "%Y-%m-%d") {
+ return (chrono::Utc::now().date_naive() - d).num_days().max(0) as u32;
+ }
+ if let Some(stamp) = indexed_at {
+ if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(stamp, "%Y-%m-%dT%H:%M:%SZ") {
+ let age = chrono::Utc::now().naive_utc().signed_duration_since(dt);
+ return age.num_days().max(0) as u32;
+ }
+ }
+ 0
+}
+
+fn approach_only_note(facts: &CorpusFacts) -> Option<String> {
+ (facts.licence_class == LicenceClass::ApproachOnly).then(|| licence_note(&facts.licence_spdx))
+}
+
+/// The wording `xerj_hub::def` puts on every hit of an approach-only corpus.
+fn licence_note(spdx: &str) -> String {
+ format!(
+ "approach-only licence ({}): read, do not copy",
+ if spdx.is_empty() { "unknown" } else { spdx }
+ )
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Building hits
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// `s` cut to at most `n` characters (never splitting a code point).
+pub fn truncate_chars(s: &str, n: usize) -> String {
+ s.chars().take(n).collect()
+}
+
+fn hex(bytes: &[u8]) -> String {
+ use std::fmt::Write as _;
+ bytes
+ .iter()
+ .fold(String::with_capacity(bytes.len() * 2), |mut s, b| {
+ let _ = write!(s, "{b:02x}");
+ s
+ })
+}
+
+/// `path:12` → (`path`, 12); anything else is all path and line 0 (a line is
+/// never invented).
+fn split_locator(loc: &str) -> (String, u32) {
+ if let Some((path, tail)) = loc.rsplit_once(':') {
+ if !tail.is_empty() && tail.bytes().all(|b| b.is_ascii_digit()) {
+ if let Ok(n) = tail.parse::<u64>() {
+ return (path.to_string(), u32::try_from(n).unwrap_or(u32::MAX));
+ }
+ }
+ }
+ (loc.to_string(), 0)
+}
+
+/// The text of a code record: `body`, else `text`, else its longest string
+/// field (a raw-JSON record carries its content under schema-named keys).
+/// Mirrors the renderer's choice in `xccode::render`, whose helper is private.
+fn record_body(src: &Value) -> String {
+ if let Some(s) = src.get("body").and_then(Value::as_str) {
+ return s.to_string();
+ }
+ if let Some(s) = src.get("text").and_then(Value::as_str) {
+ return s.to_string();
+ }
+ let mut best: Option<&str> = None;
+ if let Some(obj) = src.as_object() {
+ let mut keys: Vec<&String> = obj.keys().collect();
+ keys.sort();
+ for key in keys {
+ if let Some(s) = obj[key].as_str() {
+ if !s.trim().is_empty()
+ && best.is_none_or(|b| s.chars().count() > b.chars().count())
+ {
+ best = Some(s);
+ }
+ }
+ }
+ }
+ best.unwrap_or_default().to_string()
+}
+
+/// One retrieved record as a [`Hit`], with the passage the CLI would print: the
+/// best-matching definition when the record carries symbols, else the densest
+/// window.
+fn hit_from_record(row: &Value, query: &str, width: usize) -> Hit {
+ let src = row.get("_source").unwrap_or(&Value::Null);
+ let score = row.get("_score").and_then(Value::as_f64).unwrap_or(0.0) as f32;
+ // The pack's `-defs` index sits under the same prefix, so a definition
+ // record can come back here. Keep what it is — its kind, its value, its
+ // exact line — instead of passing it off as a prose passage.
+ if src.get("symbol").is_some_and(Value::is_string) {
+ return def_hit(src, score, width);
+ }
+ let (file, record_line) = split_locator(&passage::provenance(src));
+ let body = record_body(src);
+ let (text, kind, line) = match passage::symbol_passage(&body, src, query, width) {
+ Some((text, label)) => {
+ let (kind, symbol_line) = parse_symbol_label(&label);
+ // The matched definition's line, as the extractor recorded it against
+ // the whole-file `body`, so it is a file line. A record with no
+ // symbol line falls back to its own `line`, or 0: a line is reported
+ // only when the index supplied one.
+ let line = if symbol_line > 0 {
+ symbol_line
+ } else {
+ record_line
+ };
+ (text, kind, line)
+ }
+ None => {
+ let (window, _start, _total) = passage::best_window(&body, query, width);
+ (window, "passage".to_string(), record_line)
+ }
+ };
+ Hit {
+ file,
+ line,
+ kind,
+ text,
+ value: None,
+ score,
+ licence_warning: None,
+ }
+}
+
+/// `"function addReplyNull @ line 12"` → (`function`, 12).
+fn parse_symbol_label(label: &str) -> (String, u32) {
+ let Some((head, line)) = label.rsplit_once(" @ line ") else {
+ return ("passage".to_string(), 0);
+ };
+ let kind = head.split_whitespace().next().unwrap_or("passage");
+ let line = line.trim().parse::<u32>().unwrap_or(0);
+ (kind.to_string(), line)
+}
+
+fn record_hits(resp: &Value, query: &str, width: usize) -> Vec<Hit> {
+ resp.pointer("/hits/hits")
+ .and_then(Value::as_array)
+ .map(|rows| {
+ rows.iter()
+ .map(|row| hit_from_record(row, query, width))
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// Characters per passage: the CLI's default, or less when `max_tokens` is
+/// smaller than that.
+pub fn passage_width(max_tokens: Option<u64>) -> usize {
+ match max_tokens {
+ Some(t) => usize::try_from(t)
+ .unwrap_or(usize::MAX)
+ .saturating_mul(CHARS_PER_TOKEN)
+ .clamp(1, DEFAULT_PASSAGE_CHARS),
+ None => DEFAULT_PASSAGE_CHARS,
+ }
+}
+
+/// Hold the hits' passage text to `max_tokens`, counted as
+/// [`CHARS_PER_TOKEN`] characters a token.
+///
+/// Hits keep their rank order while they fit. The first that does not is cut to
+/// what is left and every later one is dropped. The budget covers passage text
+/// only — file, line and the rest of the JSON are not counted — and the
+/// four-characters-a-token figure is an approximation, not a model tokenizer;
+/// the warning added whenever the budget binds says both. Returns whether
+/// anything was cut or dropped.
+pub fn apply_token_budget(
+ hits: &mut Vec<Hit>,
+ max_tokens: u64,
+ warnings: &mut Vec<String>,
+) -> bool {
+ let budget = usize::try_from(max_tokens)
+ .unwrap_or(usize::MAX)
+ .saturating_mul(CHARS_PER_TOKEN);
+ let mut used = 0usize;
+ let mut cut = false;
+ let mut keep = 0usize;
+ for (i, hit) in hits.iter_mut().enumerate() {
+ let len = hit.text.chars().count();
+ if used.saturating_add(len) <= budget {
+ used += len;
+ keep = i + 1;
+ continue;
+ }
+ let left = budget - used;
+ if left > 0 {
+ hit.text = truncate_chars(&hit.text, left);
+ keep = i + 1;
+ }
+ cut = true;
+ break;
+ }
+ let omitted = hits.len() - keep;
+ hits.truncate(keep);
+ if cut || omitted > 0 {
+ warnings.push(format!(
+ "answer held to max_tokens={max_tokens} (about {CHARS_PER_TOKEN} characters a token, \
+ passage text only); {omitted} lower-ranked hit(s) omitted"
+ ));
+ return true;
+ }
+ false
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Federated search
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// The `search` fields that some index in `mapping` (a `GET /{pattern}/_mapping`
+/// reply) maps.
+pub fn mapped_search_fields(mapping: &Value) -> Vec<&'static str> {
+ let mut present = std::collections::BTreeSet::new();
+ if let Some(obj) = mapping.as_object() {
+ for m in obj.values() {
+ if let Some(props) = m.pointer("/mappings/properties").and_then(Value::as_object) {
+ present.extend(props.keys().map(String::as_str));
+ }
+ }
+ }
+ SEARCH_FIELDS
+ .into_iter()
+ .filter(|f| present.contains(f))
+ .collect()
+}
+
+/// The corpus a hub index belongs to: `xc-<slug>-b<digits>` followed by `-…` or
+/// the end, with `<slug>` one of `known`.
+///
+/// The rule `xerj corpus index` uses to tell a stamped build from a dataset
+/// named like one (`stamped_prefix` in `xerj-autoindex`, which is private and
+/// driven by a name already in hand): digits only between `-b` and the next
+/// `-`. Driven by the catalogue here, so slugs containing `-` resolve, and the
+/// shortest slug that fits wins, which is deterministic.
+pub fn slug_of_index<'a, V>(index: &str, known: &'a HashMap<String, V>) -> Option<&'a str> {
+ let rest = index.strip_prefix("xc-")?;
+ for (at, _) in rest.match_indices("-b") {
+ let after = &rest[at + 2..];
+ let digits = after.bytes().take_while(u8::is_ascii_digit).count();
+ if digits == 0 {
+ continue;
+ }
+ let tail = &after[digits..];
+ if !(tail.is_empty() || tail.starts_with('-')) {
+ continue;
+ }
+ if let Some((slug, _)) = known.get_key_value(&rest[..at]) {
+ return Some(slug.as_str());
+ }
+ }
+ None
+}
+
+struct BestHit {
+ slug: String,
+ hit: Hit,
+}
+
+/// Group a `multi_match` reply by corpus: the best hit of each, best first
+/// (ties by name), at most `want`. Hits from an index that belongs to no listed
+/// corpus, and from an `excluded` one, are skipped.
+fn group_by_corpus(resp: &Value, known: &HashMap<String, CorpusRule>, want: usize) -> Vec<BestHit> {
+ let mut best: HashMap<&str, Hit> = HashMap::new();
+ let rows = resp
+ .pointer("/hits/hits")
+ .and_then(Value::as_array)
+ .map(Vec::as_slice)
+ .unwrap_or_default();
+ for row in rows {
+ let Some(index) = row.get("_index").and_then(Value::as_str) else {
+ continue;
+ };
+ let Some(slug) = slug_of_index(index, known) else {
+ continue;
+ };
+ let Some(rule) = known.get(slug) else {
+ continue;
+ };
+ if rule.licence_class == LicenceClass::Excluded {
+ continue;
+ }
+ let score = row.get("_score").and_then(Value::as_f64).unwrap_or(0.0) as f32;
+ if best.get(slug).is_some_and(|h| h.score >= score) {
+ continue;
+ }
+ let src = row.get("_source").unwrap_or(&Value::Null);
+ // A definition record carries a `symbol`; anything else is a document
+ // record. By shape, not by index name: a dataset directory may be
+ // called `defs` too.
+ let mut hit = if src.get("symbol").is_some_and(Value::is_string) {
+ def_hit(src, score, EXCERPT_CHARS)
+ } else {
+ doc_hit(src, score)
+ };
+ if rule.licence_class == LicenceClass::ApproachOnly {
+ hit.licence_warning = Some(licence_note(&rule.licence_spdx));
+ }
+ best.insert(slug, hit);
+ }
+ let mut out: Vec<BestHit> = best
+ .into_iter()
+ .map(|(slug, hit)| BestHit {
+ slug: slug.to_string(),
+ hit,
+ })
+ .collect();
+ out.sort_by(|a, b| {
+ b.hit
+ .score
+ .total_cmp(&a.hit.score)
+ .then_with(|| a.slug.cmp(&b.slug))
+ });
+ out.truncate(want);
+ out
+}
+
+/// A best hit from a definition record: the definition itself.
+fn def_hit(src: &Value, score: f32, max_chars: usize) -> Hit {
+ let s = |k: &str| {
+ src.get(k)
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string()
+ };
+ Hit {
+ file: s("file"),
+ line: src
+ .get("line")
+ .and_then(Value::as_u64)
+ .map_or(0, |n| u32::try_from(n).unwrap_or(u32::MAX)),
+ kind: s("kind"),
+ text: truncate_chars(&s("text"), max_chars),
+ value: src.get("value").and_then(Value::as_str).map(str::to_string),
+ score,
+ licence_warning: None,
+ }
+}
+
+/// A best hit from a document record: where it is, and a short excerpt —
+/// its definitions line list, else its text, else its title. Never the body.
+fn doc_hit(src: &Value, score: f32) -> Hit {
+ let (file, line) = split_locator(&passage::provenance(src));
+ let excerpt = ["code", "defs", "text", "title"]
+ .iter()
+ .filter_map(|k| src.get(*k).and_then(Value::as_str))
+ .find(|s| !s.trim().is_empty())
+ .unwrap_or_default();
+ Hit {
+ file,
+ line,
+ kind: "passage".to_string(),
+ text: truncate_chars(excerpt, EXCERPT_CHARS),
+ value: None,
+ score,
+ licence_warning: None,
+ }
+}
diff --git a/engine/crates/xerj-api/src/lib.rs b/engine/crates/xerj-api/src/lib.rs
index f139c4711..4e9ac1b14 100644
--- a/engine/crates/xerj-api/src/lib.rs
+++ b/engine/crates/xerj-api/src/lib.rs
@@ -73,6 +73,7 @@ pub mod error;
pub mod es_compat;
pub mod extract;
pub mod graph_api;
+pub mod hub_api;
pub mod ism_api;
pub mod judge_stage;
pub mod memory_api;
diff --git a/engine/crates/xerj-api/src/router.rs b/engine/crates/xerj-api/src/router.rs
index f5f2ecdfc..736382a41 100644
--- a/engine/crates/xerj-api/src/router.rs
+++ b/engine/crates/xerj-api/src/router.rs
@@ -28,8 +28,8 @@ use uuid::Uuid;
use xerj_common::config::CorsConfig;
use crate::{
- ask_api, audit_mw, auth::auth_middleware, authz, es_compat, graph_api, ism_api, memory_api,
- native, share, state::AppState, systemone_api, wal_tap_api,
+ ask_api, audit_mw, auth::auth_middleware, authz, es_compat, graph_api, hub_api, ism_api,
+ memory_api, native, share, state::AppState, systemone_api, wal_tap_api,
};
// ─────────────────────────────────────────────────────────────────────────────
@@ -922,6 +922,14 @@ pub fn build_es_compat_router(state: AppState) -> Router {
)
.route("/_memory/:namespace/_recall", post(memory_api::recall))
.route("/_memory/:namespace/:id", delete(memory_api::forget_one))
+ // ── Corpus Hub hosted endpoints ───────────────────────────────────────
+ // Four read-only GET routes that answer from the packs restored on this
+ // node (`hub_api.rs`; plan §6). Always mounted and keyed like every
+ // other route; with `hub.public = true` exactly these four skip
+ // authentication, authorization and the audit log (the three
+ // `*_unless_public_hub` wrappers below). The rate limit is a layer on
+ // the sub-router itself, so it holds in both modes.
+ .merge(hub_api::routes(hub_api::HubShared::new(state.clone())))
// ── Share links ───────────────────────────────────────────────────────
// `xerj share`: hand one indexed corpus to a guest as a scoped,
// read-only, expiring key. Create/list/revoke are superuser-only in
@@ -965,18 +973,18 @@ pub fn build_es_compat_router(state: AppState) -> Router {
))
.layer(middleware::from_fn_with_state(
state.clone(),
- authz::authz_middleware,
+ authz_unless_public_hub,
))
// Between authn and authz, deliberately: outside authorization so a
// refused write is recorded as `denied`, inside authentication so an
// unauthenticated flood cannot evict a bounded ring (issue #329).
.layer(middleware::from_fn_with_state(
state.clone(),
- audit_mw::audit_middleware,
+ audit_unless_public_hub,
))
.layer(middleware::from_fn_with_state(
state.clone(),
- auth_middleware,
+ auth_unless_public_hub,
))
// OUTSIDE authentication, so the `401` and `403` the two layers above
// produce for `/_share…` are `no-store` too — the handlers only cover
@@ -1000,6 +1008,57 @@ pub fn build_es_compat_router(state: AppState) -> Router {
.layer(RequestDecompressionLayer::new().gzip(true))
}
+// ── hub.public ───────────────────────────────────────────────────────────────
+//
+// With `hub.public = true`, exactly the four hosted-hub routes
+// (`hub_api::is_public_path`, an exact-shape match, any method) skip the three
+// layers below; every other request goes through them untouched. They are
+// wrappers here, not edits to `auth.rs` / `authz.rs` / `audit_mw.rs`, so the
+// security modules stay exactly as reviewed and the whole exemption is the
+// short predicate in `hub_api.rs`.
+//
+// All three are skipped, not just authentication: authorization would refuse a
+// request with no principal, and the audit layer records every unauthenticated
+// write-shaped request — a public route must not be a way to flush the bounded
+// audit ring (issue #329). A `POST` to one of the four reaches the router and
+// gets its `405`; no handler exists for it.
+
+/// [`auth_middleware`], except for the public hub routes.
+async fn auth_unless_public_hub(
+ State(state): State<AppState>,
+ req: Request,
+ next: Next,
+) -> Response {
+ if hub_api::is_public_request(&state, &req) {
+ return next.run(req).await;
+ }
+ auth_middleware(State(state), req, next).await
+}
+
+/// [`audit_mw::audit_middleware`], except for the public hub routes.
+async fn audit_unless_public_hub(
+ State(state): State<AppState>,
+ req: Request,
+ next: Next,
+) -> Response {
+ if hub_api::is_public_request(&state, &req) {
+ return next.run(req).await;
+ }
+ audit_mw::audit_middleware(State(state), req, next).await
+}
+
+/// [`authz::authz_middleware`], except for the public hub routes.
+async fn authz_unless_public_hub(
+ State(state): State<AppState>,
+ req: Request,
+ next: Next,
+) -> Response {
+ if hub_api::is_public_request(&state, &req) {
+ return next.run(req).await;
+ }
+ authz::authz_middleware(State(state), req, next).await
+}
+
/// Everything under `/_share` is `Cache-Control: no-store`, whoever produced
/// the response. The handlers set it on what they return; a request refused by
/// `auth_middleware` (401) or `authz_middleware` (403) never reaches one, and
diff --git a/engine/crates/xerj-api/tests/hub_api.rs b/engine/crates/xerj-api/tests/hub_api.rs
new file mode 100644
index 000000000..6108e07e8
--- /dev/null
+++ b/engine/crates/xerj-api/tests/hub_api.rs
@@ -0,0 +1,1879 @@
+//! Route-level tests for the hosted Corpus Hub endpoints (plan §6) —
+//! `GET /_hub/v1/{catalogue, def/{slug}/{symbol}, code/{slug}, search}` over the
+//! real ES-compat router with a real engine:
+//!
+//! * the four answers: `def` returns the fixture value with its pin, `code`
+//! returns a passage with `file:line`, `search` groups by corpus, the
+//! catalogue is the file's bytes with a sha256 `ETag` and a `304`;
+//! * the validation lines: unknown corpus is `404`, `k=1000` is `50`, a
+//! 600-byte `q` is `400`, a stray parameter is `400`;
+//! * `hub.public`: `false` needs the key; `true` lets EXACTLY the four routes
+//! through without one (near-miss paths and every other route stay `401`),
+//! a `POST` to them is `405` and leaves no audit entry;
+//! * the rate limit: the 61st request in a minute from one address is `429`
+//! with `Retry-After`, keyed by the real peer (not by a header the caller
+//! writes), with a real socket on an ephemeral port as well as `oneshot`;
+//! * the guards behind the routes: an alias cannot lead a hosted query out of
+//! the `xc-*` namespace, and a backend failure never reaches the client.
+//!
+//! The ledger root is process-global (`XERJ_CODE_HOME`, read by
+//! `xerj_hub::def::lookup` the way `xerj hub pull` writes it), so every test
+//! shares ONE fixture directory, created and exported once before any node is
+//! built; each test then builds its own node and seeds its own indices.
+
+use std::net::SocketAddr;
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::{Duration, Instant};
+
+use axum::body::{Body, Bytes};
+use axum::extract::ConnectInfo;
+use axum::http::{header, HeaderMap, Request, StatusCode};
+use serde_json::{json, Value};
+use sha2::{Digest, Sha256};
+use tower::ServiceExt;
+use xerj_api::hub_api::{self, RateLimiter};
+use xerj_api::state::AppState;
+use xerj_common::hub::{
+ Answer, AnswerMode, AnsweredFrom, Catalogue, CatalogueEntry, Hit, LicenceClass, Sketch,
+ CATALOGUE_FORMAT_VERSION,
+};
+use xerj_common::xccode::state::write_hubpack_state;
+
+const ADMIN_KEY: &str = "hub-test-admin-key";
+const PIN_SHA: &str = "0774d05537f9762f838f7ab541b7765f1a729cb5";
+const PIN_DATE: &str = "2026-10-02";
+
+// ─────────────────────────────────────────────────────────────────────────────
+// The shared fixture: ledgers + catalogue, written once
+// ─────────────────────────────────────────────────────────────────────────────
+
+struct Fixture {
+ catalogue: PathBuf,
+ catalogue_bytes: Vec<u8>,
+ dir: PathBuf,
+}
+
+static FIXTURE: OnceLock<Fixture> = OnceLock::new();
+
+fn entry(slug: &str, spdx: &str, class: LicenceClass) -> CatalogueEntry {
+ CatalogueEntry {
+ slug: slug.into(),
+ domain: "DEV".into(),
+ topics: vec!["c".into()],
+ ask_for: format!("fixture corpus {slug}"),
+ pin_sha: PIN_SHA.into(),
+ pin_date: PIN_DATE.into(),
+ refresh_cadence_days: 7,
+ licence_spdx: spdx.into(),
+ licence_class: class,
+ pack_bytes: 1024,
+ pack_url: format!("https://example.invalid/{slug}.hubpack.tar.zst"),
+ pack_sha256: "0".repeat(64),
+ sig_url: format!("https://example.invalid/{slug}.hubpack.tar.zst.sig"),
+ dependency_names: vec![],
+ quality_grade: None,
+ term_sketch: Sketch {
+ m_bits: 64,
+ k_hashes: 7,
+ bits_base64: "AAAAAAAAAAA=".into(),
+ },
+ }
+}
+
+fn catalogue_bytes(entries: Vec<CatalogueEntry>) -> Vec<u8> {
+ serde_json::to_vec(&Catalogue {
+ format_version: CATALOGUE_FORMAT_VERSION,
+ generated_at: "2026-10-14T00:00:00Z".into(),
+ corpora: entries,
+ })
+ .expect("catalogue serialises")
+}
+
+/// Create the fixture and export `XERJ_CODE_HOME` — the first thing every test
+/// does, before it builds a node or reads anything else from the environment.
+fn fixture() -> &'static Fixture {
+ FIXTURE.get_or_init(|| {
+ let dir = tempfile::tempdir().expect("tempdir").keep();
+ let home = dir.join("code-home");
+ let led = |slug: &str, prefix: &str, spdx: &str, class: &str| {
+ write_hubpack_state(
+ &home, slug, "http://x", prefix, PIN_SHA, PIN_DATE, spdx, class,
+ )
+ .expect("ledger");
+ };
+ led("mini-c", "xc-mini-c-b1", "MIT", "adapt-with-attribution");
+ led(
+ "mini-gpl",
+ "xc-mini-gpl-b2",
+ "GPL-3.0-only",
+ "approach-only",
+ );
+ led(
+ "mini-closed",
+ "xc-mini-closed-b1",
+ "LicenseRef-Closed",
+ "excluded",
+ );
+ led("leaky", "xc-leaky-b1", "MIT", "adapt-with-attribution");
+ // The catalogue lists it as servable; the ledger written for the pack on
+ // THIS node says `excluded`. Both must permit, and either can refuse.
+ led(
+ "ledger-closed",
+ "xc-ledger-closed-b1",
+ "LicenseRef-Closed",
+ "excluded",
+ );
+ // A ledger whose prefix could change the meaning of a URL: the backend
+ // must refuse it, and the client must never see why.
+ led(
+ "badprefix",
+ "xc-bad prefix?x=1",
+ "MIT",
+ "adapt-with-attribution",
+ );
+ let bytes = catalogue_bytes(vec![
+ entry("mini-c", "MIT", LicenceClass::AdaptWithAttribution),
+ entry("mini-gpl", "GPL-3.0-only", LicenceClass::ApproachOnly),
+ entry("mini-closed", "LicenseRef-Closed", LicenceClass::Excluded),
+ entry("leaky", "MIT", LicenceClass::AdaptWithAttribution),
+ entry("ledger-closed", "MIT", LicenceClass::AdaptWithAttribution),
+ entry("badprefix", "MIT", LicenceClass::AdaptWithAttribution),
+ // Listed, but no ledger and no indices on any test node.
+ entry("ghost", "MIT", LicenceClass::AdaptWithAttribution),
+ ]);
+ let catalogue = dir.join("catalogue.json");
+ std::fs::write(&catalogue, &bytes).expect("catalogue file");
+ std::env::set_var("XERJ_CODE_HOME", &home);
+ Fixture {
+ catalogue,
+ catalogue_bytes: bytes,
+ dir,
+ }
+ })
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// A node under test
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[derive(Clone)]
+struct Opts {
+ public: bool,
+ /// Turn authentication on, with [`ADMIN_KEY`].
+ keyed: bool,
+ catalogue_path: Option<String>,
+ trusted_proxies: Vec<String>,
+}
+
+impl Opts {
+ fn new(public: bool, keyed: bool) -> Self {
+ Self {
+ public,
+ keyed,
+ catalogue_path: None,
+ trusted_proxies: vec![],
+ }
+ }
+}
+
+struct Hub {
+ app: axum::Router,
+ state: AppState,
+ keyed: bool,
+ _data: tempfile::TempDir,
+}
+
+struct Reply {
+ status: StatusCode,
+ headers: HeaderMap,
+ body: Bytes,
+}
+
+impl Reply {
+ fn json(&self) -> Value {
+ serde_json::from_slice(&self.body).unwrap_or(Value::Null)
+ }
+ fn header(&self, name: &str) -> Option<String> {
+ self.headers
+ .get(name)
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_string)
+ }
+ /// The body parsed as exactly an `Answer` — `deny_unknown_fields` makes
+ /// this the wire-contract check.
+ fn answer(&self) -> Answer {
+ serde_json::from_slice(&self.body).unwrap_or_else(|e| {
+ panic!(
+ "not an Answer ({e}): {}",
+ String::from_utf8_lossy(&self.body)
+ )
+ })
+ }
+}
+
+fn config_for(o: &Opts, data: &std::path::Path) -> xerj_common::config::Config {
+ let fx = fixture();
+ let mut config = xerj_common::config::Config::default();
+ config.server.data_dir = data.to_string_lossy().into_owned();
+ config.storage.wal_sync = xerj_common::config::WalSync::Async;
+ config.hub.public = o.public;
+ config.hub.catalogue_path = o
+ .catalogue_path
+ .clone()
+ .unwrap_or_else(|| fx.catalogue.to_string_lossy().into_owned());
+ config.server.trusted_proxies = o.trusted_proxies.clone();
+ if o.keyed {
+ config.auth.enabled = true;
+ config.auth.admin_api_key = ADMIN_KEY.to_string();
+ } else {
+ config.auth.enabled = false;
+ }
+ config
+}
+
+fn build(o: &Opts) -> (AppState, tempfile::TempDir) {
+ let data = tempfile::tempdir().expect("tempdir");
+ let config = config_for(o, data.path());
+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");
+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");
+ (
+ xerj_api::state::AppState::new(config, engine, metrics),
+ data,
+ )
+}
+
+/// A node with no indices at all.
+fn bare(o: &Opts) -> Hub {
+ fixture();
+ let (state, data) = build(o);
+ let app = xerj_api::router::build_es_compat_router(state.clone());
+ Hub {
+ app,
+ state,
+ keyed: o.keyed,
+ _data: data,
+ }
+}
+
+/// A node with the fixture indices seeded.
+async fn hub(o: Opts) -> Hub {
+ let hub = bare(&o);
+ seed(&hub).await;
+ hub
+}
+
+impl Hub {
+ async fn send(&self, req: Request<Body>) -> Reply {
+ let resp = self.app.clone().oneshot(req).await.expect("response");
+ let status = resp.status();
+ let headers = resp.headers().clone();
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .expect("body");
+ Reply {
+ status,
+ headers,
+ body,
+ }
+ }
+
+ fn req(method: &str, path: &str) -> axum::http::request::Builder {
+ Request::builder().method(method).uri(path)
+ }
+
+ async fn get(&self, path: &str) -> Reply {
+ self.send(Self::req("GET", path).body(Body::empty()).unwrap())
+ .await
+ }
+
+ async fn get_keyed(&self, path: &str) -> Reply {
+ self.send(
+ Self::req("GET", path)
+ .header(header::AUTHORIZATION, format!("ApiKey {ADMIN_KEY}"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ }
+
+ async fn method(&self, method: &str, path: &str) -> Reply {
+ self.send(Self::req(method, path).body(Body::empty()).unwrap())
+ .await
+ }
+
+ async fn method_keyed(&self, method: &str, path: &str) -> Reply {
+ self.send(
+ Self::req(method, path)
+ .header(header::AUTHORIZATION, format!("ApiKey {ADMIN_KEY}"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ }
+
+ /// A request as if it arrived from `peer`.
+ async fn get_from(&self, path: &str, peer: &str, xff: Option<&str>) -> Reply {
+ let mut b = Self::req("GET", path);
+ if let Some(x) = xff {
+ b = b.header("x-forwarded-for", x);
+ }
+ let mut req = b.body(Body::empty()).unwrap();
+ let addr: SocketAddr = format!("{peer}:40000").parse().expect("peer");
+ req.extensions_mut().insert(ConnectInfo(addr));
+ self.send(req).await
+ }
+
+ /// A request of any method as if it arrived from `peer`.
+ async fn method_from(&self, method: &str, path: &str, peer: &str) -> Reply {
+ let mut req = Self::req(method, path).body(Body::empty()).unwrap();
+ let addr: SocketAddr = format!("{peer}:40000").parse().expect("peer");
+ req.extensions_mut().insert(ConnectInfo(addr));
+ self.send(req).await
+ }
+
+ /// Admin-side call used only to seed the node.
+ async fn admin(&self, method: &str, path: &str, body: Option<&Value>) -> Reply {
+ let mut b = Self::req(method, path);
+ if self.keyed {
+ b = b.header(header::AUTHORIZATION, format!("ApiKey {ADMIN_KEY}"));
+ }
+ let req = match body {
+ Some(v) => b
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(Body::from(v.to_string())),
+ None => b.body(Body::empty()),
+ }
+ .unwrap();
+ self.send(req).await
+ }
+
+ async fn bulk(&self, index: &str, docs: &[Value]) {
+ let mut nd = String::new();
+ for d in docs {
+ nd.push_str("{\"index\":{}}\n");
+ nd.push_str(&d.to_string());
+ nd.push('\n');
+ }
+ let mut b = Self::req("POST", &format!("/{index}/_bulk"))
+ .header(header::CONTENT_TYPE, "application/x-ndjson");
+ if self.keyed {
+ b = b.header(header::AUTHORIZATION, format!("ApiKey {ADMIN_KEY}"));
+ }
+ let r = self.send(b.body(Body::from(nd)).unwrap()).await;
+ assert!(r.status.is_success(), "bulk into {index}: {:?}", r.json());
+ assert_eq!(
+ r.json()["errors"],
+ json!(false),
+ "bulk into {index}: {:?}",
+ r.json()
+ );
+ }
+
+ async fn create(&self, index: &str, mapping: Value) {
+ let r = self
+ .admin(
+ "PUT",
+ &format!("/{index}"),
+ Some(&json!({ "mappings": mapping })),
+ )
+ .await;
+ assert!(r.status.is_success(), "create {index}: {:?}", r.json());
+ }
+}
+
+// ── fixture indices ──────────────────────────────────────────────────────────
+
+fn defs_mapping() -> Value {
+ json!({ "properties": {
+ "symbol": {"type": "keyword"}, "symbol_text": {"type": "text"},
+ "kind": {"type": "keyword"}, "lang": {"type": "keyword"},
+ "file": {"type": "keyword"}, "line": {"type": "integer"},
+ "text": {"type": "text"}, "value": {"type": "keyword"}
+ }})
+}
+
+fn docs_mapping() -> Value {
+ json!({ "properties": {
+ "body": {"type": "text"}, "defs": {"type": "text"}, "title": {"type": "text"}
+ }})
+}
+
+fn def(symbol: &str, kind: &str, file: &str, line: u32, text: &str, value: Option<&str>) -> Value {
+ json!({
+ "symbol": symbol, "symbol_text": symbol, "kind": kind, "lang": "c",
+ "file": file, "line": line, "text": text, "value": value,
+ })
+}
+
+const HASH_C: &str = "#include \"limits.h\"\n#define MINI_HASH_SEED 5381\n\nunsigned mini_hash(const char *s) {\n unsigned h = MINI_HASH_SEED;\n while (*s) h = h * 33 + (unsigned char)*s++;\n return h;\n}\n";
+const CLAMP_C: &str =
+ "int mini_clamp(int value, int lo, int hi) {\n return value < lo ? lo : value > hi ? hi : value;\n}\n";
+
+async fn seed(h: &Hub) {
+ // ── mini-c (MIT) ──
+ h.create("xc-mini-c-b1-defs", defs_mapping()).await;
+ let mut defs = vec![
+ def(
+ "MINI_LIMIT",
+ "define",
+ "limits.h",
+ 5,
+ "#define MINI_LIMIT 128",
+ Some("128"),
+ ),
+ def(
+ "MINI_HASH_SEED",
+ "define",
+ "hash.c",
+ 2,
+ "#define MINI_HASH_SEED 5381",
+ Some("5381"),
+ ),
+ def(
+ "mini_hash",
+ "function",
+ "hash.c",
+ 4,
+ "unsigned mini_hash(const char *s)",
+ None,
+ ),
+ def(
+ "mini_clamp",
+ "function",
+ "clamp.c",
+ 4,
+ "int mini_clamp(int value, int lo, int hi)",
+ None,
+ ),
+ ];
+ // Sixty definitions of one symbol, to see `k=1000` clamped to 50.
+ for n in 0..60 {
+ defs.push(def(
+ "DUP_SYM",
+ "define",
+ &format!("dup{n:02}.h"),
+ n + 1,
+ &format!("#define DUP_SYM {n}"),
+ Some(&n.to_string()),
+ ));
+ }
+ h.bulk("xc-mini-c-b1-defs", &defs).await;
+ h.create("xc-mini-c-b1-docs", docs_mapping()).await;
+ h.bulk(
+ "xc-mini-c-b1-docs",
+ &[
+ json!({"ax_path": "mini-c/hash.c", "title": "hash.c", "body": HASH_C,
+ "defs": "define MINI_HASH_SEED\nfunction mini_hash",
+ "symbols": [{"name": "mini_hash", "kind": "function", "line": 4}]}),
+ json!({"ax_path": "mini-c/clamp.c", "title": "clamp.c", "body": CLAMP_C,
+ "defs": "function mini_clamp",
+ "symbols": [{"name": "mini_clamp", "kind": "function", "line": 1}]}),
+ json!({"ax_path": "mini-c/NOTES.md", "title": "notes",
+ "body": "frobnicate the buffer, then frobnicate it again"}),
+ json!({"ax_path": "mini-c/README.md", "title": "readme",
+ "body": "A tiny C library. Call frobnicate before you hash anything."}),
+ ],
+ )
+ .await;
+
+ // ── mini-gpl (approach-only) ──
+ h.create("xc-mini-gpl-b2-defs", defs_mapping()).await;
+ h.bulk(
+ "xc-mini-gpl-b2-defs",
+ &[def(
+ "GPL_LIMIT",
+ "define",
+ "limits.h",
+ 9,
+ "#define GPL_LIMIT 256",
+ Some("256"),
+ )],
+ )
+ .await;
+ h.create("xc-mini-gpl-b2-docs", docs_mapping()).await;
+ h.bulk(
+ "xc-mini-gpl-b2-docs",
+ &[json!({"ax_path": "mini-gpl/gpl.c", "title": "gpl.c",
+ "body": "int gpl_frob(void) {\n /* frobnicate frobnicate frobnicate the registry */\n return 1;\n}\n",
+ "defs": "function gpl_frob",
+ "symbols": [{"name": "gpl_frob", "kind": "function", "line": 1}]})],
+ )
+ .await;
+
+ // ── mini-closed (excluded): must never be served ──
+ h.create("xc-mini-closed-b1-defs", defs_mapping()).await;
+ h.bulk(
+ "xc-mini-closed-b1-defs",
+ &[def(
+ "CLOSED_LIMIT",
+ "define",
+ "c.h",
+ 1,
+ "#define CLOSED_LIMIT 7",
+ Some("7"),
+ )],
+ )
+ .await;
+ h.create("xc-mini-closed-b1-docs", docs_mapping()).await;
+ h.bulk(
+ "xc-mini-closed-b1-docs",
+ &[json!({"ax_path": "mini-closed/c.c", "body": "frobnicate closed text"})],
+ )
+ .await;
+
+ // ── an index shaped like a hub pack that no catalogue entry lists ──
+ h.create("xc-orphan-b1-docs", docs_mapping()).await;
+ h.bulk(
+ "xc-orphan-b1-docs",
+ &[json!({"ax_path": "orphan/o.c", "body": "frobnicate orphan text"})],
+ )
+ .await;
+
+ // ── leaky: a real docs index (so the corpus looks loaded) whose defs
+ // index is an ALIAS for a private index outside the hub namespace ──
+ h.create("xc-leaky-b1-docs", docs_mapping()).await;
+ h.bulk(
+ "xc-leaky-b1-docs",
+ &[json!({"ax_path": "leaky/l.c", "body": "leaky"})],
+ )
+ .await;
+ h.create("secret-notes", defs_mapping()).await;
+ h.bulk(
+ "secret-notes",
+ &[def(
+ "SECRET",
+ "define",
+ "secret.h",
+ 1,
+ "#define SECRET hunter2",
+ Some("hunter2"),
+ )],
+ )
+ .await;
+ let alias = h
+ .admin(
+ "POST",
+ "/_aliases",
+ Some(&json!({"actions": [{"add": {"index": "secret-notes", "alias": "xc-leaky-b1-defs"}}]})),
+ )
+ .await;
+ assert!(alias.status.is_success(), "alias: {:?}", alias.json());
+
+ // Searchable now, not after the next refresh tick.
+ let r = h
+ .admin(
+ "POST",
+ "/xc-mini-c-b1-defs,xc-mini-c-b1-docs,xc-mini-gpl-b2-defs,xc-mini-gpl-b2-docs,\
+ xc-mini-closed-b1-defs,xc-mini-closed-b1-docs,xc-orphan-b1-docs,\
+ xc-leaky-b1-docs,secret-notes/_refresh",
+ None,
+ )
+ .await;
+ assert!(
+ r.status.is_success(),
+ "refresh: {:?} {:?}",
+ r.status,
+ r.json()
+ );
+}
+
+const FOUR: [&str; 4] = [
+ "/_hub/v1/catalogue",
+ "/_hub/v1/def/mini-c/MINI_LIMIT",
+ "/_hub/v1/code/mini-c?q=mini_hash+unsigned",
+ "/_hub/v1/search?q=frobnicate",
+];
+
+// ─────────────────────────────────────────────────────────────────────────────
+// The four answers
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn catalogue_is_the_files_bytes_with_a_sha256_etag_and_a_304() {
+ let h = hub(Opts::new(false, false)).await;
+ let fx = fixture();
+ let want_etag = format!("\"{:x}\"", Sha256::digest(&fx.catalogue_bytes));
+
+ let r = h.get("/_hub/v1/catalogue").await;
+ assert_eq!(r.status, StatusCode::OK);
+ assert_eq!(
+ r.body.as_ref(),
+ fx.catalogue_bytes.as_slice(),
+ "the file, byte for byte"
+ );
+ assert_eq!(r.header("etag").as_deref(), Some(want_etag.as_str()));
+ assert_eq!(
+ r.header("cache-control").as_deref(),
+ Some("public, max-age=3600")
+ );
+ assert_eq!(
+ r.header("content-type").as_deref(),
+ Some("application/json")
+ );
+
+ // The validators a cache sends: exact, weak, a list, and `*` all revalidate.
+ for inm in [
+ want_etag.clone(),
+ format!("W/{want_etag}"),
+ format!("\"nope\", {want_etag}"),
+ "*".to_string(),
+ ] {
+ let r = h
+ .send(
+ Hub::req("GET", "/_hub/v1/catalogue")
+ .header(header::IF_NONE_MATCH, &inm)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await;
+ assert_eq!(r.status, StatusCode::NOT_MODIFIED, "If-None-Match: {inm}");
+ assert!(r.body.is_empty(), "a 304 carries no body");
+ assert_eq!(r.header("etag").as_deref(), Some(want_etag.as_str()));
+ assert_eq!(
+ r.header("cache-control").as_deref(),
+ Some("public, max-age=3600")
+ );
+ }
+ let r = h
+ .send(
+ Hub::req("GET", "/_hub/v1/catalogue")
+ .header(header::IF_NONE_MATCH, "\"something-else\"")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await;
+ assert_eq!(
+ r.status,
+ StatusCode::OK,
+ "a different validator gets the file"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn catalogue_follows_the_file_when_it_changes() {
+ fixture();
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("catalogue.json");
+ let first = catalogue_bytes(vec![entry(
+ "alpha",
+ "MIT",
+ LicenceClass::AdaptWithAttribution,
+ )]);
+ std::fs::write(&path, &first).unwrap();
+ let mut o = Opts::new(false, false);
+ o.catalogue_path = Some(path.to_string_lossy().into_owned());
+ let (state, _data) = build(&o);
+ let app = xerj_api::router::build_es_compat_router(state);
+ let get = |app: axum::Router| async move {
+ let resp = app
+ .oneshot(
+ Request::get("/_hub/v1/catalogue")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let etag = resp
+ .headers()
+ .get("etag")
+ .map(|v| v.to_str().unwrap().to_string());
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (etag, body)
+ };
+ let (etag1, body1) = get(app.clone()).await;
+ assert_eq!(body1.as_ref(), first.as_slice());
+
+ // A longer file: size differs, so the cache cannot be fooled by an mtime
+ // tick shorter than the filesystem's granularity.
+ let second = catalogue_bytes(vec![
+ entry("alpha", "MIT", LicenceClass::AdaptWithAttribution),
+ entry("beta", "MIT", LicenceClass::AdaptWithAttribution),
+ ]);
+ std::fs::write(&path, &second).unwrap();
+ let (etag2, body2) = get(app).await;
+ assert_eq!(
+ body2.as_ref(),
+ second.as_slice(),
+ "the new bytes are served"
+ );
+ assert_ne!(etag1, etag2, "and under a new ETag");
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn def_answers_with_the_fixture_value_the_pin_and_a_hosted_origin() {
+ let h = hub(Opts::new(false, false)).await;
+ let r = h.get("/_hub/v1/def/mini-c/MINI_LIMIT").await;
+ assert_eq!(r.status, StatusCode::OK, "{:?}", r.json());
+ let a = r.answer();
+ assert_eq!(a.corpus, "mini-c");
+ assert_eq!(a.mode, AnswerMode::Def);
+ assert_eq!(a.pin_sha, PIN_SHA);
+ assert_eq!(a.pin_date, PIN_DATE);
+ assert_eq!(a.licence_spdx, "MIT");
+ assert_eq!(a.licence_class, LicenceClass::AdaptWithAttribution);
+ assert_eq!(
+ a.answered_from,
+ AnsweredFrom::Hosted,
+ "a hosted answer says so, whatever the server read locally"
+ );
+ assert!(a.warnings.is_empty(), "{:?}", a.warnings);
+ assert_eq!(a.hits.len(), 1);
+ let hit = &a.hits[0];
+ assert_eq!((hit.file.as_str(), hit.line), ("limits.h", 5));
+ assert_eq!(hit.kind, "define");
+ assert_eq!(hit.value.as_deref(), Some("128"));
+ assert_eq!(hit.licence_warning, None);
+
+ // A miss is an answer, not an error.
+ let r = h.get("/_hub/v1/def/mini-c/NO_SUCH_SYMBOL").await;
+ assert_eq!(r.status, StatusCode::OK);
+ assert!(r.answer().hits.is_empty());
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn code_returns_a_passage_with_file_and_line() {
+ let h = hub(Opts::new(false, false)).await;
+ // The snake_case names are single tokens in this engine's analyzer, so the
+ // query uses them whole.
+ let r = h.get("/_hub/v1/code/mini-c?q=mini_hash+unsigned").await;
+ assert_eq!(r.status, StatusCode::OK, "{:?}", r.json());
+ let a = r.answer();
+ assert_eq!(a.corpus, "mini-c");
+ assert_eq!(a.mode, AnswerMode::How);
+ assert_eq!(a.answered_from, AnsweredFrom::Hosted);
+ assert!(!a.truncated);
+ assert!(!a.hits.is_empty());
+ assert!(
+ a.hits
+ .iter()
+ .all(|x| !x.file.is_empty() && x.line > 0 && x.score > 0.0),
+ "every hit cites a file and a real line: {:#?}",
+ a.hits
+ );
+ // The documents index returns the file; the pack's definitions index may
+ // return a hit for the same name too, so pick the file's own hit.
+ let top = a
+ .hits
+ .iter()
+ .find(|x| x.file == "mini-c/hash.c")
+ .unwrap_or_else(|| panic!("no hit for mini-c/hash.c in {:#?}", a.hits));
+ assert_eq!(
+ top.line, 4,
+ "the matched definition's line, never an invented one"
+ );
+ assert_eq!(top.kind, "function");
+ assert!(top.text.contains("mini_hash"), "{}", top.text);
+
+ // The pack's definitions index is under the same prefix: a definition that
+ // comes back keeps its kind, its value and its exact line.
+ let a = h.get("/_hub/v1/code/mini-c?q=MINI_LIMIT").await.answer();
+ let def = a
+ .hits
+ .iter()
+ .find(|x| x.file == "limits.h")
+ .unwrap_or_else(|| panic!("no definition hit in {:#?}", a.hits));
+ assert_eq!((def.line, def.kind.as_str()), (5, "define"));
+ assert_eq!(def.value.as_deref(), Some("128"));
+ assert_eq!(def.text, "#define MINI_LIMIT 128");
+
+ // A query nothing matches is a 200 with no hits.
+ let r = h.get("/_hub/v1/code/mini-c?q=zzzzqqqq").await;
+ assert_eq!(r.status, StatusCode::OK);
+ assert!(r.answer().hits.is_empty());
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn code_max_tokens_holds_the_answer_and_says_so() {
+ let h = hub(Opts::new(false, false)).await;
+ // Two records mention `frobnicate` (NOTES.md and README.md); 10 tokens is
+ // 40 characters, which one passage fills and two cannot.
+ let full = h.get("/_hub/v1/code/mini-c?q=frobnicate").await.answer();
+ assert_eq!(full.hits.len(), 2, "{:#?}", full.hits);
+ assert!(!full.truncated, "without a budget nothing is cut");
+ assert!(full.warnings.is_empty());
+
+ let r = h
+ .get("/_hub/v1/code/mini-c?q=frobnicate&max_tokens=10")
+ .await;
+ assert_eq!(r.status, StatusCode::OK, "{:?}", r.json());
+ let a = r.answer();
+ let chars: usize = a.hits.iter().map(|x| x.text.chars().count()).sum();
+ assert!(chars <= 40, "{chars} characters over a 40-character budget");
+ assert!(
+ !a.hits.is_empty(),
+ "the budget cuts, it does not empty the answer"
+ );
+ assert!(
+ a.hits.len() < full.hits.len()
+ || chars < full.hits.iter().map(|x| x.text.chars().count()).sum(),
+ "something was held back"
+ );
+ assert!(a.truncated, "{a:#?}");
+ assert!(
+ a.warnings.iter().any(|w| w.contains("max_tokens=10")),
+ "{:?}",
+ a.warnings
+ );
+ // The hit that survives is the better-ranked one, and still cites its file.
+ assert_eq!(a.hits[0].file, full.hits[0].file);
+
+ for bad in ["0", "9999", "abc", "-1", ""] {
+ let r = h
+ .get(&format!("/_hub/v1/code/mini-c?q=x&max_tokens={bad}"))
+ .await;
+ assert_eq!(r.status, StatusCode::BAD_REQUEST, "max_tokens={bad}");
+ }
+ let r = h.get("/_hub/v1/code/mini-c?q=x&mode=nope").await;
+ assert_eq!(r.status, StatusCode::BAD_REQUEST);
+ // The other arms are accepted; the answer warns that it cannot say which ran.
+ let r = h.get("/_hub/v1/code/mini-c?q=mini_hash&mode=hybrid").await;
+ assert_eq!(r.status, StatusCode::OK, "{:?}", r.json());
+ assert!(r
+ .answer()
+ .warnings
+ .iter()
+ .any(|w| w.contains("semantic/hybrid")));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn search_groups_by_corpus_best_first_and_lists_only_servable_corpora() {
+ let h = hub(Opts::new(false, false)).await;
+ let r = h.get("/_hub/v1/search?q=frobnicate").await;
+ assert_eq!(r.status, StatusCode::OK, "{:?}", r.json());
+ let v = r.json();
+ assert_eq!(
+ v.as_object().unwrap().len(),
+ 1,
+ "exactly {{corpora: [...]}}"
+ );
+ let rows = v["corpora"].as_array().expect("corpora");
+ let slugs: Vec<&str> = rows.iter().map(|c| c["slug"].as_str().unwrap()).collect();
+ assert!(
+ slugs.contains(&"mini-c") && slugs.contains(&"mini-gpl"),
+ "{slugs:?}"
+ );
+ assert!(
+ !slugs.contains(&"mini-closed"),
+ "an excluded corpus is never served: {slugs:?}"
+ );
+ assert!(
+ !slugs.contains(&"orphan"),
+ "an index no catalogue entry lists is skipped: {slugs:?}"
+ );
+ let unique: std::collections::BTreeSet<_> = slugs.iter().collect();
+ assert_eq!(unique.len(), slugs.len(), "one row per corpus: {slugs:?}");
+ assert!(rows.len() <= 10);
+ let scores: Vec<f64> = rows
+ .iter()
+ .map(|c| c["best_score"].as_f64().unwrap())
+ .collect();
+ assert!(
+ scores.windows(2).all(|w| w[0] >= w[1]),
+ "best first: {scores:?}"
+ );
+ for row in rows {
+ let hit: Hit = serde_json::from_value(row["best_hit"].clone()).expect("best_hit is a Hit");
+ assert!(!hit.file.is_empty());
+ assert!((hit.score as f64 - row["best_score"].as_f64().unwrap()).abs() < 1e-3);
+ }
+ let gpl = rows.iter().find(|c| c["slug"] == "mini-gpl").unwrap();
+ assert_eq!(
+ gpl["best_hit"]["licence_warning"],
+ json!("approach-only licence (GPL-3.0-only): read, do not copy")
+ );
+
+ // A definition name finds the corpus through its -defs index.
+ let v = h.get("/_hub/v1/search?q=mini_clamp").await.json();
+ let top = &v["corpora"][0];
+ assert_eq!(top["slug"], "mini-c", "{v}");
+
+ // `k` bounds the number of corpora.
+ let v = h.get("/_hub/v1/search?q=frobnicate&k=1").await.json();
+ assert_eq!(v["corpora"].as_array().unwrap().len(), 1);
+
+ // Nothing matches: an empty list, not an error.
+ let r = h.get("/_hub/v1/search?q=zzzzqqqq").await;
+ assert_eq!(r.status, StatusCode::OK);
+ assert_eq!(r.json(), json!({"corpora": []}));
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn the_first_pack_restored_is_searchable_on_the_next_request() {
+ // `search` reuses the field list it resolved from the mappings for a minute.
+ // An empty node (no hub index yet) must not be remembered as "nothing to
+ // search": a node that has just restored its first pack answers at once.
+ let h = bare(&Opts::new(false, false));
+ let r = h.get("/_hub/v1/search?q=frobnicate").await;
+ assert_eq!(r.status, StatusCode::OK);
+ assert_eq!(r.json(), json!({"corpora": []}), "nothing restored yet");
+
+ h.create("xc-mini-c-b1-docs", docs_mapping()).await;
+ h.bulk(
+ "xc-mini-c-b1-docs",
+ &[json!({"ax_path": "mini-c/NOTES.md", "body": "frobnicate the buffer"})],
+ )
+ .await;
+ let r = h.admin("POST", "/xc-mini-c-b1-docs/_refresh", None).await;
+ assert!(r.status.is_success());
+
+ let v = h.get("/_hub/v1/search?q=frobnicate").await.json();
+ assert_eq!(v["corpora"][0]["slug"], "mini-c", "{v}");
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn def_and_code_agree_on_what_they_say_about_a_corpus() {
+ let h = hub(Opts::new(false, false)).await;
+ for (slug, sym, q) in [
+ ("mini-c", "MINI_LIMIT", "hash"),
+ ("mini-gpl", "GPL_LIMIT", "frobnicate"),
+ ] {
+ let d = h.get(&format!("/_hub/v1/def/{slug}/{sym}")).await.answer();
+ let c = h.get(&format!("/_hub/v1/code/{slug}?q={q}")).await.answer();
+ assert_eq!(
+ (
+ d.corpus,
+ d.pin_sha,
+ d.pin_date,
+ d.age_days,
+ d.licence_spdx,
+ d.licence_class,
+ d.answered_from
+ ),
+ (
+ c.corpus,
+ c.pin_sha,
+ c.pin_date,
+ c.age_days,
+ c.licence_spdx,
+ c.licence_class,
+ c.answered_from
+ ),
+ "{slug}: def and code must describe the corpus identically"
+ );
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn an_approach_only_corpus_tags_every_hit_with_its_licence() {
+ let h = hub(Opts::new(false, false)).await;
+ let want = "approach-only licence (GPL-3.0-only): read, do not copy";
+ let d = h.get("/_hub/v1/def/mini-gpl/GPL_LIMIT").await.answer();
+ assert_eq!(d.licence_class, LicenceClass::ApproachOnly);
+ assert_eq!(d.hits[0].licence_warning.as_deref(), Some(want));
+ let c = h.get("/_hub/v1/code/mini-gpl?q=frobnicate").await.answer();
+ assert!(!c.hits.is_empty());
+ assert!(c
+ .hits
+ .iter()
+ .all(|x| x.licence_warning.as_deref() == Some(want)));
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Validation
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn corpora_the_catalogue_does_not_serve_are_404() {
+ let h = hub(Opts::new(false, false)).await;
+ for path in [
+ "/_hub/v1/def/not-a-corpus/X",
+ "/_hub/v1/code/not-a-corpus?q=x",
+ // Listed but excluded: the same 404, so a caller cannot tell it exists.
+ "/_hub/v1/def/mini-closed/CLOSED_LIMIT",
+ "/_hub/v1/code/mini-closed?q=frobnicate",
+ // The catalogue permits it but this node's own ledger says excluded.
+ "/_hub/v1/def/ledger-closed/X",
+ "/_hub/v1/code/ledger-closed?q=x",
+ // Not a name at all.
+ "/_hub/v1/def/..%2F..%2Fetc/passwd",
+ "/_hub/v1/code/mini-c%00?q=x",
+ "/_hub/v1/code/-lead?q=x",
+ "/_hub/v1/code/mini-c*?q=x",
+ ] {
+ let r = h.get(path).await;
+ assert_eq!(r.status, StatusCode::NOT_FOUND, "{path}: {:?}", r.json());
+ assert_eq!(r.json()["status"], json!(404));
+ assert_eq!(
+ r.json()["error"]["type"],
+ json!("resource_not_found_exception"),
+ "{path}: refusals look alike"
+ );
+ }
+ // Listed, servable, but this node never pulled it: a different 404.
+ for path in ["/_hub/v1/def/ghost/X", "/_hub/v1/code/ghost?q=x"] {
+ let r = h.get(path).await;
+ assert_eq!(r.status, StatusCode::NOT_FOUND, "{path}");
+ assert_eq!(
+ r.json()["error"]["type"],
+ json!("corpus_not_loaded"),
+ "{path}"
+ );
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn k_is_clamped_to_fifty_and_garbage_k_is_400() {
+ let h = hub(Opts::new(false, false)).await;
+ let n = |v: Value| v["hits"].as_array().unwrap().len();
+ let r = h.get("/_hub/v1/def/mini-c/DUP_SYM?k=1000").await;
+ assert_eq!(r.status, StatusCode::OK, "{:?}", r.json());
+ assert_eq!(n(r.json()), 50, "sixty exist; k=1000 is clamped to 50");
+ assert_eq!(n(h.get("/_hub/v1/def/mini-c/DUP_SYM?k=2").await.json()), 2);
+ assert_eq!(
+ n(h.get("/_hub/v1/def/mini-c/DUP_SYM").await.json()),
+ 5,
+ "default k"
+ );
+ assert_eq!(
+ n(h.get("/_hub/v1/def/mini-c/DUP_SYM?k=50").await.json()),
+ 50
+ );
+ for bad in ["0", "-1", "abc", "1.5", ""] {
+ let r = h.get(&format!("/_hub/v1/def/mini-c/DUP_SYM?k={bad}")).await;
+ assert_eq!(r.status, StatusCode::BAD_REQUEST, "k={bad}");
+ }
+ // The pure parser agrees.
+ assert_eq!(hub_api::parse_k(Some("1000"), 5), Ok(50));
+ assert_eq!(hub_api::parse_k(None, 7), Ok(7));
+ assert!(hub_api::parse_k(Some("0"), 5).is_err());
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn oversized_blank_missing_and_stray_inputs_are_400() {
+ let h = hub(Opts::new(false, false)).await;
+ let big = "a".repeat(600);
+ let edge = "a".repeat(512);
+ for path in [
+ format!("/_hub/v1/code/mini-c?q={big}"),
+ format!("/_hub/v1/search?q={big}"),
+ format!("/_hub/v1/def/mini-c/{big}"),
+ "/_hub/v1/code/mini-c".to_string(),
+ "/_hub/v1/search".to_string(),
+ "/_hub/v1/code/mini-c?q=%20%20".to_string(),
+ "/_hub/v1/search?q=x&nope=1".to_string(),
+ "/_hub/v1/def/mini-c/MINI_LIMIT?q=x".to_string(),
+ "/_hub/v1/search?q=x&q=y".to_string(),
+ "/_hub/v1/def/mini-c/MINI_LIMIT?k=1&k=2".to_string(),
+ ] {
+ let r = h.get(&path).await;
+ assert_eq!(
+ r.status,
+ StatusCode::BAD_REQUEST,
+ "{}: {:?}",
+ &path[..path.len().min(60)],
+ r.json()
+ );
+ assert_eq!(
+ r.json()["error"]["type"],
+ json!("illegal_argument_exception")
+ );
+ }
+ // 512 bytes is the limit, not 511.
+ for path in [
+ format!("/_hub/v1/code/mini-c?q={edge}"),
+ format!("/_hub/v1/search?q={edge}"),
+ format!("/_hub/v1/def/mini-c/{edge}"),
+ ] {
+ let r = h.get(&path).await;
+ assert_eq!(r.status, StatusCode::OK, "{:?}", r.json());
+ }
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// hub.public
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_keyed_node_needs_the_key_on_all_four_routes() {
+ let h = hub(Opts::new(false, true)).await;
+ for path in FOUR {
+ let r = h.get(path).await;
+ assert_eq!(r.status, StatusCode::UNAUTHORIZED, "{path} without a key");
+ let r = h
+ .send(
+ Hub::req("GET", path)
+ .header(header::AUTHORIZATION, "ApiKey wrong")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await;
+ assert_eq!(
+ r.status,
+ StatusCode::UNAUTHORIZED,
+ "{path} with a wrong key"
+ );
+ let r = h.get_keyed(path).await;
+ assert_eq!(
+ r.status,
+ StatusCode::OK,
+ "{path} with the key: {:?}",
+ r.json()
+ );
+ // Only GET: with the key a POST is 405, without it 401 first.
+ let r = h.method_keyed("POST", path).await;
+ assert_eq!(
+ r.status,
+ StatusCode::METHOD_NOT_ALLOWED,
+ "POST {path} with the key"
+ );
+ let r = h.method("POST", path).await;
+ assert_eq!(
+ r.status,
+ StatusCode::UNAUTHORIZED,
+ "POST {path} without a key"
+ );
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_public_node_opens_exactly_the_four_routes() {
+ let h = hub(Opts::new(true, true)).await;
+ for path in FOUR {
+ let r = h.get(path).await;
+ assert_eq!(
+ r.status,
+ StatusCode::OK,
+ "{path} needs no key: {:?}",
+ r.json()
+ );
+ // Every other method is a 405 from the router, and needs no key either:
+ // there is no handler to protect, and nothing for the audit layer to log.
+ for m in ["POST", "PUT", "DELETE", "PATCH"] {
+ let r = h.method(m, path).await;
+ assert_eq!(r.status, StatusCode::METHOD_NOT_ALLOWED, "{m} {path}");
+ let allow = r.header("allow").unwrap_or_default();
+ assert!(allow.contains("GET"), "{m} {path}: Allow: {allow}");
+ }
+ }
+ // HEAD is GET without a body: public like GET, and nothing more.
+ let r = h.method("HEAD", FOUR[0]).await;
+ assert_eq!(r.status, StatusCode::OK);
+ assert!(r.body.is_empty());
+ assert!(r.header("etag").is_some());
+ // The key still works on a public node.
+ assert_eq!(h.get_keyed(FOUR[1]).await.status, StatusCode::OK);
+
+ // Near misses are NOT public: a different shape falls through to
+ // authentication like any other path.
+ for path in [
+ "/_hub/v1/def/mini-c",
+ "/_hub/v1/def/mini-c/MINI_LIMIT/extra",
+ "/_hub/v1/def//MINI_LIMIT",
+ "/_hub/v1/code",
+ "/_hub/v1/code/mini-c/extra",
+ "/_hub/v1/code/",
+ "/_hub/v1/search/",
+ "/_hub/v1//search",
+ "/_hub/v1/catalogue/",
+ "/_hub/v1/catalogue/x",
+ "/_hub/v1/other",
+ "/_hub/v1",
+ "/_hub",
+ "/_HUB/v1/search",
+ "/_hub/v2/search",
+ "/x/_hub/v1/search",
+ "/_hub/v1/../v1/search",
+ ] {
+ let r = h.get(path).await;
+ assert_eq!(
+ r.status,
+ StatusCode::UNAUTHORIZED,
+ "{path} must keep authentication"
+ );
+ }
+ // Everything else on the node keeps authentication, and a hub-looking query
+ // string does not change what the path is.
+ for path in [
+ "/_cluster/health",
+ "/_cat/indices",
+ "/xc-mini-c-b1-defs/_search",
+ "/xc-mini-c-b1-defs/_mapping",
+ "/_memory/x",
+ "/_cluster/health?next=/_hub/v1/search",
+ "/_aliases",
+ ] {
+ let r = h.get(path).await;
+ assert_eq!(
+ r.status,
+ StatusCode::UNAUTHORIZED,
+ "{path} must keep authentication"
+ );
+ }
+ let r = h.method("POST", "/xc-mini-c-b1-defs/_search").await;
+ assert_eq!(r.status, StatusCode::UNAUTHORIZED);
+ assert_eq!(
+ h.get("/health/live").await.status,
+ StatusCode::OK,
+ "probes are unchanged"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn unauthenticated_hub_traffic_cannot_write_the_audit_ring() {
+ let h = hub(Opts::new(true, true)).await;
+ let audit = &h.state.engine.audit;
+
+ // A flood of non-GET requests to the public paths and of 401s elsewhere
+ // leaves nothing: the audit layer records unauthenticated write-shaped
+ // requests, and it must not see these.
+ let before = audit.next_seq();
+ // 4 rounds x 13 hub requests = 52, inside the 60-a-minute budget, so each
+ // one reaches the layer that would have recorded it.
+ for _ in 0..4 {
+ for path in FOUR {
+ for m in ["POST", "PUT", "DELETE"] {
+ h.method(m, path).await;
+ }
+ }
+ h.get("/_hub/v1/search/").await;
+ h.get("/_cluster/health").await;
+ h.get(FOUR[0]).await;
+ }
+ assert_eq!(
+ audit.next_seq(),
+ before,
+ "no entry from unauthenticated hub traffic"
+ );
+
+ // A hosted search is the one thing that does append: the `_search` handler
+ // audits itself, unconditionally (documented in hub_api.rs).
+ h.get(FOUR[1]).await;
+ let after = audit.snapshot();
+ let new: Vec<_> = after.iter().filter(|e| e.seq >= before).collect();
+ assert!(
+ !new.is_empty() && new.iter().all(|e| e.op == "search"),
+ "{new:?}"
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_node_without_a_usable_catalogue_says_so() {
+ fixture();
+ let dir = tempfile::tempdir().unwrap();
+
+ // No catalogue_path at all.
+ let mut o = Opts::new(false, false);
+ o.catalogue_path = Some(String::new());
+ let (state, _d1) = build(&o);
+ let app = xerj_api::router::build_es_compat_router(state);
+ let status = |app: axum::Router, path: &'static str| async move {
+ app.oneshot(Request::get(path).body(Body::empty()).unwrap())
+ .await
+ .unwrap()
+ .status()
+ };
+ assert_eq!(
+ status(app.clone(), "/_hub/v1/catalogue").await,
+ StatusCode::NOT_FOUND
+ );
+ assert_eq!(
+ status(app.clone(), "/_hub/v1/def/mini-c/X").await,
+ StatusCode::NOT_FOUND
+ );
+
+ // A path that does not exist.
+ let mut o = Opts::new(false, false);
+ o.catalogue_path = Some(
+ dir.path()
+ .join("missing.json")
+ .to_string_lossy()
+ .into_owned(),
+ );
+ let (state, _d2) = build(&o);
+ let app = xerj_api::router::build_es_compat_router(state);
+ assert_eq!(
+ status(app.clone(), "/_hub/v1/catalogue").await,
+ StatusCode::SERVICE_UNAVAILABLE
+ );
+ assert_eq!(
+ status(app, "/_hub/v1/search?q=x").await,
+ StatusCode::SERVICE_UNAVAILABLE
+ );
+
+ // A file that is not a catalogue: the bytes are still served (a client
+ // verifies the signature itself) but nothing is validated against them.
+ let junk = dir.path().join("junk.json");
+ std::fs::write(&junk, b"{\"not\": \"a catalogue\"}").unwrap();
+ let mut o = Opts::new(false, false);
+ o.catalogue_path = Some(junk.to_string_lossy().into_owned());
+ let (state, _d3) = build(&o);
+ let app = xerj_api::router::build_es_compat_router(state);
+ assert_eq!(
+ status(app.clone(), "/_hub/v1/catalogue").await,
+ StatusCode::OK
+ );
+ assert_eq!(
+ status(app.clone(), "/_hub/v1/def/mini-c/X").await,
+ StatusCode::SERVICE_UNAVAILABLE
+ );
+ assert_eq!(
+ status(app, "/_hub/v1/search?q=x").await,
+ StatusCode::SERVICE_UNAVAILABLE
+ );
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Rate limiting
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn the_61st_request_in_a_minute_from_one_address_is_429() {
+ let h = hub(Opts::new(true, true)).await;
+ let path = "/_hub/v1/catalogue";
+ for i in 1..=60 {
+ let r = h.get_from(path, "203.0.113.7", None).await;
+ assert_eq!(r.status, StatusCode::OK, "request {i}");
+ }
+ let r = h.get_from(path, "203.0.113.7", None).await;
+ assert_eq!(r.status, StatusCode::TOO_MANY_REQUESTS, "the 61st");
+ let retry: u64 = r
+ .header("retry-after")
+ .expect("Retry-After")
+ .parse()
+ .expect("seconds");
+ assert!((1..=60).contains(&retry), "Retry-After: {retry}");
+ assert_eq!(r.json()["error"]["type"], json!("too_many_requests"));
+ assert_eq!(r.json()["status"], json!(429));
+ // It stays limited, on every route, whatever the method: the limit sits in
+ // front of the router's own 405.
+ for p in FOUR {
+ assert_eq!(
+ h.get_from(p, "203.0.113.7", None).await.status,
+ StatusCode::TOO_MANY_REQUESTS
+ );
+ }
+ assert_eq!(
+ h.method_from("POST", path, "203.0.113.7").await.status,
+ StatusCode::TOO_MANY_REQUESTS
+ );
+
+ // A non-GET spends budget too: 59 GETs, one POST (a 405, but counted), and the
+ // next GET is refused.
+ for _ in 0..59 {
+ assert_eq!(
+ h.get_from(path, "203.0.113.9", None).await.status,
+ StatusCode::OK
+ );
+ }
+ assert_eq!(
+ h.method_from("POST", path, "203.0.113.9").await.status,
+ StatusCode::METHOD_NOT_ALLOWED
+ );
+ assert_eq!(
+ h.get_from(path, "203.0.113.9", None).await.status,
+ StatusCode::TOO_MANY_REQUESTS
+ );
+
+ // Another address has its own budget.
+ assert_eq!(
+ h.get_from(path, "203.0.113.8", None).await.status,
+ StatusCode::OK
+ );
+
+ // A header the caller writes does not buy a fresh one: the peer decides.
+ for n in 0..5 {
+ let r = h
+ .get_from(path, "203.0.113.7", Some(&format!("198.51.100.{n}")))
+ .await;
+ assert_eq!(
+ r.status,
+ StatusCode::TOO_MANY_REQUESTS,
+ "X-Forwarded-For is not believed"
+ );
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn an_ipv6_host_shares_one_budget_across_its_64() {
+ let h = hub(Opts::new(true, true)).await;
+ let path = "/_hub/v1/catalogue";
+ // Sixty different addresses out of one /64: one budget.
+ for n in 0..60 {
+ let peer = format!("[2001:db8:1:2::{n:x}]");
+ assert_eq!(h.get_from(path, &peer, None).await.status, StatusCode::OK);
+ }
+ assert_eq!(
+ h.get_from(path, "[2001:db8:1:2:ffff::1]", None)
+ .await
+ .status,
+ StatusCode::TOO_MANY_REQUESTS
+ );
+ assert_eq!(
+ h.get_from(path, "[2001:db8:1:3::1]", None).await.status,
+ StatusCode::OK
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn behind_a_declared_proxy_the_forwarded_client_is_the_bucket() {
+ let mut o = Opts::new(true, true);
+ o.trusted_proxies = vec!["10.0.0.0/8".into()];
+ let h = hub(o).await;
+ let path = "/_hub/v1/catalogue";
+ for _ in 0..60 {
+ let r = h.get_from(path, "10.0.0.1", Some("198.51.100.1")).await;
+ assert_eq!(r.status, StatusCode::OK);
+ }
+ assert_eq!(
+ h.get_from(path, "10.0.0.1", Some("198.51.100.1"))
+ .await
+ .status,
+ StatusCode::TOO_MANY_REQUESTS,
+ "that client is spent"
+ );
+ assert_eq!(
+ h.get_from(path, "10.0.0.1", Some("198.51.100.2"))
+ .await
+ .status,
+ StatusCode::OK,
+ "another client behind the same proxy is not"
+ );
+ // An undeclared peer cannot claim to be somebody else.
+ assert_eq!(
+ h.get_from(path, "192.0.2.9", Some("198.51.100.99"))
+ .await
+ .status,
+ StatusCode::OK
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn the_limit_holds_on_a_keyed_node_too() {
+ let h = hub(Opts::new(false, true)).await;
+ let mut statuses = Vec::new();
+ for _ in 0..61 {
+ let mut req = Hub::req("GET", "/_hub/v1/catalogue")
+ .header(header::AUTHORIZATION, format!("ApiKey {ADMIN_KEY}"))
+ .body(Body::empty())
+ .unwrap();
+ req.extensions_mut()
+ .insert(ConnectInfo("203.0.113.40:1".parse::<SocketAddr>().unwrap()));
+ statuses.push(h.send(req).await.status);
+ }
+ assert!(
+ statuses[..60].iter().all(|s| *s == StatusCode::OK),
+ "{statuses:?}"
+ );
+ assert_eq!(statuses[60], StatusCode::TOO_MANY_REQUESTS);
+}
+
+#[test]
+fn the_limiter_is_a_sliding_window_with_bounded_memory() {
+ let t0 = Instant::now();
+ let l = RateLimiter::new(3, Duration::from_secs(60), 100);
+ assert_eq!(l.admit("a", t0), Ok(()));
+ assert_eq!(l.admit("a", t0 + Duration::from_secs(10)), Ok(()));
+ assert_eq!(l.admit("a", t0 + Duration::from_secs(20)), Ok(()));
+ // Full: the oldest ages out at t0+60s, so 40 seconds from t0+20s.
+ assert_eq!(l.admit("a", t0 + Duration::from_secs(20)), Err(40));
+ // Refusals are not recorded, so hammering does not extend the wait.
+ assert_eq!(l.admit("a", t0 + Duration::from_secs(21)), Err(39));
+ // One request ages out at t0+60s and exactly one slot opens.
+ assert_eq!(l.admit("a", t0 + Duration::from_secs(60)), Ok(()));
+ assert!(l.admit("a", t0 + Duration::from_secs(60)).is_err());
+ // Never "0 seconds": a sub-second wait rounds up.
+ assert_eq!(l.admit("a", t0 + Duration::from_millis(69_999)), Err(1));
+ // A second client is independent.
+ assert_eq!(l.admit("b", t0), Ok(()));
+
+ // Past the table cap, unseen addresses share one overflow bucket.
+ let small = RateLimiter::new(1, Duration::from_secs(60), 2);
+ assert_eq!(small.admit("c1", t0), Ok(()));
+ assert_eq!(small.admit("c2", t0), Ok(()));
+ assert_eq!(small.admit("c3", t0), Ok(()), "first overflow request");
+ assert!(
+ small.admit("c4", t0).is_err(),
+ "later strangers share that bucket"
+ );
+ // …and the table is reclaimed once the window has passed.
+ assert_eq!(small.admit("c5", t0 + Duration::from_secs(61)), Ok(()));
+}
+
+#[test]
+fn client_buckets_collapse_ipv6_to_the_64() {
+ assert_eq!(hub_api::client_bucket("203.0.113.9"), "203.0.113.9");
+ assert_eq!(
+ hub_api::client_bucket("2001:db8:1:2:aaaa:bbbb:cccc:dddd"),
+ hub_api::client_bucket("2001:db8:1:2::1")
+ );
+ assert_eq!(
+ hub_api::client_bucket("2001:db8:1:2::1"),
+ "2001:db8:1:2::/64"
+ );
+ assert_ne!(
+ hub_api::client_bucket("2001:db8:1:3::1"),
+ hub_api::client_bucket("2001:db8:1:2::1")
+ );
+ assert_eq!(hub_api::client_bucket("unknown"), "unknown");
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// A real socket on an ephemeral port
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// One HTTP/1.0 GET over a real connection: (status, lower-cased headers, body).
+async fn raw_get(
+ addr: SocketAddr,
+ path: &str,
+ extra: &[(&str, &str)],
+) -> (u16, Vec<(String, String)>, String) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let mut stream = tokio::net::TcpStream::connect(addr).await.expect("connect");
+ let mut head = format!("GET {path} HTTP/1.0\r\nHost: hub.test\r\n");
+ for (k, v) in extra {
+ head.push_str(&format!("{k}: {v}\r\n"));
+ }
+ head.push_str("\r\n");
+ stream.write_all(head.as_bytes()).await.expect("write");
+ let mut raw = Vec::new();
+ stream.read_to_end(&mut raw).await.expect("read");
+ let text = String::from_utf8_lossy(&raw).into_owned();
+ let (head, body) = text.split_once("\r\n\r\n").expect("a response");
+ let mut lines = head.lines();
+ let status: u16 = lines
+ .next()
+ .unwrap()
+ .split_whitespace()
+ .nth(1)
+ .unwrap()
+ .parse()
+ .unwrap();
+ let headers = lines
+ .filter_map(|l| l.split_once(':'))
+ .map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_string()))
+ .collect();
+ (status, headers, body.to_string())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn over_a_real_socket_the_peer_address_is_the_bucket() {
+ fixture();
+ let o = Opts::new(true, true);
+ let (state, _data) = build(&o);
+ let app = xerj_api::router::build_es_compat_router(state);
+ // Port 0: the OS picks a free one. Never 9200, never the reference nodes.
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind");
+ let addr = listener.local_addr().unwrap();
+ assert_ne!(addr.port(), 9200);
+ tokio::spawn(async move {
+ let _ = axum::serve(
+ listener,
+ app.into_make_service_with_connect_info::<SocketAddr>(),
+ )
+ .await;
+ });
+
+ // Public, no key, over the wire.
+ let (status, headers, body) = raw_get(addr, "/_hub/v1/catalogue", &[]).await;
+ assert_eq!(status, 200);
+ assert!(headers
+ .iter()
+ .any(|(k, v)| k == "cache-control" && v == "public, max-age=3600"));
+ assert!(body.contains("\"corpora\""));
+ // …and the rest of the node is still closed.
+ let (status, _, _) = raw_get(addr, "/_cluster/health", &[]).await;
+ assert_eq!(status, 401);
+
+ // 59 more are admitted, the 61st overall is not — and a forged
+ // X-Forwarded-For does not help, because the peer (127.0.0.1) is not a
+ // declared proxy.
+ for _ in 0..59 {
+ let (status, _, _) = raw_get(addr, "/_hub/v1/catalogue", &[]).await;
+ assert_eq!(status, 200);
+ }
+ let (status, headers, _) = raw_get(
+ addr,
+ "/_hub/v1/catalogue",
+ &[("X-Forwarded-For", "198.51.100.77")],
+ )
+ .await;
+ assert_eq!(status, 429);
+ assert!(headers.iter().any(|(k, _)| k == "retry-after"));
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// What stands behind the routes
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn an_alias_cannot_lead_a_hosted_query_out_of_the_hub_namespace() {
+ let h = hub(Opts::new(false, true)).await;
+ // The alias is real: with the key, the ordinary API reads the private index
+ // through it. (Without this the assertion below proves nothing.)
+ let r = h
+ .send(
+ Hub::req("POST", "/xc-leaky-b1-defs/_search")
+ .header(header::AUTHORIZATION, format!("ApiKey {ADMIN_KEY}"))
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(Body::from(
+ json!({"query": {"term": {"symbol": "SECRET"}}}).to_string(),
+ ))
+ .unwrap(),
+ )
+ .await;
+ assert!(
+ String::from_utf8_lossy(&r.body).contains("hunter2"),
+ "fixture sanity: the alias resolves to the private index: {:?}",
+ r.json()
+ );
+
+ // Through the hosted route the same name finds nothing.
+ let r = h.get_keyed("/_hub/v1/def/leaky/SECRET").await;
+ assert!(
+ !String::from_utf8_lossy(&r.body).contains("hunter2"),
+ "the private index leaked through an alias: {:?}",
+ r.json()
+ );
+ let a = r.answer();
+ assert!(a.hits.is_empty(), "{a:?}");
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_backend_failure_is_a_fixed_503_that_names_nothing() {
+ let h = hub(Opts::new(false, false)).await;
+ for path in ["/_hub/v1/def/badprefix/X", "/_hub/v1/code/badprefix?q=x"] {
+ let r = h.get(path).await;
+ assert_eq!(
+ r.status,
+ StatusCode::SERVICE_UNAVAILABLE,
+ "{path}: {:?}",
+ r.json()
+ );
+ assert_eq!(r.json()["error"]["type"], json!("hub_unavailable"));
+ let text = String::from_utf8_lossy(&r.body).to_string();
+ for leaked in ["bad prefix", "refused", "x=1", "xc-", "HTTP", "state"] {
+ assert!(!text.contains(leaked), "{path} leaked {leaked:?}: {text}");
+ }
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn a_full_house_is_a_503_with_retry_after_and_recovers() {
+ fixture();
+ let (state, _data) = build(&Opts::new(false, false));
+ // The routes alone, with a handle on the shared state, so the test can hold
+ // every query slot the way sixteen slow queries would.
+ let shared = hub_api::HubShared::new(state);
+ let app: axum::Router = hub_api::routes(shared.clone());
+ let held = shared.hold_slots_for_test(hub_api::MAX_CONCURRENT_QUERIES);
+ assert_eq!(held.len(), hub_api::MAX_CONCURRENT_QUERIES);
+
+ let get = |app: axum::Router, path: &'static str| async move {
+ app.oneshot(Request::get(path).body(Body::empty()).unwrap())
+ .await
+ .unwrap()
+ };
+ let r = get(app.clone(), "/_hub/v1/def/mini-c/MINI_LIMIT").await;
+ assert_eq!(r.status(), StatusCode::SERVICE_UNAVAILABLE);
+ assert_eq!(r.headers().get("retry-after").unwrap(), "1");
+ // The catalogue needs no engine query, so it is not held up.
+ assert_eq!(
+ get(app.clone(), "/_hub/v1/catalogue").await.status(),
+ StatusCode::OK
+ );
+
+ drop(held);
+ let r = get(app, "/_hub/v1/def/mini-c/MINI_LIMIT").await;
+ // Free again: the query runs (the node has no indices, so the corpus is
+ // known to the ledger but not loaded — a 404, not a 503).
+ assert_eq!(r.status(), StatusCode::NOT_FOUND);
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Pure helpers
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[test]
+fn only_the_four_exact_shapes_are_public() {
+ for yes in [
+ "/_hub/v1/catalogue",
+ "/_hub/v1/search",
+ "/_hub/v1/code/lz4",
+ "/_hub/v1/def/lz4/LZ4_VERSION_RELEASE",
+ "/_hub/v1/def/lz4/a%2Fb",
+ ] {
+ assert!(hub_api::is_public_path(yes), "{yes}");
+ }
+ for no in [
+ "",
+ "/",
+ "/_hub",
+ "/_hub/",
+ "/_hub/v1",
+ "/_hub/v1/",
+ "/_hub/v1/catalogue/",
+ "/_hub/v1/catalogue/x",
+ "/_hub/v1/search/",
+ "/_hub/v1/code",
+ "/_hub/v1/code/",
+ "/_hub/v1/code/lz4/",
+ "/_hub/v1/code/lz4/x",
+ "/_hub/v1/def",
+ "/_hub/v1/def/lz4",
+ "/_hub/v1/def/lz4/",
+ "/_hub/v1/def//X",
+ "/_hub/v1/def/lz4/X/",
+ "/_hub/v1/def/lz4/X/Y",
+ "/_hub/v1//catalogue",
+ "/_hub/v1/Catalogue",
+ "/_Hub/v1/catalogue",
+ "/_hub/v2/catalogue",
+ "_hub/v1/catalogue",
+ "//_hub/v1/catalogue",
+ "/a/_hub/v1/catalogue",
+ "/_hub/v1/../catalogue",
+ ] {
+ assert!(!hub_api::is_public_path(no), "{no:?}");
+ }
+}
+
+#[test]
+fn an_index_maps_back_to_its_corpus_by_the_stamped_build_rule() {
+ let known: std::collections::HashMap<String, ()> = ["lz4", "mini-c", "a", "a-b1", "rust-vulns"]
+ .iter()
+ .map(|s| (s.to_string(), ()))
+ .collect();
+ let slug = |i: &str| hub_api::slug_of_index(i, &known);
+ assert_eq!(slug("xc-lz4-b1-defs"), Some("lz4"));
+ assert_eq!(slug("xc-lz4-b1-docs"), Some("lz4"));
+ assert_eq!(slug("xc-mini-c-b17-docs"), Some("mini-c"));
+ assert_eq!(slug("xc-rust-vulns-b1700000000-defs"), Some("rust-vulns"));
+ assert_eq!(slug("xc-lz4-b1"), Some("lz4"), "the stamped prefix itself");
+ assert_eq!(
+ slug("xc-lz4-b1-tests-b2-x-docs"),
+ Some("lz4"),
+ "a dataset named like a build"
+ );
+ // Not stamped builds: legacy `xc-<name>-<dataset>`, a non-numeric stamp,
+ // digits glued to letters, no stamp.
+ assert_eq!(slug("xc-lz4-docs"), None);
+ assert_eq!(slug("xc-lz4-bx-docs"), None);
+ assert_eq!(slug("xc-lz4-b1x-docs"), None);
+ assert_eq!(slug("xc-lz4-b-docs"), None);
+ // Not hub names, or not listed.
+ assert_eq!(slug("lz4-b1-docs"), None);
+ assert_eq!(slug("xc-other-b1-docs"), None);
+ assert_eq!(slug("secret-notes"), None);
+ // `a` and `a-b1` both fit `xc-a-b1-b2-docs`: the shortest wins, always.
+ assert_eq!(slug("xc-a-b1-b2-docs"), Some("a"));
+}
+
+#[test]
+fn the_token_budget_cuts_in_rank_order_and_says_what_it_did() {
+ let hit = |text: &str, score: f32| Hit {
+ file: "f".into(),
+ line: 1,
+ kind: "passage".into(),
+ text: text.into(),
+ value: None,
+ score,
+ licence_warning: None,
+ };
+ // 3 tokens = 12 characters.
+ let mut hits = vec![
+ hit("aaaaaaaa", 3.0),
+ hit("bbbbbbbb", 2.0),
+ hit("cccccccc", 1.0),
+ ];
+ let mut warnings = vec![];
+ assert!(hub_api::apply_token_budget(&mut hits, 3, &mut warnings));
+ let texts: Vec<&str> = hits.iter().map(|h| h.text.as_str()).collect();
+ assert_eq!(
+ texts,
+ ["aaaaaaaa", "bbbb"],
+ "the second is cut to what is left, the third dropped"
+ );
+ assert!(
+ warnings[0].contains("max_tokens=3") && warnings[0].contains("1 lower-ranked"),
+ "{warnings:?}"
+ );
+
+ // It fits: untouched, no warning.
+ let mut hits = vec![hit("aaaa", 1.0), hit("bbbb", 1.0)];
+ let mut warnings = vec![];
+ assert!(!hub_api::apply_token_budget(&mut hits, 2, &mut warnings));
+ assert_eq!(hits.len(), 2);
+ assert!(warnings.is_empty());
+
+ // Characters, not bytes.
+ let mut hits = vec![hit("ééééééééé", 1.0)];
+ assert!(hub_api::apply_token_budget(&mut hits, 1, &mut vec![]));
+ assert_eq!(hits[0].text, "éééé");
+
+ assert_eq!(hub_api::passage_width(None), 800);
+ assert_eq!(hub_api::passage_width(Some(10)), 40);
+ assert_eq!(
+ hub_api::passage_width(Some(8192)),
+ 800,
+ "never wider than the CLI's default"
+ );
+}
+
+#[test]
+fn the_search_field_gate_keeps_only_fields_some_index_maps() {
+ let mapping = json!({
+ "xc-a-b1-defs": {"mappings": {"properties": {"symbol_text": {"type": "text"}, "symbol": {"type": "keyword"}}}},
+ "xc-a-b1-docs": {"mappings": {"properties": {"body": {"type": "text"}}}},
+ });
+ assert_eq!(
+ hub_api::mapped_search_fields(&mapping),
+ vec!["body", "symbol_text"]
+ );
+ assert!(hub_api::mapped_search_fields(&json!({})).is_empty());
+ assert!(hub_api::mapped_search_fields(&json!(null)).is_empty());
+}
+
+#[test]
+fn slugs_are_plain_names() {
+ let (l64, l65) = ("a".repeat(64), "a".repeat(65));
+ for ok in ["lz4", "rust-vulns", "c++", "a.b_c", "0day", l64.as_str()] {
+ assert!(hub_api::valid_slug(ok), "{ok}");
+ }
+ for bad in [
+ "",
+ "-x",
+ ".x",
+ "_x",
+ "a/b",
+ "a b",
+ "a*",
+ "a\0",
+ "a?b",
+ "a%2f",
+ "é",
+ l65.as_str(),
+ ] {
+ assert!(!hub_api::valid_slug(bad), "{bad:?}");
+ }
+}
+
+#[test]
+fn if_none_match_handles_the_forms_a_cache_sends() {
+ use axum::http::HeaderValue;
+ let m =
+ |h: &str, etag: &str| hub_api::etag_matches(Some(&HeaderValue::from_str(h).unwrap()), etag);
+ assert!(m("\"abc\"", "\"abc\""));
+ assert!(m("W/\"abc\"", "\"abc\""));
+ assert!(m("\"x\", \"abc\"", "\"abc\""));
+ assert!(m("*", "\"abc\""));
+ assert!(!m("\"abd\"", "\"abc\""));
+ assert!(!m("abc", "\"abc\""), "an unquoted tag is not a validator");
+ assert!(!hub_api::etag_matches(None, "\"abc\""));
+}
+
+#[test]
+fn the_fixture_dir_is_the_shared_one() {
+ // Guards the premise of the whole file: one fixture, created once.
+ let a = fixture().dir.clone();
+ let b = fixture().dir.clone();
+ assert_eq!(a, b);
+ assert_eq!(
+ std::env::var("XERJ_CODE_HOME").unwrap(),
+ a.join("code-home").to_string_lossy()
+ );
+}
diff --git a/engine/crates/xerj-common/src/config.rs b/engine/crates/xerj-common/src/config.rs
index b82047971..565a83060 100644
--- a/engine/crates/xerj-common/src/config.rs
+++ b/engine/crates/xerj-common/src/config.rs
@@ -1,6 +1,6 @@
//! xerj configuration system.
//!
-//! Configuration is intentionally minimal: **130 settings** versus
+//! Configuration is intentionally minimal: **132 settings** versus
//! Elasticsearch's 3000+. Every option is named, documented, and has a sensible
//! production-ready default. The format is TOML, loaded from a single file.
//!
@@ -102,9 +102,13 @@ pub struct Config {
/// nearest-neighbour vote — 8 settings. Inert until `decisions.index`
/// names an index that exists.
pub decisions: DecisionsConfig,
+ /// Corpus Hub hosted read-only endpoints (`/_hub/v1/…`) — 2 settings.
+ /// Inert until `hub.catalogue_path` names a catalogue file; the routes
+ /// need an API key unless `hub.public` is switched on.
+ pub hub: HubConfig,
}
-// 23 sub-configs, 130 leaf settings in total. Do not maintain that sum by hand
+// 24 sub-configs, 132 leaf settings in total. Do not maintain that sum by hand
// — `journey_zero_config` in xerj-engine/tests/product_experience.rs counts a
// serialised `Config::default()` and fails if this comment and the module
// header stop matching. `Default` is derived: every field is a sub-config that
@@ -235,6 +239,17 @@ impl Config {
return Err(XerjError::config(reason));
}
+ // Hub: a public node validates every corpus name against the
+ // catalogue, so a public node with no catalogue answers 404 to
+ // everything while appearing to be up. Refuse that at boot.
+ if self.hub.public && self.hub.catalogue_path.trim().is_empty() {
+ return Err(XerjError::config(
+ "hub.public = true requires hub.catalogue_path: the public routes validate \
+ every corpus name against the catalogue, and with none every request \
+ would be a 404",
+ ));
+ }
+
// Compression: block_size_docs is documented as 16–4096 and was
// accepted at any value (#318 got `999999` past startup in silence).
// Range-check it even though the knob is dormant: an out-of-range
@@ -535,7 +550,7 @@ impl Config {
}
// ═════════════════════════════════════════════════════════════════════════════
-// Sub-configs (130 user-facing settings total; counted by
+// Sub-configs (132 user-facing settings total; counted by
// `journey_zero_config`, not by hand)
// ═════════════════════════════════════════════════════════════════════════════
@@ -2684,6 +2699,37 @@ impl Default for DecisionsConfig {
}
}
}
+
+/// Corpus Hub hosted endpoints: four read-only `GET` routes under
+/// `/_hub/v1/` that answer from the pre-indexed packs restored on this node
+/// (`catalogue`, `def/{slug}/{symbol}`, `code/{slug}`, `search`). They are
+/// served on the Elasticsearch-compatible listener (`server.es_compat_port`),
+/// next to `/_memory`, not on the native one.
+///
+/// **2 settings.**
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(default, deny_unknown_fields)]
+pub struct HubConfig {
+ /// Let those four routes — and nothing else — answer without an API key
+ /// (default: `false`, every route needs a key).
+ ///
+ /// With `true`, `GET /_hub/v1/catalogue`, `/_hub/v1/def/{slug}/{symbol}`,
+ /// `/_hub/v1/code/{slug}` and `/_hub/v1/search` skip authentication,
+ /// authorization and the audit log. Every other route on the node keeps
+ /// all three. The four routes are read-only, only ever query `xc-*`
+ /// indices, and are rate-limited to 60 requests a minute per client
+ /// address (`429` with `Retry-After`). Behind a reverse proxy, list the
+ /// proxy in `server.trusted_proxies`; without it every client shares the
+ /// proxy's address and therefore one 60-a-minute budget.
+ pub public: bool,
+ /// Path to the signed `catalogue.json` this node serves at
+ /// `GET /_hub/v1/catalogue` and validates every corpus name against
+ /// (default: `""` — none). A corpus name that is not in the file is a
+ /// `404`. Required when `public = true`. Prefer an absolute path: a
+ /// relative one resolves against the server's working directory.
+ pub catalogue_path: String,
+}
+
// ═════════════════════════════════════════════════════════════════════════════
// Tests
// ═════════════════════════════════════════════════════════════════════════════
@@ -2712,6 +2758,35 @@ mod tests {
assert!(RerankProviderConfig::check_resolved_endpoint(bad, Some(good)).is_err());
}
+ /// `[hub]` is closed and fail-closed: a typo is a boot error, the
+ /// defaults leave every route behind the API key, and a public node with
+ /// no catalogue is refused rather than left answering 404 to everything.
+ #[test]
+ fn hub_section_defaults_closed_and_public_requires_a_catalogue() {
+ let d = Config::default();
+ assert!(!d.hub.public, "the hosted routes are keyed by default");
+ assert!(d.hub.catalogue_path.is_empty());
+
+ let ok = Config::from_toml_str(
+ "[hub]\npublic = true\ncatalogue_path = \"/srv/hub/catalogue.json\"\n",
+ )
+ .expect("a public node with a catalogue is valid");
+ assert!(ok.hub.public);
+ assert_eq!(ok.hub.catalogue_path, "/srv/hub/catalogue.json");
+
+ let err = Config::from_toml_str("[hub]\npublic = true\n")
+ .expect_err("public without a catalogue must be refused at boot");
+ assert!(
+ err.to_string().contains("hub.catalogue_path"),
+ "the error names the setting to set: {err}"
+ );
+ // A private node needs no catalogue to boot.
+ Config::from_toml_str("[hub]\npublic = false\n").expect("private, no catalogue");
+
+ // Closed: a misspelt key is an error, not a silently ignored line.
+ assert!(Config::from_toml_str("[hub]\npubic = true\n").is_err());
+ }
+
#[test]
fn default_config_is_valid() {
Config::default()
@@ -3600,6 +3675,7 @@ mod tests {
("wal_tap", 10),
("rerank", 3),
("decisions", 8),
+ ("hub", 2),
];
/// Count the settings by *counting them*.
@@ -3642,7 +3718,7 @@ mod tests {
"the section table must sum to the whole config"
);
assert_eq!(
- total, 130,
+ total, 132,
"the total settings count changed. It is quoted in this module's \
header, in xerj-common/src/lib.rs, in engine/README.md, in \
xerj.default.toml and in EXPECTED_SETTINGS in \
diff --git a/engine/crates/xerj-common/src/lib.rs b/engine/crates/xerj-common/src/lib.rs
index 741c09415..8867ec4ff 100644
--- a/engine/crates/xerj-common/src/lib.rs
+++ b/engine/crates/xerj-common/src/lib.rs
@@ -7,13 +7,13 @@
//! ## Design philosophy
//!
//! Unlike Elasticsearch's 3000+ configuration knobs, xerj deliberately exposes
-//! **130 settings**, each meaningful and production-tested. Every default
+//! **132 settings**, each meaningful and production-tested. Every default
//! is chosen so that a fresh deployment with zero configuration changes performs
//! well for the majority of workloads.
//!
//! ## Modules
//!
-//! - [`config`] — TOML-based configuration (130 settings)
+//! - [`config`] — TOML-based configuration (132 settings)
//! - [`feedback`] — the bug/UX-report invitation shared by every `--help`
//! - [`error`] — Unified error type ([`XerjError`])
//! - [`types`] — Core domain types (documents, fields, IDs)
diff --git a/engine/crates/xerj-engine/tests/product_experience.rs b/engine/crates/xerj-engine/tests/product_experience.rs
index 3481e4ae1..7f5065c13 100644
--- a/engine/crates/xerj-engine/tests/product_experience.rs
+++ b/engine/crates/xerj-engine/tests/product_experience.rs
@@ -753,7 +753,7 @@ fn count_settings(value: &serde_json::Value) -> usize {
/// Settings in a default `Config`, measured by `count_settings`. Quoted in
/// `xerj-common/src/config.rs`; keep the two in step.
-const EXPECTED_SETTINGS: usize = 130;
+const EXPECTED_SETTINGS: usize = 132;
#[tokio::test]
async fn journey_zero_config() {
diff --git a/engine/xerj.default.toml b/engine/xerj.default.toml
index 17edcda56..efd0b121e 100644
--- a/engine/xerj.default.toml
+++ b/engine/xerj.default.toml
@@ -1,6 +1,6 @@
# xerj Default Configuration
# ============================================================
-# This file sets 55 of XERJ's 130 user-facing settings to their
+# This file sets 55 of XERJ's 132 user-facing settings to their
# production-ready defaults, and describes the rest in comments.
# Every value here IS the default, so copying this file changes
# nothing until you edit it (a test enforces that). The complete
@@ -681,3 +681,23 @@ access_log = false
# min_confidence = 0.0 # /_decide abstains below this
# human_weight = 2.0 # vote-weight multiplier for history docs carrying human: true
# calibration = "none" # none | isotonic | temperature — p_cal beside every p_raw (#1063)
+
+# ─────────────────────────────────────────────────────────────────────────
+# Corpus Hub — hosted read-only endpoints.
+#
+# Four GET routes under /_hub/v1/ answer from the pre-indexed corpus packs
+# restored on this node: /catalogue, /def/{slug}/{symbol}, /code/{slug} and
+# /search. They are served on the ES-compatible port (es_compat_port), are
+# read-only, only ever query xc-* indices, and are rate limited to 60
+# requests a minute per client address (429 + Retry-After).
+# By default every route needs an API key like the rest of the node.
+# `public = true` lets exactly those four routes answer without one; every
+# other route keeps authentication, authorization and the audit log.
+# `catalogue_path` is the signed catalogue.json the node serves and checks
+# every corpus name against; it is required when `public = true`, or the
+# node refuses to start. Behind a reverse proxy, also list the proxy in
+# [server] trusted_proxies, or every client shares the proxy's one budget.
+#
+# [hub]
+# public = false
+# catalogue_path = "" # not a default ("/srv/hub/catalogue.json") — required when public = true