AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(api): apply the request-time script guard on _msearch, and bound the bucket_script evaluator ahead of #95 (#115)
xerj-org5594d89c6f65
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex f86bc91a8..5f30e668e 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -17837,6 +17837,20 @@ async fn msearch_impl(}};+ // Same request-time script guard `_search` applies in+ // `build_search_request`. Without it `_msearch` was a general bypass:+ // any script `_search` rejects up front with a 400 reached the+ // per-document paths unchecked here. Sub-searches are independent, so+ // the violation fails this item only (400, ES's per-item error shape)+ // and the rest of the batch still runs.+ if let Some(msg) = find_script_limit_violation(&search_body_val) {+ responses.push(json!({+ "error": { "type": "illegal_argument_exception", "reason": msg },+ "status": 400+ }));+ continue;+ }+// Determine index name: header wins, then the path index (for// /{index}/_msearch), then "*" (all indices).let index_name = header@@ -23927,6 +23941,13 @@ pub async fn search_template(.into_response();};+ // A rendered template is user input like any other search body — apply+ // the same request-time script guard `_search` applies in+ // `build_search_request`, which this path also skips.+ if let Some(msg) = find_script_limit_violation(&search_body_val) {+ return ApiError::new(xerj_common::XerjError::invalid_query(msg)).into_response();+ }+// Parse and execute as a normal search.let search_req = match xerj_query::parse_request(&search_body_val).map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))@@ -24109,6 +24130,17 @@ async fn msearch_template_impl(continue;};+ // Same request-time script guard as `_search`/`_msearch`; the+ // rendered template is user input and this path skips+ // `build_search_request` too.+ if let Some(msg) = find_script_limit_violation(&search_body_val) {+ responses.push(json!({+ "error": { "type": "illegal_argument_exception", "reason": msg },+ "status": 400+ }));+ continue;+ }+let search_req = match xerj_query::parse_request(&search_body_val).map_err(|e| xerj_common::XerjError::invalid_query(e.to_string())){@@ -32032,3 +32064,126 @@ mod request_validation_tests {assert!(uuid::Uuid::parse_str("not-a-real-scroll-id").is_err());}}++// ─────────────────────────────────────────────────────────────────────────────+// The request-time script guard must cover every search entry point, not just+// `_search`. `_msearch` used to build its sub-requests straight off+// `parse_request`, skipping `build_search_request` — so every script `_search`+// rejects with a 400 reached the per-document paths unchecked through the+// multi-search API.+// ─────────────────────────────────────────────────────────────────────────────+#[cfg(test)]+mod msearch_script_guard_tests {+ use super::*;+ use xerj_common::{config::Config, metrics::Metrics};+ use xerj_engine::Engine;++ fn test_state() -> AppState {+ let dir = tempfile::tempdir().expect("tempdir");+ // Leak the tempdir so the data directory outlives the Engine.+ let path = dir.keep();+ let mut config = Config::default();+ config.server.data_dir = path.to_str().unwrap().to_string();+ let metrics = Metrics::new().expect("metrics");+ let engine = Engine::new(config.clone()).expect("engine");+ AppState::new(config, engine, metrics)+ }++ async fn drain_json(resp: Response) -> Value {+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap_or_default();+ serde_json::from_slice::<Value>(&bytes).unwrap_or(Value::Null)+ }++ /// The reported repro: a `bucket_script` whose source is an ~80 KB+ /// right-associative ternary chain. Every `?` is one more level of+ /// expression recursion at evaluation time.+ fn nested_ternary_bucket_script() -> Value {+ let script = format!("{}1", "0?1:".repeat(20_000));+ assert_eq!(script.len(), 80_001, "fixture must be the ~80 KB repro");+ json!({+ "size": 0,+ "aggs": {+ "by_tag": {+ "terms": { "field": "tag" },+ "aggs": {+ "total": { "sum": { "field": "n" } },+ "ratio": {+ "bucket_script": {+ "buckets_path": { "t": "total" },+ "script": script+ }+ }+ }+ }+ }+ })+ }++ /// Three ~80 KB items = the reported ~240 KB `_msearch` body. Each one is+ /// rejected on its own; the trailing ordinary item still runs, because ES+ /// sub-searches are independent.+ #[tokio::test]+ async fn msearch_rejects_over_limit_scripts_per_item() {+ let state = test_state();+ let hostile = serde_json::to_string(&nested_ternary_bucket_script()).unwrap();+ let mut body = String::new();+ for _ in 0..3 {+ body.push_str("{}\n");+ body.push_str(&hostile);+ body.push('\n');+ }+ body.push_str("{}\n");+ body.push_str(&json!({ "query": { "match_all": {} } }).to_string());+ body.push('\n');+ assert!(body.len() > 240_000, "fixture must be the ~240 KB repro");++ let resp = msearch(State(state), bytes::Bytes::from(body))+ .await+ .into_response();+ let v = drain_json(resp).await;+ let items = v["responses"].as_array().expect("responses array");+ assert_eq!(items.len(), 4);+ for (i, item) in items.iter().take(3).enumerate() {+ assert_eq!(+ item["status"],+ json!(400),+ "item {i} must be rejected: {item}"+ );+ let reason = item["error"]["reason"].as_str().unwrap_or_default();+ assert!(+ reason.contains("nesting depth") || reason.contains("byte limit"),+ "item {i} must report the limit it broke, got {reason:?}"+ );+ }+ assert_eq!(+ items[3]["status"],+ json!(200),+ "an ordinary sub-search must still run: {}",+ items[3]+ );+ }++ /// The same guard `_search` applies: an ordinary sub-search body is+ /// untouched by it (no spurious 400s on scripts that are merely outside+ /// the supported subset).+ #[tokio::test]+ async fn msearch_leaves_ordinary_scripts_alone() {+ let state = test_state();+ let body = format!(+ "{{}}\n{}\n",+ json!({+ "query": { "match_all": {} },+ "script_fields": {+ "doubled": { "script": { "source": "doc['n'].value * 2" } }+ }+ })+ );+ let resp = msearch(State(state), bytes::Bytes::from(body))+ .await+ .into_response();+ let v = drain_json(resp).await;+ assert_eq!(v["responses"][0]["status"], json!(200), "{v}");+ }+}diff --git a/engine/crates/xerj-engine/src/aggs.rs b/engine/crates/xerj-engine/src/aggs.rsindex 634afa16c..f1f291637 100644--- a/engine/crates/xerj-engine/src/aggs.rs+++ b/engine/crates/xerj-engine/src/aggs.rs@@ -1025,13 +1025,81 @@ fn resolve_bucket_script(}}+/// Maximum nesting the `bucket_script` / `bucket_selector` expression+/// evaluator accepts, checked on ENTRY before a single token is produced.+///+/// Mirrors `sql::MAX_SQL_DEPTH` and `xerj-query`'s `MAX_QUERY_DEPTH` (both+/// 64). The token stream this evaluator produces is consumed *recursively* —+/// parenthesised sub-expressions, and above all the ternary `cond ? a : b`+/// split, which re-enters the evaluator once per `?` — so an expression from+/// an unauthenticated request is otherwise unbounded native-stack recursion.+/// The release profile sets `panic = "abort"`, which turns that overflow into+/// a process kill rather than an error response, so the bound has to be+/// enforced before the recursion starts, not inside it.+const MAX_EXPR_DEPTH: usize = 64;++/// Sentinel returned by [`check_expr_limits`] for an expression the evaluator+/// cannot safely walk.+const EXPR_TOO_DEEP_MSG: &str = "bucket script expression exceeds the maximum nesting depth";++/// Validate a `bucket_script` / `bucket_selector` expression against the+/// evaluator's resource limits WITHOUT evaluating it.+///+/// `Err` is returned only for genuine limit violations — oversized source, or+/// nesting beyond [`MAX_EXPR_DEPTH`]. Ordinary syntax errors stay the+/// evaluator's business and keep degrading to a null bucket value.+///+/// Both counts are taken over the raw source rather than the token stream,+/// because the recursion they bound happens *while consuming* the tokens: the+/// budget has to be known before tokenizing. Ternaries are counted rather than+/// depth-tracked, because a right-associative chain (`a?b:c?d:e?f:g`) re-enters+/// the evaluator once per `?` while never opening a paren — counting `?` is the+/// only count that bounds it.+fn check_expr_limits(script: &str) -> Result<(), String> {+ if script.len() > crate::painless::MAX_SCRIPT_LEN {+ return Err(format!(+ "bucket script expression is {} bytes, exceeds the {}-byte limit",+ script.len(),+ crate::painless::MAX_SCRIPT_LEN+ ));+ }+ let mut paren_depth: usize = 0;+ let mut ternaries: usize = 0;+ for b in script.bytes() {+ match b {+ b'(' => {+ paren_depth += 1;+ if paren_depth > MAX_EXPR_DEPTH {+ return Err(EXPR_TOO_DEEP_MSG.to_string());+ }+ }+ b')' => paren_depth = paren_depth.saturating_sub(1),+ b'?' => {+ ternaries += 1;+ if ternaries > MAX_EXPR_DEPTH {+ return Err(EXPR_TOO_DEEP_MSG.to_string());+ }+ }+ _ => {}+ }+ }+ Ok(())+}+/// Evaluate a simple arithmetic / comparison expression against a params map.////// Supports: numbers (incl. decimals), `params.<name>` identifiers,/// operators `+ - * / %`, comparisons `< > <= >= == !=` (yield 0.0 or 1.0),/// logical `&&` / `||` (yield 0.0 or 1.0), and parentheses. Honors/// standard precedence. Returns `None` on parse failure.+///+/// Bounded on entry by [`check_expr_limits`]: an expression past the limits+/// resolves to `None` — the same null bucket value every other unevaluable+/// script already produces — instead of overflowing the stack.fn eval_script_expr(script: &str, params: &HashMap<String, f64>) -> Option<f64> {+ if check_expr_limits(script).is_err() {+ return None;+ }let tokens = tokenize_script(script, params)?;let rpn = shunting_yard(&tokens)?;evaluate_rpn(&rpn)@@ -1288,6 +1356,116 @@ fn evaluate_rpn(rpn: &[Tok]) -> Option<f64> {}}+#[cfg(test)]+mod bucket_script_expr_limit_tests {+ //! The `bucket_script` / `bucket_selector` expression evaluator takes an+ //! arbitrary-length string straight off an unauthenticated request and+ //! hands it to consumers that walk the token stream recursively (nested+ //! parens; the ternary `cond ? a : b` split, which re-enters the evaluator+ //! once per `?`). With `panic = "abort"` in the release profile, running+ //! out of native stack there kills the process instead of returning an+ //! error, so the limits are enforced on entry — before tokenizing.+ //!+ //! If the entry bound regresses, these tests do not silently pass: the+ //! test process itself overflows and aborts.+ use super::*;++ fn no_params() -> HashMap<String, f64> {+ HashMap::new()+ }++ #[test]+ fn deeply_nested_parens_are_rejected_instead_of_evaluated() {+ let src = format!("{}1{}", "(".repeat(5000), ")".repeat(5000));+ assert!(+ check_expr_limits(&src).is_err(),+ "5000-deep parens must trip the entry bound"+ );+ assert_eq!(+ eval_script_expr(&src, &no_params()),+ None,+ "an over-deep expression must resolve to a null bucket value"+ );+ }++ #[test]+ fn chained_ternaries_are_bounded_by_their_count_not_their_paren_depth() {+ // The reported repro, verbatim: a right-associative ternary chain+ // whose conditions are all false, so every step descends into the+ // tail. It never opens a paren, yet a ternary-splitting evaluator+ // re-enters itself once per `?` — counting `?` is the only thing that+ // bounds it. Measured against that evaluator in an optimized build:+ // 80,001 bytes (20k ternaries) overflows a 2 MiB worker stack and+ // SIGABRTs the process; the entry bound below rejects it in ~5 µs.+ let src = format!("{}1", "0?1:".repeat(20_000));+ assert_eq!(src.len(), 80_001, "the fixture must be the ~80 KB repro");+ assert_eq!(+ src.matches('?').count(),+ 20_000,+ "the fixture must actually be a 20k-deep ternary chain"+ );+ assert!(+ check_expr_limits(&src).is_err(),+ "a 20k ternary chain must trip the entry bound"+ );+ assert_eq!(eval_script_expr(&src, &no_params()), None);+ }++ #[test]+ fn nested_ternaries_are_rejected_instead_of_evaluated() {+ // The other spelling of the same attack: each ternary nested inside+ // the previous one's false branch.+ let src = format!("0?1:{}1{}", "(0?1:".repeat(10_000), ")".repeat(10_000));+ assert!(check_expr_limits(&src).is_err());+ assert_eq!(eval_script_expr(&src, &no_params()), None);+ }++ #[test]+ fn oversized_expression_is_rejected_instead_of_evaluated() {+ // Valid arithmetic — the pre-bound evaluator happily tokenizes and+ // folds all of it — but far past the 64 KiB source limit.+ let src = format!("{}1", "1+".repeat(crate::painless::MAX_SCRIPT_LEN));+ assert!(src.len() > crate::painless::MAX_SCRIPT_LEN);+ assert!(check_expr_limits(&src).is_err());+ assert_eq!(eval_script_expr(&src, &no_params()), None);+ }++ #[test]+ fn ordinary_expressions_still_evaluate() {+ let mut params = HashMap::new();+ params.insert("numerator".to_string(), 8.0);+ params.insert("denominator".to_string(), 2.0);+ assert_eq!(+ eval_script_expr("params.numerator / params.denominator", ¶ms),+ Some(4.0)+ );+ // Nesting right up to the bound is still accepted — the limit only+ // rejects what no generated script produces.+ let deep_ok = format!(+ "{}params.numerator{}",+ "(".repeat(MAX_EXPR_DEPTH),+ ")".repeat(MAX_EXPR_DEPTH)+ );+ assert!(check_expr_limits(&deep_ok).is_ok());+ assert_eq!(eval_script_expr(&deep_ok, ¶ms), Some(8.0));+ }++ #[test]+ fn an_over_deep_bucket_script_resolves_to_null_not_a_crash() {+ // End to end through the pipeline resolver: the bucket keeps its+ // shape and reports a null value, exactly like any other script the+ // evaluator can't handle.+ let mut siblings = Map::new();+ siblings.insert("total".to_string(), json!({"value": 10.0}));+ let bp = json!({"t": "total"});+ let src = format!("{}params.t{}", "(".repeat(5000), ")".repeat(5000));+ assert_eq!(+ resolve_bucket_script(&bp, &src, &HashMap::new(), &siblings),+ json!({"value": Value::Null})+ );+ }+}+fn split_buckets_path(buckets_path: &str) -> (&str, Option<&str>) {if let Some(pos) = buckets_path.find('>') {(&buckets_path[..pos], Some(&buckets_path[pos + 1..]))