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): refuse a malformed _bulk action line for the whole request (#2938)
Jake Elbirtc57984314193
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fb95d3a4c..7f32f4d86 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -156,6 +156,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`sudo ifconfig lo0 alias 127.0.0.2 up` instead of a bare connection error,through the new `xerj_common::loopback_test::require_loopback_alias`.CONTRIBUTING documents both, and that CI runs `--profile ci-test`.+- `_bulk` refuses a malformed action line the way Elasticsearch 8 does: the+ whole request is a 400 `illegal_argument_exception` naming the line+ (`Malformed action/metadata line [3], expected FIELD_NAME but found+ [END_OBJECT]`, `Action/metadata line [1] contains an unknown parameter+ [_type]`), and nothing in the body is written. XERJ answered 200 with a+ per-item error for that line and wrote every other action. An unknown+ parameter (`_type`, `_version`, `_routing`, a typo) used to be ignored and+ is now refused, as in ES 8; a client sending the 7.x REST compatibility+ header (`compatible-with=7`) may still send `_type`, as ES 8 allows. A line+ the check cannot read with confidence (JSON ES's own parser rejects, an+ escaped key, a byte order mark) stops the check there, and the rest of the+ body is answered as before.- Data-stream `_rollover` honours `dry_run` and its `conditions` instead ofignoring the body: `max_docs`/`max_age` are ORed and reported in`conditions`, and a dry run or an unmet condition creates no backing index.diff --git a/engine/crates/xerj-api/src/bulk_action_lines.rs b/engine/crates/xerj-api/src/bulk_action_lines.rsnew file mode 100644index 000000000..d978c5753--- /dev/null+++ b/engine/crates/xerj-api/src/bulk_action_lines.rs@@ -0,0 +1,554 @@+//! Elasticsearch's whole-request check of `_bulk` action lines.+//!+//! ES parses every action line of a bulk body before it executes any action+//! (`BulkRequestParser#parse`, 8.13). A line it cannot read as an action+//! refuses the whole request with a 400 `illegal_argument_exception` that+//! names the line, so nothing in the body is written. The bulk engine reads+//! action lines on its parallel parse and reports a bad one as a per-item+//! error after the rest have run; this check runs first, on the HTTP path,+//! and gives ES's answer instead.+//!+//! It is a byte scanner, not a JSON parse: action lines are short, and the+//! bulk hot path deliberately avoids building a `Value` per action (M5.12 in+//! `xerj_engine::bulk`). It reads names and token shapes the way ES's+//! streaming parser meets them, and refuses only what it reads with+//! confidence. Anything else (JSON it cannot follow, an escaped key, a byte+//! order mark) stops the check at that line and leaves the rest of the body+//! to the engine, which answers exactly as before. Stopping, rather than+//! skipping the line, matters: once a line is unread, which line is an action+//! and which is a source is no longer certain, and reading a source line as+//! an action would refuse a body ES accepts.+//!+//! It does not convert values. ES does (`version` to a number, `_source` to a+//! fetch context), so for a line that also has a value ES cannot convert, ES+//! can name that value where this check names a later problem. Both answers+//! are a 400 for the whole request.++/// Fields ES reads as a simple value inside an action. `_type` is absent on+/// purpose: on the 8.x REST API it is an unknown parameter (see+/// `first_malformed_action_line` for the 7.x compatibility case).+const SIMPLE_FIELDS: &[&[u8]] = &[+ b"_index",+ b"_id",+ b"routing",+ b"op_type",+ b"version",+ b"version_type",+ b"if_seq_no",+ b"if_primary_term",+ b"retry_on_conflict",+ b"pipeline",+ b"_source",+ b"require_alias",+ b"require_data_stream",+ b"list_executed_pipelines",+];++/// Fields ES accepts as an object inside an action.+const OBJECT_FIELDS: &[&[u8]] = &[b"dynamic_templates", b"_source"];++/// The reason ES gives for the first malformed action line in `body`, or+/// `None` when every action line is one ES would accept, or the check+/// stopped at a line it leaves to the engine. Lines are numbered from 1 and+/// blank lines count, as in ES. Pairing follows the bulk engine: every action+/// but a delete is followed by one source line.+///+/// `compat_v7` is a request sent with ES's REST compatibility header+/// (`compatible-with=7`); ES 8 then accepts `_type` with a deprecation+/// warning instead of refusing it.+pub(crate) fn first_malformed_action_line(body: &str, compat_v7: bool) -> Option<String> {+ let mut expect_source = false;+ for (n, line) in body.split('\n').enumerate() {+ if line.trim().is_empty() {+ if expect_source {+ // ES takes the very next line as the source even when it is+ // blank; the engine skips blank lines. The two pair every+ // line after this one differently, so stop here.+ return None;+ }+ continue;+ }+ if expect_source {+ expect_source = false;+ continue;+ }+ match check(line.as_bytes(), n + 1, compat_v7) {+ Line::Refused(reason) => return Some(reason),+ Line::Deferred => return None,+ Line::Accepted => {}+ }+ expect_source = !crate::cluster_shard::bulk_action_line_is_delete(line);+ }+ None+}++enum Line {+ Accepted,+ Refused(String),+ /// Not something this scanner reads with confidence; the engine decides.+ Deferred,+}++/// A JSON number, the whole of `t`.+fn is_json_number(t: &[u8]) -> bool {+ let digits = |i: &mut usize| {+ let start = *i;+ while matches!(t.get(*i), Some(b'0'..=b'9')) {+ *i += 1;+ }+ *i > start+ };+ let mut i = 0;+ if t.first() == Some(&b'-') {+ i += 1;+ }+ match t.get(i) {+ Some(b'0') => i += 1,+ Some(b'1'..=b'9') => {+ digits(&mut i);+ }+ _ => return false,+ }+ if t.get(i) == Some(&b'.') {+ i += 1;+ if !digits(&mut i) {+ return false;+ }+ }+ if matches!(t.get(i), Some(b'e' | b'E')) {+ i += 1;+ if matches!(t.get(i), Some(b'+' | b'-')) {+ i += 1;+ }+ if !digits(&mut i) {+ return false;+ }+ }+ i == t.len()+}++struct Cursor<'a> {+ b: &'a [u8],+ p: usize,+}++impl<'a> Cursor<'a> {+ fn peek(&mut self) -> Option<u8> {+ while self.p < self.b.len() && matches!(self.b[self.p], b' ' | b'\t' | b'\r' | b'\n') {+ self.p += 1;+ }+ self.b.get(self.p).copied()+ }++ fn eat(&mut self, c: u8) -> bool {+ if self.peek() == Some(c) {+ self.p += 1;+ true+ } else {+ false+ }+ }++ /// A key with no escapes, consumed with its closing quote. `None` for an+ /// escaped or unterminated key.+ fn key(&mut self) -> Option<&'a [u8]> {+ if !self.eat(b'"') {+ return None;+ }+ let start = self.p;+ while self.p < self.b.len() {+ match self.b[self.p] {+ b'"' => {+ self.p += 1;+ return Some(&self.b[start..self.p - 1]);+ }+ b'\\' => return None,+ _ => self.p += 1,+ }+ }+ None+ }++ /// Consume a string, number or literal and name its token as ES's parser+ /// does. `None` when it is not a complete JSON scalar: the JSON parser in+ /// ES would fail on it before ES looks at the line, with another error.+ fn scalar(&mut self) -> Option<&'static str> {+ if self.peek()? == b'"' {+ self.p += 1;+ while self.p < self.b.len() {+ match self.b[self.p] {+ b'\\' => self.p += 2,+ b'"' => {+ self.p += 1;+ return Some("VALUE_STRING");+ }+ _ => self.p += 1,+ }+ }+ return None;+ }+ let start = self.p;+ while self.p < self.b.len()+ && !matches!(+ self.b[self.p],+ b',' | b'}' | b']' | b' ' | b'\t' | b'\r' | b'\n'+ )+ {+ self.p += 1;+ }+ match &self.b[start..self.p] {+ b"true" | b"false" => Some("VALUE_BOOLEAN"),+ b"null" => Some("VALUE_NULL"),+ t if is_json_number(t) => Some("VALUE_NUMBER"),+ _ => None,+ }+ }++ /// Skip a balanced object starting at `{`. `false` when it does not end.+ fn skip_object(&mut self) -> bool {+ let mut depth = 0usize;+ let mut in_str = false;+ while self.p < self.b.len() {+ let c = self.b[self.p];+ self.p += 1;+ if in_str {+ match c {+ b'\\' => self.p += 1,+ b'"' => in_str = false,+ _ => {}+ }+ continue;+ }+ match c {+ b'"' => in_str = true,+ b'{' | b'[' => depth += 1,+ b'}' | b']' => {+ depth -= 1;+ if depth == 0 {+ return true;+ }+ }+ _ => {}+ }+ }+ false+ }+}++fn check(line: &[u8], n: usize, compat_v7: bool) -> Line {+ let malformed =+ |what: &str| Line::Refused(format!("Malformed action/metadata line [{n}], {what}"));+ let mut c = Cursor { b: line, p: 0 };++ match c.peek() {+ Some(b'{') => c.p += 1,+ Some(b'[') => return malformed("expected START_OBJECT but found [START_ARRAY]"),+ Some(_) => {+ return match c.scalar() {+ Some(t) => malformed(&format!("expected START_OBJECT but found [{t}]")),+ None => Line::Deferred,+ }+ }+ None => return Line::Deferred,+ }++ match c.peek() {+ Some(b'"') => {}+ Some(b'}') => return malformed("expected FIELD_NAME but found [END_OBJECT]"),+ _ => return Line::Deferred,+ }+ let Some(action) = c.key() else {+ return Line::Deferred;+ };+ if !c.eat(b':') {+ return Line::Deferred;+ }+ // ES's JSON parser reads the start of a value together with its name, so+ // a value it cannot read fails before the name is looked at.+ let value = match c.peek() {+ Some(b'{') => {+ c.p += 1;+ None+ }+ Some(b'[') => Some("START_ARRAY"),+ Some(_) => match c.scalar() {+ Some(t) => Some(t),+ None => return Line::Deferred,+ },+ None => return Line::Deferred,+ };+ if !matches!(action, b"create" | b"delete" | b"index" | b"update") {+ return malformed(&format!(+ "expected field [create], [delete], [index] or [update] but found [{}]",+ String::from_utf8_lossy(action)+ ));+ }+ if let Some(t) = value {+ return malformed(&format!(+ "expected START_OBJECT or END_OBJECT but found [{t}]"+ ));+ }++ if c.eat(b'}') {+ return Line::Accepted;+ }+ loop {+ let Some(field) = c.key() else {+ return Line::Deferred;+ };+ if !c.eat(b':') {+ return Line::Deferred;+ }+ let name = || String::from_utf8_lossy(field);+ match c.peek() {+ Some(b'[') => {+ return malformed(&format!(+ "expected a simple value for field [{}] but found [START_ARRAY]",+ name()+ ))+ }+ Some(b'{') => {+ if !OBJECT_FIELDS.contains(&field) {+ return malformed(&format!(+ "expected a simple value for field [{}] but found [START_OBJECT]",+ name()+ ));+ }+ if !c.skip_object() {+ return Line::Deferred;+ }+ }+ Some(_) => match c.scalar() {+ None => return Line::Deferred,+ // ES skips a null for any field without looking at its name.+ Some("VALUE_NULL") => {}+ Some(_) => {+ let known = SIMPLE_FIELDS.contains(&field) || (compat_v7 && field == b"_type");+ if !known {+ return Line::Refused(format!(+ "Action/metadata line [{n}] contains an unknown parameter [{}]",+ name()+ ));+ }+ }+ },+ None => return Line::Deferred,+ }+ if c.eat(b',') {+ continue;+ }+ // ES stops reading at the action's closing brace; what follows it is+ // only a deprecation warning there, so it is not checked here.+ return if c.eat(b'}') {+ Line::Accepted+ } else {+ Line::Deferred+ };+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn reason(body: &str) -> Option<String> {+ first_malformed_action_line(body, false)+ }++ #[test]+ fn canonical_bodies_pass() {+ assert_eq!(reason(""), None);+ assert_eq!(reason("\n\n"), None);+ assert_eq!(+ reason("{\"index\":{}}\n{\"a\":1}\n{\"delete\":{\"_id\":\"1\"}}\n{\"create\":{\"_id\":1}}\n{}\n"),+ None,+ "a source line is never read as an action, even when it is `{{}}`"+ );+ assert_eq!(+ reason("{\"index\":{\"_id\":\"a\\\"b\",\"_source\":{\"x\":[1,{\"y\":\"}\"}]}}}\n{}\n"),+ None+ );+ assert_eq!(+ reason("\r\n{ \"index\" : { \"_id\" : \"1\" } }\r\n{\"a\":1}\r\n"),+ None+ );+ }++ #[test]+ fn the_first_problem_is_the_one_reported() {+ assert_eq!(+ reason("{\"index\":{\"_type\":\"x\",\"_id\":[1]}}\n{}\n").as_deref(),+ Some("Action/metadata line [1] contains an unknown parameter [_type]")+ );+ assert_eq!(+ reason("{\"index\":{\"_id\":[1],\"_type\":\"x\"}}\n{}\n").as_deref(),+ Some(+ "Malformed action/metadata line [1], expected a simple value for field [_id] but found [START_ARRAY]"+ )+ );+ }++ #[test]+ fn a_value_es_ignores_is_ignored() {+ assert_eq!(reason("{\"index\":{\"anything\":null}}\n{}\n"), None);+ assert_eq!(+ reason("{\"index\":{\"_index\":\"t\"}} trailing\n{}\n"),+ None+ );+ }++ #[test]+ fn what_it_cannot_read_is_left_to_the_engine() {+ for line in [+ "{\"index\":",+ "{\"ind",+ "{\"\\u0069ndex\":{}}",+ "{\"index\":{\"_\\u0069d\":\"1\"}}",+ "{\"index\":{\"_id\":\"1\"",+ "{index:{}}",+ "garbage",+ ] {+ assert_eq!(reason(&format!("{line}\n{{}}\n")), None, "{line}");+ }+ }++ #[test]+ fn a_delete_takes_no_source_line() {+ assert_eq!(+ reason("{\"delete\":{\"_id\":\"1\"}}\n{\"bogus\":{}}\n").as_deref(),+ Some(+ "Malformed action/metadata line [2], expected field [create], [delete], [index] or [update] but found [bogus]"+ )+ );+ }++ #[test]+ fn every_name_es_accepts_is_accepted() {+ // Written out by hand from ES 8.13's `BulkRequestParser` fields, not+ // read from `SIMPLE_FIELDS`, so a typo there fails here.+ for (field, value) in [+ ("_index", "\"t\""),+ ("_id", "\"1\""),+ ("_id", "1"),+ ("routing", "\"r\""),+ ("op_type", "\"create\""),+ ("version", "3"),+ ("version_type", "\"external\""),+ ("if_seq_no", "0"),+ ("if_primary_term", "1"),+ ("retry_on_conflict", "3"),+ ("pipeline", "\"p\""),+ ("_source", "true"),+ ("_source", "\"a\""),+ ("_source", "{\"includes\":[\"a\"]}"),+ ("require_alias", "false"),+ ("require_data_stream", "true"),+ ("list_executed_pipelines", "false"),+ ("dynamic_templates", "{\"a\":\"b\"}"),+ ("version", "-1.5e+3"),+ ] {+ let body = format!("{{\"update\":{{\"{field}\":{value}}}}}\n{{}}\n");+ assert_eq!(reason(&body), None, "{field}: {value}");+ }+ }++ #[test]+ fn a_complete_scalar_is_named_by_its_token() {+ for (line, t) in [+ ("\"abc\"", "expected START_OBJECT but found [VALUE_STRING]"),+ ("true", "expected START_OBJECT but found [VALUE_BOOLEAN]"),+ ("12", "expected START_OBJECT but found [VALUE_NUMBER]"),+ (+ "{\"index\":null}",+ "expected START_OBJECT or END_OBJECT but found [VALUE_NULL]",+ ),+ (+ "{\"index\":false}",+ "expected START_OBJECT or END_OBJECT but found [VALUE_BOOLEAN]",+ ),+ (+ "{\"index\":-0.5}",+ "expected START_OBJECT or END_OBJECT but found [VALUE_NUMBER]",+ ),+ ] {+ assert_eq!(+ reason(&format!("{line}\n{{}}\n")),+ Some(format!("Malformed action/metadata line [1], {t}")),+ "{line}"+ );+ }+ }++ #[test]+ fn json_es_could_not_read_is_never_given_an_es_reason() {+ // Each of these fails in ES's JSON parser before ES reads the line,+ // with a parse error this check does not imitate.+ for line in [+ "nope",+ "tru",+ "1x",+ "01",+ "-",+ "}",+ "]",+ "{\"index\":}",+ "{\"index\":]",+ "{\"index\":nul}",+ "{\"bogus\"}",+ "{\"bogus\":x}",+ "{\"index\":{\"_type\":tru}}",+ "{\"index\":{\"_type\":1.}}",+ "{\"index\":{\"_id\":\"1\",}}",+ "{\"index\":{\"_id\":\"1\" \"x\":1}}",+ ] {+ assert_eq!(reason(&format!("{line}\n{{}}\n")), None, "{line}");+ }+ }++ #[test]+ fn the_check_stops_where_pairing_is_in_doubt() {+ // An escaped `delete` key: ES reads a delete (no source line), this+ // scanner cannot. Reading on would check `{"a":1}` as an action.+ assert_eq!(+ reason("{\"\\u0064elete\":{\"_index\":\"t\",\"_id\":\"1\"}}\n{\"index\":{\"_index\":\"t\"}}\n{\"a\":1}\n"),+ None+ );+ // A byte order mark before a delete, which ES's parser skips.+ assert_eq!(+ reason("\u{feff}{\"delete\":{\"_index\":\"t\",\"_id\":\"1\"}}\n{\"index\":{}}\n{\"a\":1}\n"),+ None+ );+ // A blank line where a source belongs: ES takes it as the source,+ // the engine skips it.+ assert_eq!(+ reason("{\"index\":{}}\n\n{\"a\":1}\n{\"index\":{}}\n{\"b\":1}\n"),+ None+ );+ // Before any doubt, a bad line is still found.+ assert_eq!(+ reason("{\"index\":{}}\n{\"a\":1}\n{}\n{\"\\u0064elete\":{}}\n").as_deref(),+ Some("Malformed action/metadata line [3], expected FIELD_NAME but found [END_OBJECT]")+ );+ }++ #[test]+ fn rest_compatibility_with_7_accepts_type() {+ let body = "{\"index\":{\"_index\":\"t\",\"_type\":\"_doc\",\"_id\":\"1\"}}\n{}\n";+ assert_eq!(+ reason(body).as_deref(),+ Some("Action/metadata line [1] contains an unknown parameter [_type]")+ );+ assert_eq!(first_malformed_action_line(body, true), None);+ // Only `_type` comes back, and only as a simple value.+ assert_eq!(+ first_malformed_action_line("{\"index\":{\"_version\":1}}\n{}\n", true).as_deref(),+ Some("Action/metadata line [1] contains an unknown parameter [_version]")+ );+ assert_eq!(+ first_malformed_action_line("{\"index\":{\"_type\":{}}}\n{}\n", true).as_deref(),+ Some(+ "Malformed action/metadata line [1], expected a simple value for field [_type] but found [START_OBJECT]"+ )+ );+ }+}diff --git a/engine/crates/xerj-api/src/cluster_shard.rs b/engine/crates/xerj-api/src/cluster_shard.rsindex 2739909f7..961e4dc58 100644--- a/engine/crates/xerj-api/src/cluster_shard.rs+++ b/engine/crates/xerj-api/src/cluster_shard.rs@@ -1849,7 +1849,7 @@ fn bulk_item_error(/// Same pairing rule as the bulk engine: a delete action has no source line./// The two parsers have to agree, or a delete swallows the next action.-fn bulk_action_line_is_delete(line: &str) -> bool {+pub(crate) fn bulk_action_line_is_delete(line: &str) -> bool {let b = line.as_bytes();let mut p = 0usize;while p < b.len() && (b[p] == b' ' || b[p] == b'\t') {diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 17923db33..a28628969 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -21417,11 +21417,13 @@ pub async fn bulk_ops(State(state): State<AppState>,Path(index): Path<String>,axum::extract::Query(qp): axum::extract::Query<std::collections::HashMap<String, String>>,+ headers: axum::http::HeaderMap,body: bytes::Bytes,) -> impl IntoResponse {let started = Instant::now();let opts = bulk_opts_from_query(&qp);- process_bulk_body(&state, Some(&index), &body, started, opts).await+ let compat_v7 = wants_rest_compat_v7(&headers);+ process_bulk_body(&state, Some(&index), &body, started, opts, compat_v7).await}// ─────────────────────────────────────────────────────────────────────────────@@ -21431,11 +21433,30 @@ pub async fn bulk_ops(pub async fn global_bulk(State(state): State<AppState>,axum::extract::Query(qp): axum::extract::Query<std::collections::HashMap<String, String>>,+ headers: axum::http::HeaderMap,body: bytes::Bytes,) -> impl IntoResponse {let started = Instant::now();let opts = bulk_opts_from_query(&qp);- process_bulk_body(&state, None, &body, started, opts).await+ let compat_v7 = wants_rest_compat_v7(&headers);+ process_bulk_body(&state, None, &body, started, opts, compat_v7).await+}++/// A request sent with ES's REST API compatibility header for 7.x+/// (`Accept` or `Content-Type` of+/// `application/vnd.elasticsearch+json; compatible-with=7`). ES 8 keeps a few+/// 7.x forms for such a client; `_bulk` uses it to accept `_type`.+fn wants_rest_compat_v7(headers: &axum::http::HeaderMap) -> bool {+ [axum::http::header::ACCEPT, axum::http::header::CONTENT_TYPE]+ .iter()+ .filter_map(|h| headers.get(h)?.to_str().ok())+ .any(|v| {+ v.split(';').any(|param| {+ param.trim().split_once('=').is_some_and(|(k, v)| {+ k.trim().eq_ignore_ascii_case("compatible-with") && v.trim() == "7"+ })+ })+ })}fn bulk_opts_from_query(@@ -21522,6 +21543,7 @@ async fn process_bulk_body(body: &bytes::Bytes,_started: Instant,opts: xerj_engine::bulk::BulkOpts,+ compat_v7: bool,) -> axum::response::Response {// The request body remains owned by this handler through parsing,// grouping, and publication. The opt-in guard is a single branch and@@ -21538,6 +21560,14 @@ async fn process_bulk_body(}};+ // ES reads every action line before it runs any action, so a malformed+ // one refuses the whole request and nothing is written. Checked on the+ // body as sent, before the rewrites below and before the local and+ // cluster paths split, so the line number is the client's.+ if let Some(reason) = crate::bulk_action_lines::first_malformed_action_line(text, compat_v7) {+ return es_bad_request("illegal_argument_exception", &reason, None);+ }+// ES bulk NDJSON alternates action-lines and source-lines. We rewrite// each source line through apply_ignore_malformed so the downstream// bulk pipeline sees a doc with _ignored already populated and anydiff --git a/engine/crates/xerj-api/src/lib.rs b/engine/crates/xerj-api/src/lib.rsindex 406b07eee..4801598c8 100644--- a/engine/crates/xerj-api/src/lib.rs+++ b/engine/crates/xerj-api/src/lib.rs@@ -68,6 +68,7 @@ pub mod audit_mw;pub mod auth;pub mod authz;pub mod binary_protocol;+mod bulk_action_lines;pub mod cat;pub mod cluster_shard;pub mod embed_warning;diff --git a/engine/crates/xerj-api/tests/bulk_action_line_refusal.rs b/engine/crates/xerj-api/tests/bulk_action_line_refusal.rsnew file mode 100644index 000000000..5d1e200cd--- /dev/null+++ b/engine/crates/xerj-api/tests/bulk_action_line_refusal.rs@@ -0,0 +1,232 @@+//! A malformed `_bulk` action line refuses the whole request, as in+//! Elasticsearch 8, and nothing in the body is written.+//!+//! ES parses every action line before it executes any of them+//! (`BulkRequestParser`), so a bad line is a 400 `illegal_argument_exception`+//! naming the line, and the actions before it never run. XERJ used to answer+//! 200 with a per-item error for the bad line and write everything else.++use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_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();+ 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 send(app: &axum::Router, method: &str, path: &str, body: &str) -> (StatusCode, Value) {+ send_as(app, method, path, "application/x-ndjson", body).await+}++async fn send_as(+ app: &axum::Router,+ method: &str,+ path: &str,+ content_type: &str,+ body: &str,+) -> (StatusCode, Value) {+ let req = Request::builder()+ .method(method)+ .uri(path)+ .header("content-type", content_type)+ .body(Body::from(body.to_owned()))+ .expect("request");+ let response = app.clone().oneshot(req).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 bulk(app: &axum::Router, body: &str) -> (StatusCode, Value) {+ send(app, "POST", "/_bulk?refresh=true", body).await+}++/// The request was refused as a whole with ES's reason.+fn assert_refused(status: StatusCode, got: &Value, reason: &str) {+ assert_eq!(status, StatusCode::BAD_REQUEST, "{got}");+ assert_eq!(got["status"], 400, "{got}");+ assert_eq!(got["error"]["type"], "illegal_argument_exception", "{got}");+ assert_eq!(got["error"]["reason"], reason, "{got}");+ assert_eq!(got["error"]["root_cause"][0]["reason"], reason, "{got}");+}++async fn doc_exists(app: &axum::Router, index: &str, id: &str) -> bool {+ let (status, _) = send(app, "GET", &format!("/{index}/_doc/{id}"), "").await;+ status == StatusCode::OK+}++#[tokio::test]+async fn an_empty_action_refuses_the_request_and_writes_nothing() {+ let (app, _dir) = app().await;+ let body = "{\"index\":{\"_index\":\"t\",\"_id\":\"1\"}}\n{\"f1\":\"v1\"}\n{}\n";+ let (status, got) = bulk(&app, body).await;+ assert_refused(+ status,+ &got,+ "Malformed action/metadata line [3], expected FIELD_NAME but found [END_OBJECT]",+ );+ assert!(!doc_exists(&app, "t", "1").await, "the first action ran");+}++#[tokio::test]+async fn an_unknown_parameter_refuses_the_request_and_writes_nothing() {+ let (app, _dir) = app().await;+ // ES 8 dropped mapping types: `_type` is an unknown parameter now.+ let body = "{\"index\":{\"_index\":\"t\",\"_id\":\"1\"}}\n{\"a\":1}\n\+ {\"update\":{\"_index\":\"t\",\"_type\":\"x\",\"_id\":\"1\"}}\n{\"doc\":{\"a\":2}}\n";+ let (status, got) = bulk(&app, body).await;+ assert_refused(+ status,+ &got,+ "Action/metadata line [3] contains an unknown parameter [_type]",+ );+ assert!(!doc_exists(&app, "t", "1").await, "the first action ran");++ // The ES 7 underscore spellings are unknown too.+ for key in ["_version", "_routing", "_retry_on_conflict"] {+ let body =+ format!("{{\"index\":{{\"_index\":\"t\",\"_id\":\"2\",\"{key}\":1}}}}\n{{\"a\":1}}\n");+ let (status, got) = bulk(&app, &body).await;+ assert_refused(+ status,+ &got,+ &format!("Action/metadata line [1] contains an unknown parameter [{key}]"),+ );+ }+ assert!(!doc_exists(&app, "t", "2").await);+}++#[tokio::test]+async fn an_unknown_action_is_named_with_its_line() {+ let (app, _dir) = app().await;+ // Blank lines count toward the line number, as in ES; a delete has no+ // source line, so the line after it is the next action.+ let body = "\n{\"delete\":{\"_index\":\"t\",\"_id\":\"9\"}}\n\n{\"upsert\":{\"_index\":\"t\"}}\n{\"a\":1}\n";+ let (status, got) = bulk(&app, body).await;+ assert_refused(+ status,+ &got,+ "Malformed action/metadata line [4], expected field [create], [delete], [index] or [update] but found [upsert]",+ );+}++#[tokio::test]+async fn each_malformed_shape_gets_es_reason() {+ let (app, _dir) = app().await;+ let cases = [+ ("[]", "Malformed action/metadata line [1], expected START_OBJECT but found [START_ARRAY]"),+ (+ "{\"index\":\"t\"}",+ "Malformed action/metadata line [1], expected START_OBJECT or END_OBJECT but found [VALUE_STRING]",+ ),+ (+ "{\"index\":[]}",+ "Malformed action/metadata line [1], expected START_OBJECT or END_OBJECT but found [START_ARRAY]",+ ),+ (+ "{\"index\":{\"_id\":[\"a\"]}}",+ "Malformed action/metadata line [1], expected a simple value for field [_id] but found [START_ARRAY]",+ ),+ (+ "{\"index\":{\"routing\":{\"a\":1}}}",+ "Malformed action/metadata line [1], expected a simple value for field [routing] but found [START_OBJECT]",+ ),+ (+ // `dynamic_templates` is only accepted as an object.+ "{\"index\":{\"dynamic_templates\":\"x\"}}",+ "Action/metadata line [1] contains an unknown parameter [dynamic_templates]",+ ),+ ];+ for (line, reason) in cases {+ let body = format!("{line}\n{{\"a\":1}}\n");+ let (status, got) = send(&app, "POST", "/t/_bulk", &body).await;+ assert_refused(status, &got, reason);+ }+}++#[tokio::test]+async fn every_parameter_es_accepts_still_runs() {+ let (app, _dir) = app().await;+ let body = concat!(+ "{\"index\":{\"_index\":\"t\",\"_id\":\"1\",\"routing\":\"r\",\"op_type\":\"index\",",+ "\"require_alias\":false,\"require_data_stream\":false,\"list_executed_pipelines\":false,",+ "\"version_type\":\"internal\",\"dynamic_templates\":{},\"ignored\":null}}\n",+ "{\"a\":1}\n",+ "{ \"create\" : { \"_index\" : \"t\", \"_id\" : 2 } }\n",+ "{\"a\":2}\n",+ "{\"update\":{\"_index\":\"t\",\"_id\":\"1\",\"routing\":\"r\",\"retry_on_conflict\":3,",+ "\"_source\":{\"includes\":[\"a\"]}}}\n",+ "{\"doc\":{\"b\":2}}\n",+ "{\"delete\":{\"_index\":\"t\",\"_id\":\"2\"}}\n",+ "{\"index\":{}}\n",+ "{\"a\":3}\n",+ );+ let (status, got) = send(&app, "POST", "/t/_bulk?refresh=true", body).await;+ assert_eq!(status, StatusCode::OK, "{got}");+ assert_eq!(got["errors"], false, "{got}");+ assert_eq!(got["items"].as_array().map(Vec::len), Some(5), "{got}");+ assert!(doc_exists(&app, "t", "1").await);+ assert!(!doc_exists(&app, "t", "2").await);+}++#[tokio::test]+async fn a_line_the_check_cannot_read_keeps_its_per_item_error() {+ let (app, _dir) = app().await;+ // Not JSON: ES fails it in its JSON parser with an error this check does+ // not imitate, so the engine answers it as before.+ let body = concat!(+ "{\"index\":{\"_index\":\"t\",\"_id\":\"1\"}}\n{\"a\":1}\n",+ "{\"index\":}\n{\"b\":1}\n",+ "{\"index\":{\"_index\":\"t\",\"_id\":\"3\"}}\n{\"c\":1}\n",+ );+ let (status, got) = bulk(&app, body).await;+ assert_eq!(status, StatusCode::OK, "{got}");+ assert_eq!(got["errors"], true, "{got}");+ assert_eq!(got["items"][1]["index"]["status"], 400, "{got}");+ assert!(doc_exists(&app, "t", "1").await);+ assert!(doc_exists(&app, "t", "3").await);+}++#[tokio::test]+async fn a_client_in_7x_compatibility_may_still_send_type() {+ let (app, _dir) = app().await;+ let body = "{\"index\":{\"_index\":\"t\",\"_type\":\"_doc\",\"_id\":\"1\"}}\n{\"a\":1}\n";+ let (status, got) = send_as(+ &app,+ "POST",+ "/_bulk?refresh=true",+ "application/vnd.elasticsearch+x-ndjson; compatible-with=7",+ body,+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{got}");+ assert_eq!(got["errors"], false, "{got}");+ assert!(doc_exists(&app, "t", "1").await);++ // The same body from an 8.x client is refused.+ let (status, got) = send_as(+ &app,+ "POST",+ "/_bulk",+ "application/vnd.elasticsearch+x-ndjson; compatible-with=8",+ &body.replace("\"1\"", "\"2\""),+ )+ .await;+ assert_refused(+ status,+ &got,+ "Action/metadata line [1] contains an unknown parameter [_type]",+ );+}diff --git a/engine/tests/es-compat-yaml/catch-lenient.txt b/engine/tests/es-compat-yaml/catch-lenient.txtindex 475ce4477..a2fd0cfdc 100644--- a/engine/tests/es-compat-yaml/catch-lenient.txt+++ b/engine/tests/es-compat-yaml/catch-lenient.txt@@ -44,8 +44,6 @@ aggregations/stats_metric_fail_formatting.yml · fail formattingaggregations/terms.yml · IP testaggregations/top_hits.yml · havingaggregations/weighted_avg.yml · Multi weight field not allowed-bulk/10_basic.yml · empty action-bulk/60_deprecated.yml · Deprecated parameters should fail in Bulk queryindices/indices.put_template/10_basic.yml · Put template createscroll/11_clear.yml · Body params with array param override query stringscroll/11_clear.yml · Body params with string param scroll id override query string