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(blocks): make index blocks removable, un-invert read_only_allow_delete, answer 403 not 500
xerj-org0a0623d78f34
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 36f2c6327..ce180546e 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -21169,6 +21169,56 @@ pub async fn cat_shards(State(state): State<AppState>) -> impl IntoResponse {// PUT /{index}/_settings — update index settings// ─────────────────────────────────────────────────────────────────────────────+/// Republish an index's authoritative `index.blocks` map into the display-side+/// `engine.index_settings` entry that `GET /{index}/_settings` serves.+///+/// Enforcement reads `Index::settings` (persisted at `<index>/settings.json`);+/// `GET /_settings` reads the separate `engine.index_settings` map. Without this+/// mirror the two disagree — a block set through `PUT /_block/{block}` was+/// enforced but invisible, which is how "I can't tell whether the block is+/// still on" turns into "I can't get rid of it".+async fn sync_display_blocks(state: &AppState, name: &str) {+ let Ok(idx) = state.engine.get_index(name) else {+ return;+ };+ let blocks = idx+ .get_settings()+ .await+ .pointer("/index/blocks")+ .cloned()+ .filter(|b| b.as_object().is_some_and(|m| !m.is_empty()));++ let mut display = state+ .engine+ .index_settings+ .get(name)+ .map(|v| v.clone())+ .unwrap_or_else(|| json!({ "index": {} }));+ if !display.is_object() {+ display = json!({ "index": {} });+ }+ let root = display.as_object_mut().unwrap();+ if !root.get("index").is_some_and(Value::is_object) {+ root.insert("index".to_string(), json!({}));+ }+ let inner = root.get_mut("index").unwrap().as_object_mut().unwrap();+ // Drop any dotted spellings a settings PUT may have left behind, so the+ // nested map below is the single rendering of the block state.+ inner.retain(|k, _| !k.starts_with("blocks."));+ match blocks {+ Some(b) => {+ inner.insert("blocks".to_string(), b);+ }+ None => {+ inner.remove("blocks");+ }+ }+ state+ .engine+ .index_settings+ .insert(name.to_string(), display);+}+pub async fn put_settings(State(state): State<AppState>,Path(index): Path<String>,@@ -21210,6 +21260,21 @@ pub async fn put_settings(state.engine.index_settings.insert(idx.clone(), existing);}+ // `index.blocks.*` is not a display-only setting: it gates writes and reads+ // in the engine, whose `Index::settings` is a different store from the+ // `engine.index_settings` map updated above. Forward the block keys so a+ // settings PUT can both set *and clear* a block — previously it updated only+ // the display copy, leaving every block permanent once set.+ for name in &targets {+ let Ok(idx) = state.engine.get_index(name) else {+ continue;+ };+ if let Err(e) = idx.apply_block_settings(&body).await {+ return ApiError::new(xerj_common::XerjError::from(e)).into_response();+ }+ sync_display_blocks(&state, name).await;+ }+Json(json!({ "acknowledged": true })).into_response()}@@ -27629,42 +27694,60 @@ pub async fn get_mapping_field(}// ─────────────────────────────────────────────────────────────────────────────-// PUT /{index}/_block/{block}+// PUT /{index}/_block/{block} — add a block+// DELETE /{index}/_block/{block} — remove it again// ─────────────────────────────────────────────────────────────────────────────-pub async fn put_index_block(- State(state): State<AppState>,- Path((index, block)): Path<(String, String)>,-) -> impl IntoResponse {+/// Shared body of the two `_block` verbs.+///+/// `enabled` selects add vs remove. Removal exists because the only other way+/// off a block — `PUT /_settings` — used to write the display copy alone, so an+/// index that took a block could never be un-blocked without a restart.+async fn set_index_block(+ state: AppState,+ index: String,+ block: String,+ enabled: bool,+) -> axum::response::Response {let idx = match state.engine.get_index(&index) {Ok(i) => i,Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),};- // Validate block name.- let valid_blocks = [- "read_only",- "read_only_allow_delete",- "write",- "metadata",- "read",- ];- if !valid_blocks.contains(&block.as_str()) {+ if !xerj_engine::Index::BLOCK_NAMES.contains(&block.as_str()) {let e = xerj_common::XerjError::invalid_query(format!(- "invalid index block: {block}; valid values are: read_only, read_only_allow_delete, write, metadata, read"+ "invalid index block: {block}; valid values are: {}",+ xerj_engine::Index::BLOCK_NAMES.join(", ")));return ApiError::new(e).into_response();}- match idx.set_block(&block).await {- Ok(()) => Json(json!({- "acknowledged": true,- "shards_acknowledged": true,- "indices": [{ "name": index, "blocked": true }]- }))- .into_response(),- Err(e) => ApiError::new(xerj_common::XerjError::from(e)).into_response(),+ if let Err(e) = idx.set_block_state(&block, enabled).await {+ return ApiError::new(xerj_common::XerjError::from(e)).into_response();}+ // Keep GET /_settings in step with what is actually enforced.+ sync_display_blocks(&state, &index).await;++ Json(json!({+ "acknowledged": true,+ "shards_acknowledged": true,+ "indices": [{ "name": index, "blocked": enabled }]+ }))+ .into_response()+}++pub async fn put_index_block(+ State(state): State<AppState>,+ Path((index, block)): Path<(String, String)>,+) -> impl IntoResponse {+ set_index_block(state, index, block, true).await+}++pub async fn delete_index_block(+ State(state): State<AppState>,+ Path((index, block)): Path<(String, String)>,+) -> impl IntoResponse {+ set_index_block(state, index, block, false).await}// ─────────────────────────────────────────────────────────────────────────────diff --git a/engine/crates/xerj-api/src/router.rs b/engine/crates/xerj-api/src/router.rsindex a80544618..c2fb51f1e 100644--- a/engine/crates/xerj-api/src/router.rs+++ b/engine/crates/xerj-api/src/router.rs@@ -290,7 +290,10 @@ pub fn build_es_compat_router(state: AppState) -> Router {get(es_compat::get_settings).put(es_compat::put_settings),)// ── Index blocks ───────────────────────────────────────────────────- .route("/:index/_block/:block", put(es_compat::put_index_block))+ .route(+ "/:index/_block/:block",+ put(es_compat::put_index_block).delete(es_compat::delete_index_block),+ )// ── Explain ────────────────────────────────────────────────────────.route("/:index/_explain/:id",diff --git a/engine/crates/xerj-api/tests/index_blocks_http.rs b/engine/crates/xerj-api/tests/index_blocks_http.rsnew file mode 100644index 000000000..17020ad84--- /dev/null+++ b/engine/crates/xerj-api/tests/index_blocks_http.rs@@ -0,0 +1,523 @@+//! Index blocks, from the outside — the three defects reported against the+//! `_block` / `index.blocks.*` surface, each pinned by a test that fails on the+//! pre-fix tree.+//!+//! 1. **A block could be set but never removed.** `PUT /{index}/_settings`+//! wrote only the display-side `engine.index_settings` map, which nothing+//! enforces; enforcement reads `Index::settings`. So the 200+//! `{"acknowledged": true}` was a lie and the index stayed blocked. There was+//! no `DELETE /{index}/_block/{block}` either — the route was PUT-only — so+//! the block outlived every API on offer.+//!+//! 2. **`read_only_allow_delete` was inverted.** It set `blocks.read`, which+//! denies *searches* and leaves *writes* running: precisely backwards.+//! Elasticsearch's own definition is a WRITE-level block that answers 429+//! (`IndexMetadata.INDEX_READ_ONLY_ALLOW_DELETE_BLOCK`), and its docs are+//! explicit that document deletes are denied too — the "allow delete" is+//! *index* deletion, which frees disk immediately, unlike deleting documents+//! which costs disk first+//! (`docs/reference/elasticsearch/index-settings/index-block.md:29-34`).+//! `read_only` had the same inversion: it forced `blocks.read` on as well,+//! when ES means "readable, not writable".+//!+//! 3. **A blocked bulk answered 500.** Three inline `match`es in `bulk.rs`+//! listed the errors their authors had in mind and sent everything else to+//! `_ => 500`, so a plain write block — a 403 in `XerjError::http_status()`+//! and a `cluster_block_exception` in ES — was reported to clients as a+//! server fault.+//!+//! 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;++/// A one-index app with a single document already visible.+async fn app_with_index(name: &str) -> (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);++ state+ .engine+ .create_index(name, xerj_common::types::Schema::empty())+ .expect("create_index");+ let idx = state.engine.get_index(name).expect("get_index");+ idx.index_document(Some("seed".into()), json!({ "value": 1 }))+ .await+ .expect("index_document");+ idx.refresh().await.expect("refresh");++ (xerj_api::router::build_es_compat_router(state), dir)+}++async fn send(app: &axum::Router, req: Request<Body>) -> (StatusCode, Value) {+ 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");+ let value: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);+ (status, value)+}++async fn put_json(app: &axum::Router, path: &str, body: Value) -> (StatusCode, Value) {+ send(+ app,+ Request::put(path)+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .expect("request"),+ )+ .await+}++async fn put_empty(app: &axum::Router, path: &str) -> (StatusCode, Value) {+ send(+ app,+ Request::put(path).body(Body::empty()).expect("request"),+ )+ .await+}++async fn delete(app: &axum::Router, path: &str) -> (StatusCode, Value) {+ send(+ app,+ Request::delete(path).body(Body::empty()).expect("request"),+ )+ .await+}++async fn get(app: &axum::Router, path: &str) -> (StatusCode, Value) {+ send(+ app,+ Request::get(path).body(Body::empty()).expect("request"),+ )+ .await+}++async fn bulk(app: &axum::Router, path: &str, ndjson: &str) -> (StatusCode, Value) {+ send(+ app,+ Request::post(path)+ .header("content-type", "application/x-ndjson")+ .body(Body::from(ndjson.to_owned()))+ .expect("request"),+ )+ .await+}++/// Index one document; returns the status the write got.+async fn write_doc(app: &axum::Router, index: &str, id: &str) -> StatusCode {+ put_json(app, &format!("/{index}/_doc/{id}"), json!({ "value": 2 }))+ .await+ .0+}++// ── 1. A block must be removable ─────────────────────────────────────────────++#[tokio::test]+async fn a_write_block_can_be_cleared_through_the_settings_api() {+ let (app, _dir) = app_with_index("clearsettings").await;++ let (status, _) = put_empty(&app, "/clearsettings/_block/write").await;+ assert_eq!(status, StatusCode::OK, "setting the block should succeed");+ assert_eq!(+ write_doc(&app, "clearsettings", "1").await,+ StatusCode::FORBIDDEN,+ "a write block must deny writes with 403"+ );++ let (status, body) = put_json(+ &app,+ "/clearsettings/_settings",+ json!({ "index": { "blocks": { "write": false } } }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "settings update: {body}");++ assert_eq!(+ write_doc(&app, "clearsettings", "1").await,+ StatusCode::CREATED,+ "PUT _settings answered 'acknowledged' but the block was still enforced — \+ the settings write never reached the engine state the write guard reads"+ );+}++#[tokio::test]+async fn a_write_block_can_be_cleared_through_the_dotted_settings_form() {+ let (app, _dir) = app_with_index("cleardotted").await;++ put_empty(&app, "/cleardotted/_block/write").await;+ assert_eq!(+ write_doc(&app, "cleardotted", "1").await,+ StatusCode::FORBIDDEN+ );++ // ES clients send index settings in dotted form at least as often as nested.+ let (status, body) = put_json(+ &app,+ "/cleardotted/_settings",+ json!({ "index.blocks.write": false }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "settings update: {body}");++ assert_eq!(+ write_doc(&app, "cleardotted", "1").await,+ StatusCode::CREATED,+ "the dotted spelling of index.blocks.write must clear the block too"+ );+}++#[tokio::test]+async fn a_write_block_can_be_set_through_the_settings_api() {+ let (app, _dir) = app_with_index("setsettings").await;++ // The inverse direction of the same defect: setting a block through+ // _settings also has to reach the engine, not just the display map.+ let (status, body) = put_json(+ &app,+ "/setsettings/_settings",+ json!({ "index": { "blocks": { "write": true } } }),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "settings update: {body}");++ assert_eq!(+ write_doc(&app, "setsettings", "1").await,+ StatusCode::FORBIDDEN,+ "index.blocks.write set through _settings must actually deny writes"+ );+}++/// A block declared in the **create** body has to be enforced too, in any+/// spelling. `PUT /{index}` forwards its `settings` blob to the engine+/// verbatim, so an index created with the dotted (and string-valued) form used+/// to store a flag that the write guard's nested-only lookup never saw.+#[tokio::test]+async fn a_block_declared_at_create_time_is_enforced_in_every_spelling() {+ for (n, settings) in [+ json!({ "index": { "blocks": { "write": true } } }),+ json!({ "index.blocks.write": true }),+ json!({ "index.blocks.write": "true" }),+ json!({ "index": { "blocks.write": "true" } }),+ ]+ .into_iter()+ .enumerate()+ {+ 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);+ let app = xerj_api::router::build_es_compat_router(state);++ let name = format!("created{n}");+ let (status, body) =+ put_json(&app, &format!("/{name}"), json!({ "settings": settings })).await;+ assert_eq!(status, StatusCode::OK, "create {settings}: {body}");++ assert_eq!(+ write_doc(&app, &name, "1").await,+ StatusCode::FORBIDDEN,+ "a create-time block written as {settings} must deny writes"+ );++ // …and it must still be removable, which means the stray spelling has+ // to be cleared alongside the canonical one.+ let (status, _) = delete(&app, &format!("/{name}/_block/write")).await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(+ write_doc(&app, &name, "1").await,+ StatusCode::CREATED,+ "a create-time block written as {settings} must be removable"+ );+ }+}++#[tokio::test]+async fn the_block_api_has_a_delete_verb() {+ let (app, _dir) = app_with_index("blockdelete").await;++ put_empty(&app, "/blockdelete/_block/write").await;+ assert_eq!(+ write_doc(&app, "blockdelete", "1").await,+ StatusCode::FORBIDDEN+ );++ let (status, body) = delete(&app, "/blockdelete/_block/write").await;+ assert_eq!(+ status,+ StatusCode::OK,+ "DELETE /{{index}}/_block/{{block}} must exist — the route was PUT-only, \+ so this answered 405 and the block had no removal path: {body}"+ );+ assert_eq!(body["acknowledged"], json!(true), "body: {body}");+ assert_eq!(body["indices"][0]["blocked"], json!(false), "body: {body}");++ assert_eq!(+ write_doc(&app, "blockdelete", "1").await,+ StatusCode::CREATED,+ "writes must be admitted again once the block is deleted"+ );+}++#[tokio::test]+async fn deleting_an_unknown_block_name_is_a_client_error() {+ let (app, _dir) = app_with_index("blockvalidate").await;++ let (status, _) = delete(&app, "/blockvalidate/_block/not_a_block").await;+ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "the DELETE verb must validate the block name like the PUT verb does"+ );+}++#[tokio::test]+async fn a_block_is_visible_in_the_settings_it_is_cleared_through() {+ let (app, _dir) = app_with_index("blockvisible").await;++ put_empty(&app, "/blockvisible/_block/write").await;+ let (_, body) = get(&app, "/blockvisible/_settings").await;+ assert_eq!(+ body["blockvisible"]["settings"]["index"]["blocks"]["write"],+ json!(true),+ "a block set through _block must show up in GET _settings — otherwise the \+ only API that reports blocks disagrees with the one that enforces them: \+ {body}"+ );++ delete(&app, "/blockvisible/_block/write").await;+ let (_, body) = get(&app, "/blockvisible/_settings").await;+ assert!(+ body["blockvisible"]["settings"]["index"]["blocks"]["write"].is_null(),+ "a cleared block must disappear from GET _settings: {body}"+ );+}++// ── 2. read_only_allow_delete / read_only were inverted ──────────────────────++#[tokio::test]+async fn read_only_allow_delete_blocks_writes_and_not_reads() {+ let (app, _dir) = app_with_index("floodstage").await;++ let (status, _) = put_empty(&app, "/floodstage/_block/read_only_allow_delete").await;+ assert_eq!(status, StatusCode::OK);++ let (status, body) = get(&app, "/floodstage/_search").await;+ assert_eq!(+ status,+ StatusCode::OK,+ "read_only_allow_delete is a WRITE-level block; searches stay served. \+ The pre-fix code set index.blocks.read instead: {body}"+ );++ assert_eq!(+ write_doc(&app, "floodstage", "1").await,+ StatusCode::TOO_MANY_REQUESTS,+ "read_only_allow_delete must deny writes, with the 429 ES answers for the \+ flood-stage block (not the 403 the explicit blocks get)"+ );+}++#[tokio::test]+async fn read_only_allow_delete_denies_document_deletes() {+ let (app, _dir) = app_with_index("floodstagedel").await;++ put_empty(&app, "/floodstagedel/_block/read_only_allow_delete").await;++ let (status, body) = delete(&app, "/floodstagedel/_doc/seed").await;+ assert_eq!(+ status,+ StatusCode::TOO_MANY_REQUESTS,+ "deleting *documents* under this block is denied — it grows the index \+ before it shrinks it, which is the opposite of what a node out of disk \+ needs. Only deleting the index itself stays allowed: {body}"+ );+}++#[tokio::test]+async fn read_only_allow_delete_still_allows_deleting_the_index() {+ let (app, _dir) = app_with_index("floodstagedrop").await;++ put_empty(&app, "/floodstagedrop/_block/read_only_allow_delete").await;++ let (status, body) = delete(&app, "/floodstagedrop").await;+ assert_eq!(+ status,+ StatusCode::OK,+ "dropping the index is the one write this block exists to permit: {body}"+ );+}++#[tokio::test]+async fn read_only_blocks_writes_and_not_reads() {+ let (app, _dir) = app_with_index("readonly").await;++ put_empty(&app, "/readonly/_block/read_only").await;++ let (status, body) = get(&app, "/readonly/_search").await;+ assert_eq!(+ status,+ StatusCode::OK,+ "read_only means readable-but-not-writable; the pre-fix alias expansion \+ forced index.blocks.read on as well: {body}"+ );+ assert_eq!(+ write_doc(&app, "readonly", "1").await,+ StatusCode::FORBIDDEN,+ "read_only must still deny writes, with 403"+ );+}++#[tokio::test]+async fn read_only_is_cleared_by_clearing_read_only() {+ let (app, _dir) = app_with_index("readonlyclear").await;++ put_empty(&app, "/readonlyclear/_block/read_only").await;+ assert_eq!(+ write_doc(&app, "readonlyclear", "1").await,+ StatusCode::FORBIDDEN+ );++ delete(&app, "/readonlyclear/_block/read_only").await;++ assert_eq!(+ write_doc(&app, "readonlyclear", "1").await,+ StatusCode::CREATED,+ "clearing read_only must lift the write denial — with the old alias \+ expansion it left an independent blocks.write behind that nothing \+ addressed by name could reach"+ );+}++#[tokio::test]+async fn an_explicit_read_block_still_denies_reads() {+ let (app, _dir) = app_with_index("readblocked").await;++ put_empty(&app, "/readblocked/_block/read").await;++ let (status, _) = get(&app, "/readblocked/_search").await;+ assert_eq!(+ status,+ StatusCode::FORBIDDEN,+ "index.blocks.read is the block that denies reads, and it must keep doing so"+ );+}++// ── 3. A blocked bulk is 403, not 500 ────────────────────────────────────────++#[tokio::test]+async fn bulk_auto_id_against_a_write_blocked_index_is_403_per_item() {+ let (app, _dir) = app_with_index("bulkauto").await;++ put_empty(&app, "/bulkauto/_block/write").await;++ // No `_id` — this is the auto-ID path, which batches through+ // `index_batch_turbo_raw` and fails as a whole batch.+ let (status, body) = bulk(&app, "/bulkauto/_bulk", "{\"index\":{}}\n{\"value\":2}\n").await;+ assert_eq!(status, StatusCode::OK, "the bulk envelope itself is 200");+ assert_eq!(body["errors"], json!(true), "body: {body}");+ assert_eq!(+ body["items"][0]["index"]["status"],+ json!(403),+ "a write block is a client error (cluster_block_exception, 403), but the \+ inline whole-batch match in bulk.rs sent it to `_ => 500`: {body}"+ );+}++#[tokio::test]+async fn bulk_with_an_explicit_id_against_a_write_blocked_index_is_403_per_item() {+ let (app, _dir) = app_with_index("bulkid").await;++ put_empty(&app, "/bulkid/_block/write").await;++ let (status, body) = bulk(+ &app,+ "/bulkid/_bulk",+ "{\"index\":{\"_id\":\"9\"}}\n{\"value\":2}\n",+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(body["errors"], json!(true), "body: {body}");+ assert_eq!(+ body["items"][0]["index"]["status"],+ json!(403),+ "body: {body}"+ );+}++#[tokio::test]+async fn bulk_against_a_flood_stage_blocked_index_stays_429_per_item() {+ let (app, _dir) = app_with_index("bulkflood").await;++ put_empty(&app, "/bulkflood/_block/read_only_allow_delete").await;++ let (_, body) = bulk(&app, "/bulkflood/_bulk", "{\"index\":{}}\n{\"value\":2}\n").await;+ assert_eq!(+ body["items"][0]["index"]["status"],+ json!(429),+ "the flood-stage block keeps its retryable 429 — routing every bulk error \+ through one mapper must not flatten that into the 403 the other blocks \+ get: {body}"+ );+}++#[tokio::test]+async fn a_bulk_delete_against_a_write_blocked_index_is_403_per_item() {+ let (app, _dir) = app_with_index("bulkdel").await;++ put_empty(&app, "/bulkdel/_block/write").await;++ let (_, body) = bulk(&app, "/bulkdel/_bulk", "{\"delete\":{\"_id\":\"seed\"}}\n").await;+ assert_eq!(+ body["items"][0]["delete"]["status"],+ json!(403),+ "body: {body}"+ );+}++// ── Round trip ───────────────────────────────────────────────────────────────++#[tokio::test]+async fn block_set_and_clear_round_trips_across_every_route() {+ let (app, _dir) = app_with_index("roundtrip").await;++ for (n, (path, expected_denied)) in [+ ("/roundtrip/_block/write", StatusCode::FORBIDDEN),+ ("/roundtrip/_block/read_only", StatusCode::FORBIDDEN),+ (+ "/roundtrip/_block/read_only_allow_delete",+ StatusCode::TOO_MANY_REQUESTS,+ ),+ ]+ .into_iter()+ .enumerate()+ {+ // A fresh id each pass, so the admitted write is unambiguously a 201+ // create rather than a 200 update of the previous pass's document.+ let id = format!("rt{n}");+ put_empty(&app, path).await;+ assert_eq!(+ write_doc(&app, "roundtrip", &id).await,+ expected_denied,+ "{path} should deny the write"+ );+ delete(&app, path).await;+ assert_eq!(+ write_doc(&app, "roundtrip", &id).await,+ StatusCode::CREATED,+ "{path} should be fully removable"+ );+ }+}diff --git a/engine/crates/xerj-engine/src/bulk.rs b/engine/crates/xerj-engine/src/bulk.rsindex 49fc43a16..9e9181d35 100644--- a/engine/crates/xerj-engine/src/bulk.rs+++ b/engine/crates/xerj-engine/src/bulk.rs@@ -154,6 +154,19 @@ fn malformed_document_reason()}+/// The one place a bulk item's per-item `status` is derived from an engine+/// error. Every `Err` arm in this module routes through here.+///+/// It defers to `XerjError::http_status()` (409 version conflict, 404 not+/// found, 403 index blocked, 400 bad mapping/query, 429 exhausted …) and only+/// overrides one case: the disk flood-stage block reports itself as+/// `read_only_allow_delete`, which ES answers **429**, not the 403 the other+/// blocks get (`IndexMetadata.INDEX_READ_ONLY_ALLOW_DELETE_BLOCK` carries+/// `RestStatus.TOO_MANY_REQUESTS`; approach only, no ES code reproduced).+///+/// Three call sites used to inline their own `match` instead, and each listed+/// only the errors its author had in mind — so a genuine write block fell+/// through `_ => 500` and a blocked bulk looked like a server fault.fn engine_error_http_status(error: &EngineError) -> u16 {match error {EngineError::Common(xerj_common::XerjError::IndexBlocked { block_type, .. })@@ -1453,15 +1466,7 @@ pub async fn process_bulk_with_opts(Err(e) => {// Whole-batch failure (e.g. ResourceExhausted → 429):// mark every item in the batch with the same status.- let status = match &e {- EngineError::Common(xerj_common::XerjError::ResourceExhausted { .. })- | EngineError::Common(xerj_common::XerjError::CircuitBreaking { .. }) => 429,- EngineError::Common(xerj_common::XerjError::IndexBlocked {- block_type,- ..- }) if block_type.contains("read_only_allow_delete") => 429,- _ => 500,- };+ let status = engine_error_http_status(&e);for item_idx in item_indices {items[item_idx] = Some(BulkItemResult {action: "index".into(),@@ -1549,22 +1554,7 @@ pub async fn process_bulk_with_opts(});}Err(e) => {- let status = match &e {- EngineError::Common(xerj_common::XerjError::ResourceExhausted {- ..- })- | EngineError::Common(xerj_common::XerjError::CircuitBreaking { .. }) => {- 429- }- EngineError::Common(xerj_common::XerjError::IndexBlocked {- block_type,- ..- }) if block_type.contains("read_only_allow_delete") => 429,- // Default-format date rejection ("failed to parse- // field [..] of type [date]") — ES answers 400.- EngineError::Common(xerj_common::XerjError::InvalidMapping { .. }) => 400,- _ => 500,- };+ let status = engine_error_http_status(&e);items[item_idx] = Some(BulkItemResult {action: "index".into(),index: index_name.clone(),@@ -2004,19 +1994,7 @@ pub async fn process_bulk_with_opts(// Map engine-level errors to the correct HTTP status so// per-item error objects carry the status ES clients key// off of. VersionConflict → 409, NotFound → 404.- let status = match &e {- EngineError::Common(xerj_common::XerjError::VersionConflict { .. }) => 409,- EngineError::Common(xerj_common::XerjError::DocumentNotFound { .. }) => 404,- EngineError::Common(xerj_common::XerjError::ResourceExhausted { .. })- | EngineError::Common(xerj_common::XerjError::CircuitBreaking { .. }) => 429,- EngineError::Common(xerj_common::XerjError::IndexBlocked {- block_type,- ..- }) if block_type.contains("read_only_allow_delete") => 429,- // Default-format date rejection — ES answers 400.- EngineError::Common(xerj_common::XerjError::InvalidMapping { .. }) => 400,- _ => 500,- };+ let status = engine_error_http_status(&e);items[item_idx] = Some(BulkItemResult {action: action_type,index: target_index,diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex c5c5b1a9f..77032ce84 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -6005,10 +6005,10 @@ impl Index {external_version: Option<(u64, bool)>,) -> Result<IndexResponse> {// Check write block.- if self.is_write_blocked().await {+ if let Some(block) = self.write_block_reason().await {return Err(EngineError::Common(xerj_common::XerjError::index_blocked(self.name.as_str(),- "write",+ block,)));}// Default-format date validation — before any durable write so a@@ -6329,10 +6329,10 @@ impl Index {return Ok(Vec::new());}- if self.is_write_blocked().await {+ if let Some(block) = self.write_block_reason().await {return Err(EngineError::Common(xerj_common::XerjError::index_blocked(self.name.as_str(),- "write",+ block,)));}// Process-wide admission: disk flood-stage block (item 3) + parent@@ -6678,10 +6678,10 @@ impl Index {return Ok(Vec::new());}let batch_len = docs.len();- if self.is_write_blocked().await {+ if let Some(block) = self.write_block_reason().await {return Err(EngineError::Common(xerj_common::XerjError::index_blocked(self.name.as_str(),- "write",+ block,)));}// Process-wide admission: disk flood-stage block (item 3) + parent@@ -7481,10 +7481,10 @@ impl Index {return Ok(Vec::new());}- if self.is_write_blocked().await {+ if let Some(block) = self.write_block_reason().await {return Err(EngineError::Common(xerj_common::XerjError::index_blocked(self.name.as_str(),- "write",+ block,)));}// Process-wide admission: disk flood-stage block (item 3) + parent@@ -12060,10 +12060,10 @@ impl Index {if_primary_term: Option<u64>,) -> Result<DeleteDocOutcome> {// Check write block.- if self.is_write_blocked().await {+ if let Some(block) = self.write_block_reason().await {return Err(EngineError::Common(xerj_common::XerjError::index_blocked(self.name.as_str(),- "write",+ block,)));}// Process-wide admission: disk flood-stage block (item 3) + parent@@ -17050,58 +17050,190 @@ impl Index {Ok(())}- /// Returns true if the write block is set on this index.- pub async fn is_write_blocked(&self) -> bool {- let settings = self.settings.read().await;- settings- .pointer("/index/blocks/write")- .and_then(Value::as_bool)+ /// Every block name the `_block` API and `index.blocks.*` settings accept.+ pub const BLOCK_NAMES: [&'static str; 5] = [+ "read_only",+ "read_only_allow_delete",+ "write",+ "metadata",+ "read",+ ];++ /// Every JSON location one `index.blocks.<name>` flag can occupy in a+ /// stored settings document, canonical form first.+ ///+ /// A settings body is stored the way the client wrote it — `PUT /{index}`+ /// forwards its `settings` blob to `Index::new` verbatim — and ES accepts+ /// the nested and the dotted spellings interchangeably. Reading only the+ /// nested one meant an index created with+ /// `{"settings": {"index.blocks.write": true}}` reported no block and+ /// admitted every write.+ fn block_flag_pointers(name: &str) -> [String; 4] {+ [+ format!("/index/blocks/{name}"),+ format!("/index/blocks.{name}"),+ format!("/index.blocks.{name}"),+ format!("/blocks/{name}"),+ ]+ }++ /// Reads one `index.blocks.<name>` flag in whichever spelling it was stored+ /// under. Accepts the boolean `true` and the string `"true"` — ES+ /// normalises index settings to strings on the wire, so a settings round+ /// trip can hand us either shape.+ fn block_flag(settings: &Value, name: &str) -> bool {+ Self::block_flag_pointers(name)+ .iter()+ .find_map(|p| match settings.pointer(p) {+ Some(Value::Bool(b)) => Some(*b),+ Some(Value::String(s)) => Some(s.eq_ignore_ascii_case("true")),+ _ => None,+ }).unwrap_or(false)}+ /// Names the block that is currently denying **writes** on this index, or+ /// `None` when writes are admitted.+ ///+ /// The returned name is threaded into `XerjError::IndexBlocked` so the HTTP+ /// layer can pick the status ES picks. Three settings deny writes, and they+ /// do *not* all answer the same status:+ ///+ /// | setting | denies | status |+ /// |---|---|---|+ /// | `index.blocks.write` | writes | 403 |+ /// | `index.blocks.read_only` | writes + metadata changes | 403 |+ /// | `index.blocks.read_only_allow_delete` | writes (incl. doc deletes) | 429 |+ ///+ /// Precedence is 403-before-429, matching how ES collapses a multi-block+ /// `ClusterBlockException` down to one status: a non-retryable block always+ /// wins over a retryable one+ /// (`cluster/block/ClusterBlockException.java:95-107`, approach only — ES is+ /// AGPL/SSPL/Elastic-2.0 and no code from it is reproduced here).+ ///+ /// Note what is deliberately **absent**: none of these deny *reads*. Only+ /// `index.blocks.read` does that. `read_only` means "readable, not+ /// writable", and `read_only_allow_delete` is the disk flood-stage block —+ /// the "allow delete" is index deletion, not document deletion+ /// (`docs/reference/elasticsearch/index-settings/index-block.md:29-34`:+ /// "When `index.blocks.read_only_allow_delete` is set to `true`, deleting+ /// documents is not permitted. However, deleting the index entirely …+ /// is still permitted").+ pub async fn write_block_reason(&self) -> Option<&'static str> {+ let settings = self.settings.read().await;+ for name in ["write", "read_only", "read_only_allow_delete"] {+ if Self::block_flag(&settings, name) {+ return Some(name);+ }+ }+ None+ }++ /// Returns true if any write-denying block is set on this index.+ pub async fn is_write_blocked(&self) -> bool {+ self.write_block_reason().await.is_some()+ }+/// Returns true if the read block is set on this index.+ ///+ /// Only `index.blocks.read` denies reads. `read_only` and+ /// `read_only_allow_delete` leave the index searchable — see+ /// [`Self::write_block_reason`].pub async fn is_read_blocked(&self) -> bool {let settings = self.settings.read().await;- settings- .pointer("/index/blocks/read")- .and_then(Value::as_bool)- .unwrap_or(false)+ Self::block_flag(&settings, "read")+ }++ /// Erase every spelling of one block flag from a settings document, leaving+ /// the canonical nested slot for the caller to write (or leave absent).+ fn remove_block_spellings(settings: &mut Value, name: &str) {+ let Some(root) = settings.as_object_mut() else {+ return;+ };+ root.remove(&format!("index.blocks.{name}"));+ if let Some(blocks) = root.get_mut("blocks").and_then(Value::as_object_mut) {+ blocks.remove(name);+ }+ if let Some(index) = root.get_mut("index").and_then(Value::as_object_mut) {+ index.remove(&format!("blocks.{name}"));+ if let Some(blocks) = index.get_mut("blocks").and_then(Value::as_object_mut) {+ blocks.remove(name);+ }+ }}/// Set a named block on the index (`read_only`, `read_only_allow_delete`, `write`, `metadata`, `read`).////// Stores as `index.blocks.<block_name> = true` in the settings.pub async fn set_block(&self, block_name: &str) -> Result<()> {+ self.set_block_state(block_name, true).await+ }++ /// Clear a named block. The inverse of [`Self::set_block`], and what both+ /// `DELETE /{index}/_block/{block}` and a+ /// `PUT /{index}/_settings {"index.blocks.<name>": false}` land on.+ pub async fn clear_block(&self, block_name: &str) -> Result<()> {+ self.set_block_state(block_name, false).await+ }++ /// Set or clear `index.blocks.<block_name>`, persisting the result.+ ///+ /// Stores exactly the block the caller named — no alias expansion. Deriving+ /// the effect at read time ([`Self::write_block_reason`]) instead of writing+ /// derived flags at set time is what makes removal work: with expansion, a+ /// `read_only` block left an independent `blocks.write: true` behind that+ /// clearing `read_only` could not reach.+ ///+ /// Both directions first drop every non-canonical spelling of the block+ /// ([`Self::block_flag_pointers`]), so a dotted key left by a create-time+ /// settings body cannot outlive the nested key and silently re-block the+ /// index — the same "block with no removal path" shape this fixes.+ pub async fn set_block_state(&self, block_name: &str, enabled: bool) -> Result<()> {let mut settings = {let guard = self.settings.read().await;guard.clone()};- // Ensure nested structure: settings["index"]["blocks"][block_name] = true- if settings.is_null() {+ // Ensure nested structure: settings["index"]["blocks"][block_name].+ if !settings.is_object() {settings = Value::Object(serde_json::Map::new());}+ Self::remove_block_spellings(&mut settings, block_name);let obj = settings.as_object_mut().unwrap();- let index_obj = obj+ let index_obj = match obj.entry("index").or_insert_with(|| Value::Object(serde_json::Map::new())).as_object_mut()- .unwrap();- let blocks_obj = index_obj+ {+ Some(o) => o,+ // A non-object `index` value (corrupt settings.json) — replace it+ // rather than panic.+ None => {+ obj.insert("index".to_string(), Value::Object(serde_json::Map::new()));+ obj.get_mut("index").unwrap().as_object_mut().unwrap()+ }+ };+ let blocks_obj = match index_obj.entry("blocks").or_insert_with(|| Value::Object(serde_json::Map::new())).as_object_mut()- .unwrap();- blocks_obj.insert(block_name.to_string(), Value::Bool(true));-- // Handle aliases: read_only also sets both read + write blocks.- if block_name == "read_only" {- blocks_obj.insert("read".to_string(), Value::Bool(true));- blocks_obj.insert("write".to_string(), Value::Bool(true));- }- if block_name == "read_only_allow_delete" {- blocks_obj.insert("read".to_string(), Value::Bool(true));- // write is NOT blocked (only delete is allowed)+ {+ Some(o) => o,+ None => {+ index_obj.insert("blocks".to_string(), Value::Object(serde_json::Map::new()));+ index_obj+ .get_mut("blocks")+ .unwrap()+ .as_object_mut()+ .unwrap()+ }+ };+ if enabled {+ blocks_obj.insert(block_name.to_string(), Value::Bool(true));+ } else {+ // Removing the key rather than storing `false` keeps a cleared+ // block out of GET /_settings, which is what ES shows.+ blocks_obj.remove(block_name);}let path = self.data_dir.join("settings.json");@@ -17111,6 +17243,86 @@ impl Index {Ok(())}+ /// Apply an `index.blocks` sub-document from a settings update.+ ///+ /// Accepts the nested (`{"index": {"blocks": {"write": false}}}`), dotted+ /// (`{"index.blocks.write": false}`) and bare (`{"blocks": {...}}`) shapes+ /// that ES settings bodies come in. Values may be JSON booleans or the+ /// strings `"true"`/`"false"` — ES stringifies index settings on the wire.+ ///+ /// Returns the block names that changed state.+ pub async fn apply_block_settings(&self, body: &Value) -> Result<Vec<String>> {+ let as_bool = |v: &Value| -> Option<bool> {+ match v {+ Value::Bool(b) => Some(*b),+ Value::String(s) if s.eq_ignore_ascii_case("true") => Some(true),+ Value::String(s) if s.eq_ignore_ascii_case("false") => Some(false),+ Value::Null => Some(false),+ _ => None,+ }+ };++ // Collect name → desired state from every accepted shape.+ let mut wanted: Vec<(String, bool)> = Vec::new();+ let mut collect_nested = |blocks: &Value| {+ if let Some(map) = blocks.as_object() {+ for (name, v) in map {+ if Self::BLOCK_NAMES.contains(&name.as_str()) {+ if let Some(b) = as_bool(v) {+ wanted.push((name.clone(), b));+ }+ }+ }+ }+ };+ if let Some(b) = body.pointer("/index/blocks") {+ collect_nested(b);+ }+ if let Some(b) = body.get("blocks") {+ collect_nested(b);+ }+ if let Some(map) = body.as_object() {+ for (k, v) in map {+ let name = k+ .strip_prefix("index.blocks.")+ .or_else(|| k.strip_prefix("blocks."));+ if let Some(name) = name {+ if Self::BLOCK_NAMES.contains(&name) {+ if let Some(b) = as_bool(v) {+ wanted.push((name.to_string(), b));+ }+ }+ }+ }+ }+ // `{"index": {"blocks.write": false}}` — dotted under a nested `index`.+ if let Some(map) = body.get("index").and_then(Value::as_object) {+ for (k, v) in map {+ if let Some(name) = k.strip_prefix("blocks.") {+ if Self::BLOCK_NAMES.contains(&name) {+ if let Some(b) = as_bool(v) {+ wanted.push((name.to_string(), b));+ }+ }+ }+ }+ }++ let mut applied = Vec::new();+ for (name, enabled) in wanted {+ let current = {+ let guard = self.settings.read().await;+ Self::block_flag(&guard, &name)+ };+ if current == enabled {+ continue;+ }+ self.set_block_state(&name, enabled).await?;+ applied.push(name);+ }+ Ok(applied)+ }+// ── Schema ────────────────────────────────────────────────────────────────/// Get the current schema.diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rsindex 527d25194..208918097 100644--- a/engine/crates/xerj-engine/tests/integration.rs+++ b/engine/crates/xerj-engine/tests/integration.rs@@ -3381,6 +3381,131 @@ async fn test_index_read_block() {);}+/// `write_block_reason` names the block, and the name is what the HTTP layer+/// turns into a status. `read_only_allow_delete` is the one that answers 429+/// instead of 403, so mislabelling it silently changes the wire contract.+#[tokio::test]+async fn write_block_reason_names_the_block_that_denied_the_write() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("reasons", Schema::empty()).unwrap();+ let idx = engine.get_index("reasons").unwrap();++ assert_eq!(idx.write_block_reason().await, None);++ for name in ["write", "read_only", "read_only_allow_delete"] {+ idx.set_block(name).await.unwrap();+ assert_eq!(+ idx.write_block_reason().await,+ Some(name),+ "{name} must both deny writes and identify itself"+ );+ idx.clear_block(name).await.unwrap();+ assert_eq!(+ idx.write_block_reason().await,+ None,+ "clearing {name} must lift the denial"+ );+ }+}++/// ES collapses a multi-block rejection to a single status by letting a+/// non-retryable block outrank a retryable one, so an index carrying both an+/// explicit `write` block (403) and the flood-stage block (429) reports 403.+#[tokio::test]+async fn an_explicit_block_outranks_the_flood_stage_block() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("precedence", Schema::empty()).unwrap();+ let idx = engine.get_index("precedence").unwrap();++ idx.set_block("read_only_allow_delete").await.unwrap();+ idx.set_block("write").await.unwrap();+ assert_eq!(+ idx.write_block_reason().await,+ Some("write"),+ "the 403 block must win while it is set"+ );++ idx.clear_block("write").await.unwrap();+ assert_eq!(+ idx.write_block_reason().await,+ Some("read_only_allow_delete"),+ "and the 429 block must still be in force underneath it"+ );+}++/// A settings body reaches us in whichever of ES's spellings the client library+/// chose, and index settings survive a round trip as strings. All of them have+/// to move the block, or "clear the block" silently no-ops for some clients.+#[tokio::test]+async fn apply_block_settings_accepts_every_settings_spelling() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine.create_index("shapes", Schema::empty()).unwrap();+ let idx = engine.get_index("shapes").unwrap();++ let set_forms = [+ json!({ "index": { "blocks": { "write": true } } }),+ json!({ "index.blocks.write": true }),+ json!({ "index": { "blocks.write": true } }),+ json!({ "blocks": { "write": true } }),+ json!({ "index": { "blocks": { "write": "true" } } }),+ ];+ let clear_forms = [+ json!({ "index": { "blocks": { "write": false } } }),+ json!({ "index.blocks.write": false }),+ json!({ "index": { "blocks.write": false } }),+ json!({ "blocks": { "write": false } }),+ json!({ "index": { "blocks": { "write": "false" } } }),+ ];++ for (set, clear) in set_forms.iter().zip(clear_forms.iter()) {+ let applied = idx.apply_block_settings(set).await.unwrap();+ assert_eq!(applied, vec!["write".to_string()], "setting via {set}");+ assert!(idx.is_write_blocked().await, "setting via {set}");++ let applied = idx.apply_block_settings(clear).await.unwrap();+ assert_eq!(applied, vec!["write".to_string()], "clearing via {clear}");+ assert!(!idx.is_write_blocked().await, "clearing via {clear}");+ }++ // Unrelated settings keys must not be mistaken for blocks.+ let applied = idx+ .apply_block_settings(&json!({ "index": { "number_of_replicas": 0 } }))+ .await+ .unwrap();+ assert!(+ applied.is_empty(),+ "non-block settings must not touch blocks"+ );+}++/// The blocks live in the index's own `settings.json`, so they have to survive+/// a reopen — a block you can only clear by restarting is the defect; a block+/// that *clears itself* on restart is the same defect wearing the other face.+#[tokio::test]+async fn blocks_survive_a_reopen_and_stay_clearable() {+ let dir = TempDir::new().unwrap();+ {+ let engine = make_engine(&dir);+ engine.create_index("persisted", Schema::empty()).unwrap();+ let idx = engine.get_index("persisted").unwrap();+ idx.set_block("read_only_allow_delete").await.unwrap();+ }++ let engine = make_engine(&dir);+ let idx = engine.get_index("persisted").unwrap();+ assert_eq!(+ idx.write_block_reason().await,+ Some("read_only_allow_delete"),+ "the block must be reloaded from settings.json"+ );++ idx.clear_block("read_only_allow_delete").await.unwrap();+ assert_eq!(idx.write_block_reason().await, None);+}+// ── New feature tests ─────────────────────────────────────────────────────────// ── SQL query test ────────────────────────────────────────────────────────────