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.

fix(search): validate slice before running a search; a slice.max of 2^32 aborted the node (#2652)

Amartya Vikram Singhb1a583a65f01
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 74e7e7d3d..270da3dca 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -7486,6 +7486,47 @@ where
deserializer.deserialize_any(FromVisitor)
}
+/// ES's `SliceBuilder` rules for a `slice` object: `id` and `max` are Java
+/// ints, `id >= 0`, `max > 1` and `id < max`, checked in that order with its
+/// messages. A string spelling of the integer is accepted, as ES's parser does.
+fn slice_spec_error(slice: &Value) -> Option<String> {
+ fn int_field(slice: &Value, key: &str) -> Result<Option<i32>, String> {
+ let Some(v) = slice.get(key) else {
+ return Ok(None);
+ };
+ let n = match v {
+ Value::Number(n) => n.as_i64(),
+ Value::String(s) => s.trim().parse::<i64>().ok(),
+ _ => None,
+ };
+ match n.map(i32::try_from) {
+ Some(Ok(n)) => Ok(Some(n)),
+ Some(Err(_)) => Err(format!(
+ "[slice] failed to parse field [{key}]: Numeric value ({v}) out of range of int"
+ )),
+ None => Err(format!("[slice] failed to parse field [{key}]")),
+ }
+ }
+ let id = match int_field(slice, "id") {
+ Ok(id) => id.unwrap_or(-1),
+ Err(e) => return Some(e),
+ };
+ let max = match int_field(slice, "max") {
+ Ok(max) => max.unwrap_or(-1),
+ Err(e) => return Some(e),
+ };
+ if id < 0 {
+ return Some("id must be greater than or equal to 0".to_string());
+ }
+ if max <= 1 {
+ return Some("max must be greater than 1".to_string());
+ }
+ if id >= max {
+ return Some("max must be greater than id".to_string());
+ }
+ None
+}
+
fn negative_from_reason(n: i64) -> String {
format!("[from] parameter cannot be negative but was [{n}]")
}
@@ -13672,6 +13713,12 @@ async fn search_impl(
},
}
}
+ // `slice` is validated before anything runs: its `max` and `id` feed
+ // unchecked `u32` arithmetic in the post-search slice filter, where a
+ // `max` of 2^32 truncated to 0 and the `% max` aborted the process.
+ if let Some(reason) = body.slice.as_ref().and_then(slice_spec_error) {
+ return ApiError::new(xerj_common::XerjError::invalid_query(reason)).into_response();
+ }
// URL-level `seq_no_primary_term=true` / `version=true` promote the
// corresponding body flag when the caller didn't already set one.
if body.seq_no_primary_term.is_none() {
@@ -16234,8 +16281,12 @@ async fn search_impl(
n.as_i64()
.or_else(|| n.as_str().and_then(|s| s.parse::<i64>().ok()))
})
- .map(|n| n as u32)
+ .and_then(|n| u32::try_from(n).ok())
})
+ // `number_of_shards` is not range-checked at index
+ // creation; a stored 0 would make the shard routing and
+ // `max / shards` below divide by zero.
+ .filter(|n| *n >= 1)
.unwrap_or(1);
let slice_by_id = slice_field == "_id";
let mut kept: Vec<(String, xerj_query::executor::Hit)> =
@@ -26584,7 +26635,8 @@ fn index_int_setting(state: &AppState, ix: &str, key: &str) -> Option<u64> {
/// result window);
/// * more `docvalue_fields` than `index.max_docvalue_fields_search` (100);
/// * a `regexp`, `prefix` or `/regex/` `query_string` longer than
-/// `index.max_regex_length` (1000 characters).
+/// `index.max_regex_length` (1000 characters);
+/// * for a scroll, a `slice.max` over `index.max_slices_per_scroll` (1024).
fn find_index_request_limit_violation(
state: &AppState,
ix: &str,
@@ -26612,6 +26664,24 @@ fn find_index_request_limit_violation(
});
}
+ if is_scroll {
+ let max_slices = index_int_setting(state, ix, "max_slices_per_scroll").unwrap_or(1024);
+ if let Some(slices) = body
+ .slice
+ .as_ref()
+ .and_then(|s| s.get("max"))
+ .and_then(|m| m.as_u64().or_else(|| m.as_str()?.trim().parse().ok()))
+ {
+ if slices > max_slices {
+ return Some(format!(
+ "The number of slices [{slices}] is too large. It must be less than \
+ [{max_slices}]. This limit can be set by changing the \
+ [index.max_slices_per_scroll] index level setting."
+ ));
+ }
+ }
+ }
+
let max_rescore = index_int_setting(state, ix, "max_rescore_window")
.map(|v| v as usize)
.unwrap_or(max_window);
diff --git a/engine/crates/xerj-api/tests/slice_spec_is_validated.rs b/engine/crates/xerj-api/tests/slice_spec_is_validated.rs
new file mode 100644
index 000000000..d5eeb53ad
--- /dev/null
+++ b/engine/crates/xerj-api/tests/slice_spec_is_validated.rs
@@ -0,0 +1,192 @@
+//! `slice` is validated before a search runs.
+//!
+//! The post-search slice filter did its shard arithmetic in `u32` on the raw
+//! request values: `{"slice":{"id":0,"max":4294967296}}` truncated `max` to 0
+//! and the `shard % max` aborted the whole node (release builds use
+//! `panic = "abort"`), for any caller with read access to one non-empty index.
+//! A stored `number_of_shards: 0` reached the same division through the shard
+//! count. Elasticsearch refuses these with a 400: `id` and `max` are ints,
+//! `id >= 0`, `max > 1`, `id < max`, and a scroll may not use more slices than
+//! `index.max_slices_per_scroll` (default 1024).
+//!
+//! Elasticsearch is referenced for semantics only. It is AGPL-3.0/SSPL-1.0/
+//! Elastic-2.0 licensed and no code from it is reproduced here.
+
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use serde_json::{json, Value};
+use tower::ServiceExt;
+
+async fn app() -> (axum::Router, tempfile::TempDir) {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let mut config = xerj_common::config::Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ config.storage.wal_sync = xerj_common::config::WalSync::Async;
+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");
+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");
+ let state = xerj_api::state::AppState::new(config, engine, metrics);
+ (xerj_api::router::build_es_compat_router(state), dir)
+}
+
+async fn json_req(
+ app: &axum::Router,
+ method: &str,
+ path: &str,
+ body: Value,
+) -> (StatusCode, Value) {
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method(method)
+ .uri(path)
+ .header("content-type", "application/json")
+ .body(Body::from(body.to_string()))
+ .expect("request"),
+ )
+ .await
+ .expect("response");
+ let status = response.status();
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("body");
+ (
+ status,
+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),
+ )
+}
+
+async fn seed(app: &axum::Router, index: &str, settings: Value) {
+ let (status, resp) = json_req(app, "PUT", &format!("/{index}"), settings).await;
+ assert_eq!(status, StatusCode::OK, "{resp}");
+ for i in 0..8 {
+ let (status, resp) = json_req(
+ app,
+ "PUT",
+ &format!("/{index}/_doc/{i}?refresh=true"),
+ json!({"n": i}),
+ )
+ .await;
+ assert!(status.is_success(), "{resp}");
+ }
+}
+
+fn reason(resp: &Value) -> String {
+ resp["error"]["reason"]
+ .as_str()
+ .unwrap_or_default()
+ .to_string()
+}
+
+/// FAIL-BEFORE: the first body panicked on `% 0` inside the handler; the
+/// others returned 200 with an arbitrary (often empty) slice.
+#[tokio::test]
+async fn out_of_range_slice_specs_are_400_not_a_crash() {
+ let (app, _dir) = app().await;
+ seed(&app, "s", json!({})).await;
+
+ for (slice, want) in [
+ (
+ json!({"id": 0, "max": 4294967296u64}),
+ "out of range of int",
+ ),
+ (json!({"id": 0, "max": 1}), "max must be greater than 1"),
+ (
+ json!({"id": -1, "max": 2}),
+ "id must be greater than or equal to 0",
+ ),
+ (json!({"id": 2, "max": 2}), "max must be greater than id"),
+ (
+ json!({"id": "x", "max": 2}),
+ "[slice] failed to parse field [id]",
+ ),
+ ] {
+ let (status, resp) = json_req(&app, "POST", "/s/_search", json!({"slice": slice})).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{slice}: {resp}");
+ assert!(reason(&resp).contains(want), "{slice}: {resp}");
+ }
+}
+
+/// Valid slices still partition the result set: two slices of `max: 2`
+/// are disjoint and together return every document.
+#[tokio::test]
+async fn valid_slices_partition_the_hits() {
+ let (app, _dir) = app().await;
+ seed(&app, "s", json!({})).await;
+
+ let mut seen = Vec::new();
+ for id in [json!(0), json!("1")] {
+ let (status, resp) = json_req(
+ &app,
+ "POST",
+ "/s/_search",
+ json!({"size": 100, "slice": {"id": id, "max": 2}}),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{resp}");
+ for h in resp["hits"]["hits"].as_array().unwrap() {
+ seen.push(h["_id"].as_str().unwrap().to_string());
+ }
+ }
+ seen.sort();
+ let all: Vec<String> = (0..8).map(|i| i.to_string()).collect();
+ assert_eq!(seen, all);
+}
+
+/// FAIL-BEFORE: a stored shard count of 0 reached `rem_euclid(0)` in the
+/// shard routing hash and aborted the node.
+#[tokio::test]
+async fn zero_shard_setting_does_not_divide_by_zero() {
+ let (app, _dir) = app().await;
+ let (status, _) = json_req(
+ &app,
+ "PUT",
+ "/z",
+ json!({"settings": {"number_of_shards": 0}}),
+ )
+ .await;
+ if !status.is_success() {
+ // Refused at creation is also correct; nothing to slice then.
+ return;
+ }
+ let (status, resp) = json_req(&app, "PUT", "/z/_doc/1?refresh=true", json!({"n": 1})).await;
+ assert!(status.is_success(), "{resp}");
+ let (status, resp) = json_req(
+ &app,
+ "POST",
+ "/z/_search",
+ json!({"slice": {"id": 0, "max": 2}}),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{resp}");
+}
+
+/// `scroll/12_slices.yml · Sliced scroll with invalid arguments`.
+#[tokio::test]
+async fn scroll_slices_respect_max_slices_per_scroll() {
+ let (app, _dir) = app().await;
+ seed(&app, "s", json!({})).await;
+ let body = json!({"size": 1, "slice": {"id": "0", "max": 1025}});
+
+ let (status, resp) = json_req(&app, "POST", "/s/_search?scroll=1m", body.clone()).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{resp}");
+ assert!(
+ reason(&resp).contains("The number of slices [1025] is too large"),
+ "{resp}"
+ );
+
+ // Without a scroll the cap does not apply.
+ let (status, resp) = json_req(&app, "POST", "/s/_search", body.clone()).await;
+ assert_eq!(status, StatusCode::OK, "{resp}");
+
+ let (status, resp) = json_req(
+ &app,
+ "PUT",
+ "/s/_settings",
+ json!({"index.max_slices_per_scroll": 1025}),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{resp}");
+ let (status, resp) = json_req(&app, "POST", "/s/_search?scroll=1m", body).await;
+ assert_eq!(status, StatusCode::OK, "{resp}");
+}
diff --git a/engine/tests/es-compat-yaml/catch-lenient.txt b/engine/tests/es-compat-yaml/catch-lenient.txt
index 1a468d447..42f53a275 100644
--- a/engine/tests/es-compat-yaml/catch-lenient.txt
+++ b/engine/tests/es-compat-yaml/catch-lenient.txt
@@ -56,7 +56,6 @@ scroll/10_basic.yml · Scroll with size 0
scroll/11_clear.yml · Body params with array param override query string
scroll/11_clear.yml · Body params with string param scroll id override query string
scroll/11_clear.yml · Clear scroll
-scroll/12_slices.yml · Sliced scroll with invalid arguments
scroll/20_keep_alive.yml · Max keep alive
search/110_field_collapsing.yml · field collapsing and scroll
search/110_field_collapsing.yml · field collapsing and search_after with invalid sort