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(api): refuse more than one alias write index at update time (#2876)

ordinary being1fc456970836
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 78b7e3466..191647c62 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -232,6 +232,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
bytes) is reported as the new `version_map` category. On the 1 GB gate's
search node the map held ~0.5 GB that no budget saw. (#2427)
- `xerj autoindex`: Vue (`.vue`) and Svelte (`.svelte`) single-file components are indexed as code instead of being junk-filed as malformed XML. Their `<script>` blocks are parsed with the TypeScript or JavaScript grammar (by `lang`), so their declarations are symbols on the component's own lines, and the record's `language` is `vue` or `svelte`. (#2732)
+- The alias APIs reject an update that would leave more than one
+ `is_write_index: true` member (`POST /_aliases` and
+ `PUT /{index}/_alias/{name}`), including a wildcard add that expands to
+ several indices. The check is on the final state of a batch, so an atomic
+ switch (add the new writer, clear the old one) still works; a rejected
+ update changes nothing instead of leaving an alias whose every write
+ answers 400.
+
- `_reindex` applies `source._source` field filtering to the documents it
copies, so an excluded secret or large field no longer reaches the
destination. `_source:false` is refused with ES's sentence, and a `script`
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 07d374de2..a9517e973 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -26256,6 +26256,49 @@ fn alias_target_is_pattern(spec: &str) -> bool {
.any(|p| p == "_all" || p.contains('*'))
}
+/// The members of `alias` explicitly marked `is_write_index: true`.
+///
+/// A single-member alias with no explicit flag is an implicit write target and
+/// is deliberately not listed: adding a second member with an explicit `true`
+/// leaves exactly one designated write index, which ES accepts. The list is
+/// what the alias-update invariant counts.
+fn alias_write_members(state: &AppState, alias: &str) -> HashSet<String> {
+ let mut writes = HashSet::new();
+ if let Some(members) = state.engine.aliases.get(alias) {
+ for member in members.iter() {
+ let is_write = state
+ .engine
+ .index_alias_metadata
+ .get(member.as_str())
+ .is_some_and(|meta| {
+ meta.get(alias)
+ .and_then(|alias_meta| alias_meta.get("is_write_index"))
+ .and_then(Value::as_bool)
+ == Some(true)
+ });
+ if is_write {
+ writes.insert(member.clone());
+ }
+ }
+ }
+ writes
+}
+
+/// ES's metadata invariant: an alias can designate at most one write index.
+/// Refuse the alias update before it is stored, rather than accepting an alias
+/// whose every later write answers 400.
+fn more_than_one_write_index(alias: &str, writes: &HashSet<String>) -> Option<String> {
+ if writes.len() <= 1 {
+ return None;
+ }
+ let mut names: Vec<&str> = writes.iter().map(String::as_str).collect();
+ names.sort_unstable();
+ Some(format!(
+ "alias [{alias}] has more than one write index [{}]",
+ names.join(", ")
+ ))
+}
+
pub async fn post_aliases(
State(state): State<AppState>,
Json(body): Json<AliasActionsBody>,
@@ -26307,6 +26350,41 @@ pub async fn post_aliases(
plan.push(Resolved::Remove(remove, targets));
}
}
+ // At most one `is_write_index: true` per alias. Actions run in order, so
+ // an atomic swap (add the new write index, then clear the old one) is
+ // valid even though an intermediate action has two. Simulate the final
+ // state and refuse the whole request before the first mutation; otherwise
+ // the alias is persisted and every later write answers 400.
+ let mut write_members: HashMap<String, HashSet<String>> = HashMap::new();
+ for step in &plan {
+ match step {
+ Resolved::Add(add, targets) => {
+ let writes = write_members
+ .entry(add.alias.clone())
+ .or_insert_with(|| alias_write_members(&state, &add.alias));
+ for target in targets {
+ if add.is_write_index == Some(true) {
+ writes.insert(target.clone());
+ } else {
+ writes.remove(target);
+ }
+ }
+ }
+ Resolved::Remove(remove, targets) => {
+ let writes = write_members
+ .entry(remove.alias.clone())
+ .or_insert_with(|| alias_write_members(&state, &remove.alias));
+ for target in targets {
+ writes.remove(target);
+ }
+ }
+ }
+ }
+ for (alias, writes) in &write_members {
+ if let Some(reason) = more_than_one_write_index(alias, writes) {
+ return es_bad_request("illegal_argument_exception", &reason, None);
+ }
+ }
for step in &plan {
match step {
Resolved::Add(add, targets) => {
@@ -26634,6 +26712,20 @@ pub async fn put_alias(
let e = xerj_common::XerjError::index_not_found(&index);
return ApiError::new(e).into_response();
}
+ // Re-putting an alias replaces its definition (including the write flag).
+ // Simulate the final member set and refuse a second write index before
+ // any member is attached, so a rejected PUT leaves the alias untouched.
+ let mut write_members = alias_write_members(&state, &alias);
+ for target in &targets {
+ if alias_meta.get("is_write_index").and_then(Value::as_bool) == Some(true) {
+ write_members.insert(target.clone());
+ } else {
+ write_members.remove(target);
+ }
+ }
+ if let Some(reason) = more_than_one_write_index(&alias, &write_members) {
+ return es_bad_request("illegal_argument_exception", &reason, None);
+ }
for idx in &targets {
if let Err(error) = attach(idx) {
return ApiError::new(xerj_common::XerjError::from(error)).into_response();
diff --git a/engine/crates/xerj-api/tests/alias_write_index_uniqueness.rs b/engine/crates/xerj-api/tests/alias_write_index_uniqueness.rs
new file mode 100644
index 000000000..8066c4e20
--- /dev/null
+++ b/engine/crates/xerj-api/tests/alias_write_index_uniqueness.rs
@@ -0,0 +1,240 @@
+//! An alias may designate at most one write index.
+//!
+//! `POST /_aliases` and `PUT /{index}/_alias/{alias}` used to accept two
+//! members with `is_write_index: true` and answer 200. The resulting alias
+//! was unusable: every document write through it answered 400 "alias [a] has
+//! more than one write index", so the configuration error surfaced only at
+//! the next write, possibly long after the alias update.
+//!
+//! The invariant is checked against the FINAL state of the action batch:
+//! actions run in order, so an atomic swap (add the new write index, then
+//! clear the old one) is valid even though an intermediate step names two.
+//! A refused batch changes nothing, including when the second write index is
+//! added through a wildcard that expands to several indices.
+//!
+//! Elasticsearch is referenced for wire semantics only; no ES code 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 call(app: &axum::Router, method: &str, path: &str, body: Value) -> (StatusCode, Value) {
+ let mut req = Request::builder().method(method).uri(path);
+ let body = if body.is_null() {
+ Body::empty()
+ } else {
+ req = req.header("content-type", "application/json");
+ Body::from(body.to_string())
+ };
+ let response = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = response.status();
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (
+ status,
+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),
+ )
+}
+
+async fn create_index(app: &axum::Router, index: &str) {
+ let (status, body) = call(app, "PUT", &format!("/{index}"), json!({})).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+}
+
+async fn post_actions(app: &axum::Router, actions: Value) -> (StatusCode, Value) {
+ call(app, "POST", "/_aliases", json!({"actions": actions})).await
+}
+
+async fn put_alias(
+ app: &axum::Router,
+ index: &str,
+ alias: &str,
+ body: Value,
+) -> (StatusCode, Value) {
+ call(app, "PUT", &format!("/{index}/_alias/{alias}"), body).await
+}
+
+fn is_write(entry: &Value) -> bool {
+ entry["is_write_index"] == json!(true) || entry["is_write_index"] == json!("true")
+}
+
+/// `(index, is_write_index)` for one alias from `_cat/aliases?format=json`.
+async fn alias_members(app: &axum::Router, alias: &str) -> Vec<(String, bool)> {
+ let (status, body) = call(app, "GET", "/_cat/aliases?format=json", Value::Null).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let mut members: Vec<(String, bool)> = body
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|entry| entry["alias"] == alias)
+ .map(|entry| {
+ (
+ entry["index"].as_str().unwrap_or_default().to_string(),
+ is_write(entry),
+ )
+ })
+ .collect();
+ members.sort_by(|a, b| a.0.cmp(&b.0));
+ members
+}
+
+async fn write_through_alias(app: &axum::Router, alias: &str) -> (StatusCode, Value) {
+ call(app, "PUT", &format!("/{alias}/_doc/1"), json!({"v": "x"})).await
+}
+
+fn reason(body: &Value) -> &str {
+ body.pointer("/error/root_cause/0/reason")
+ .and_then(Value::as_str)
+ .or_else(|| body.get("error").and_then(Value::as_str))
+ .unwrap_or_default()
+}
+
+#[tokio::test]
+async fn post_aliases_rejects_two_write_indices_atomically() {
+ let (app, _dir) = app().await;
+ create_index(&app, "i1").await;
+ create_index(&app, "i2").await;
+
+ let (status, body) = post_actions(
+ &app,
+ json!([
+ {"add": {"index": "i1", "alias": "a", "is_write_index": true}},
+ {"add": {"index": "i2", "alias": "a", "is_write_index": true}}
+ ]),
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
+ assert_eq!(
+ body.pointer("/error/type").and_then(Value::as_str),
+ Some("illegal_argument_exception"),
+ "{body}"
+ );
+ assert!(
+ reason(&body).contains("alias [a] has more than one write index"),
+ "{body}"
+ );
+ assert!(
+ alias_members(&app, "a").await.is_empty(),
+ "a refused batch must leave no alias behind"
+ );
+}
+
+#[tokio::test]
+async fn atomic_swap_in_one_request_is_allowed() {
+ let (app, _dir) = app().await;
+ create_index(&app, "i1").await;
+ create_index(&app, "i2").await;
+ let (status, body) = post_actions(
+ &app,
+ json!([{"add": {"index": "i1", "alias": "swap", "is_write_index": true}}]),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+
+ // Intermediate state has two writers; the final state has one.
+ let (status, body) = post_actions(
+ &app,
+ json!([
+ {"add": {"index": "i2", "alias": "swap", "is_write_index": true}},
+ {"add": {"index": "i1", "alias": "swap", "is_write_index": false}}
+ ]),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+
+ let members = alias_members(&app, "swap").await;
+ assert_eq!(
+ members,
+ vec![("i1".to_string(), false), ("i2".to_string(), true)],
+ "the final write index must be i2"
+ );
+ let (status, body) = write_through_alias(&app, "swap").await;
+ assert_eq!(status, StatusCode::CREATED, "{body}");
+ assert_eq!(body["_index"], "i2", "{body}");
+}
+
+#[tokio::test]
+async fn put_alias_rejects_second_write_index_and_can_switch() {
+ let (app, _dir) = app().await;
+ create_index(&app, "i1").await;
+ create_index(&app, "i2").await;
+ let (status, body) = put_alias(&app, "i1", "a", json!({"is_write_index": true})).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+
+ let (status, body) = put_alias(&app, "i2", "a", json!({"is_write_index": true})).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
+ assert!(
+ reason(&body).contains("alias [a] has more than one write index"),
+ "{body}"
+ );
+ let (status, body) = write_through_alias(&app, "a").await;
+ assert_eq!(status, StatusCode::CREATED, "{body}");
+ assert_eq!(
+ body["_index"], "i1",
+ "the rejected PUT must not move the write index"
+ );
+
+ // The supported switch is two updates: clear the old flag, then set the
+ // new one. Each step leaves at most one write index.
+ let (status, body) = put_alias(&app, "i1", "a", json!({"is_write_index": false})).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let (status, body) = put_alias(&app, "i2", "a", json!({"is_write_index": true})).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let (status, body) = write_through_alias(&app, "a").await;
+ assert_eq!(status, StatusCode::CREATED, "{body}");
+ assert_eq!(body["_index"], "i2", "{body}");
+}
+
+#[tokio::test]
+async fn wildcard_add_with_write_index_is_refused() {
+ let (app, _dir) = app().await;
+ create_index(&app, "i1").await;
+ create_index(&app, "i2").await;
+
+ let (status, body) = post_actions(
+ &app,
+ json!([{"add": {"index": "i*", "alias": "w", "is_write_index": true}}]),
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
+ assert!(
+ reason(&body).contains("alias [w] has more than one write index"),
+ "{body}"
+ );
+ assert!(alias_members(&app, "w").await.is_empty());
+}
+
+#[tokio::test]
+async fn implicit_single_member_plus_explicit_true_is_allowed() {
+ let (app, _dir) = app().await;
+ create_index(&app, "i1").await;
+ create_index(&app, "i2").await;
+ let (status, body) = put_alias(&app, "i1", "a", json!({})).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+
+ // i1 is an implicit write target while alone; adding i2 with an explicit
+ // flag leaves exactly one designated writer, so this is valid.
+ let (status, body) = post_actions(
+ &app,
+ json!([{"add": {"index": "i2", "alias": "a", "is_write_index": true}}]),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let (status, body) = write_through_alias(&app, "a").await;
+ assert_eq!(status, StatusCode::CREATED, "{body}");
+ assert_eq!(body["_index"], "i2", "{body}");
+}
diff --git a/engine/crates/xerj-api/tests/alias_write_routing.rs b/engine/crates/xerj-api/tests/alias_write_routing.rs
index 59be72501..1f31821ce 100644
--- a/engine/crates/xerj-api/tests/alias_write_routing.rs
+++ b/engine/crates/xerj-api/tests/alias_write_routing.rs
@@ -211,7 +211,8 @@ async fn writes_follow_the_alias_write_index_and_refuse_ambiguity() {
assert_eq!(status, StatusCode::CREATED, "{body}");
assert_eq!(body["_index"], "i1", "{body}");
- // Two designated write indices are refused like the ambiguous shape.
+ // A second designated write index is refused at the alias update, before
+ // it can leave the alias unusable; i2 remains the write target.
let (status, body) = call(
&app,
"PUT",
@@ -219,11 +220,12 @@ async fn writes_follow_the_alias_write_index_and_refuse_ambiguity() {
json!({"is_write_index": true}),
)
.await;
- assert_eq!(status, StatusCode::OK, "{body}");
- let (status, body) = call(&app, "PUT", "/multi/_doc/10", json!({"t": "ten"})).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
assert!(
refusal(&body).contains("has more than one write index"),
"{body}"
);
+ let (status, body) = call(&app, "PUT", "/multi/_doc/10", json!({"t": "ten"})).await;
+ assert_eq!(status, StatusCode::CREATED, "{body}");
+ assert_eq!(body["_index"], "i2", "{body}");
}