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(console-api): require If-Match on dashboard writes — 428 when missing (#210)
xerj-org1b4ee45b718d
diff --git a/engine/crates/xerj-console-api/src/dashboards.rs b/engine/crates/xerj-console-api/src/dashboards.rsindex c5fea87a1..d5541c8b2 100644--- a/engine/crates/xerj-console-api/src/dashboards.rs+++ b/engine/crates/xerj-console-api/src/dashboards.rs@@ -2,9 +2,11 @@//!//! Replaces `localStorage["xerj.dashboards"]` and//! `localStorage["xerj.layout.<id>"]` with engine-backed durable state.-//! Every shared dashboard write expects an `If-Match: W/"<version>"`-//! etag for optimistic concurrency; private dashboards skip that check-//! since only the owner ever writes them.+//! Every dashboard write (PUT / PATCH) **requires** an+//! `If-Match: W/"<version>"` etag for optimistic concurrency: a missing+//! header is rejected with 428 Precondition Required, a stale one with+//! 409 Conflict. This applies to private dashboards too — one owner+//! with two tabs open is still two writers.//!//! Real-time push (SSE `/_stream`) is NOT implemented in this release://! there is no `/_stream` endpoint on dashboards or views, and none is@@ -572,10 +574,19 @@ fn require_active(sess: &AuthSession) -> ConsoleResult<()> {}fn enforce_etag(headers: &HeaderMap, current_version: u64) -> ConsoleResult<()> {- // If-Match optional but recommended; if present, must match the current- // version (in either weak `W/"7"` or unweak `"7"` form).+ // If-Match is REQUIRED on every dashboard write (issue #210). It used to+ // be "optional but recommended", which made the 409 lost-update+ // protection opt-in: two writers that never sent the header both+ // succeeded and the second silently clobbered the first. A missing+ // header is now 428 Precondition Required; a present-but-stale header+ // stays 409 Conflict (the value must match the current version, in+ // either weak `W/"7"` or unweak `"7"` form).let Some(if_match) = headers.get("if-match").and_then(|v| v.to_str().ok()) else {- return Ok(());+ return Err(ConsoleApiError::PreconditionRequired(format!(+ "dashboard writes require an If-Match header; \+ GET the dashboard and retry with If-Match: W/\"<version>\" \+ (current = W/\"{current_version}\")"+ )));};let trimmed = if_match.trim();let unwrapped = trimmed.trim_start_matches("W/").trim_matches('"');diff --git a/engine/crates/xerj-console-api/src/error.rs b/engine/crates/xerj-console-api/src/error.rsindex 69f109b55..e4719380a 100644--- a/engine/crates/xerj-console-api/src/error.rs+++ b/engine/crates/xerj-console-api/src/error.rs@@ -19,6 +19,12 @@ pub enum ConsoleApiError {#[error("conflict: {0}")]Conflict(String),+ /// RFC 6585 §3 — the request must carry a precondition header+ /// (`If-Match`) and did not. Distinct from [`Self::Conflict`], which+ /// means the precondition was sent but did not match.+ #[error("precondition required: {0}")]+ PreconditionRequired(String),+#[error("forbidden: {0}")]Forbidden(String),@@ -48,6 +54,7 @@ impl ConsoleApiError {match self {Self::NotFound(_) => StatusCode::NOT_FOUND,Self::Conflict(_) => StatusCode::CONFLICT,+ Self::PreconditionRequired(_) => StatusCode::PRECONDITION_REQUIRED,Self::Forbidden(_) => StatusCode::FORBIDDEN,Self::Unauthorized(_) => StatusCode::UNAUTHORIZED,Self::BadRequest(_) => StatusCode::BAD_REQUEST,@@ -61,6 +68,7 @@ impl ConsoleApiError {match self {Self::NotFound(_) => "not_found",Self::Conflict(_) => "conflict",+ Self::PreconditionRequired(_) => "precondition_required",Self::Forbidden(_) => "forbidden",Self::Unauthorized(_) => "unauthorized",Self::BadRequest(_) => "bad_request",diff --git a/engine/crates/xerj-console-api/tests/phase3_user_state.rs b/engine/crates/xerj-console-api/tests/phase3_user_state.rsindex 5fd0e8c31..16c64ddea 100644--- a/engine/crates/xerj-console-api/tests/phase3_user_state.rs+++ b/engine/crates/xerj-console-api/tests/phase3_user_state.rs@@ -255,6 +255,96 @@ async fn dashboards_create_get_list_patch_delete() {assert_eq!(r.status(), 404);}+/// Issue #210 — a write WITHOUT If-Match must be rejected with 428+/// Precondition Required, not silently accepted. Before the fix,+/// `enforce_etag` returned Ok on a missing header, so two writers that+/// never sent it both succeeded and the second clobbered the first+/// (lost update with no error).+#[tokio::test]+async fn dashboard_write_without_if_match_is_428() {+ let app = boot_with_session().await;++ // CREATE (no If-Match needed — there is no prior version to guard).+ let r = app+ .router+ .clone()+ .oneshot(req(+ "POST",+ "/_xerj-console/api/v1/dashboards",+ &app.cookie,+ Some(json!({ "name": "Original", "visibility": "private" })),+ ))+ .await+ .unwrap();+ let (status, body) = body_json(r).await;+ assert_eq!(status, 201, "create: {body}");+ let dash_id = body["data"]["id"].as_str().unwrap().to_string();++ // PATCH without If-Match → 428 Precondition Required.+ let r = app+ .router+ .clone()+ .oneshot(req(+ "PATCH",+ &format!("/_xerj-console/api/v1/dashboards/{dash_id}"),+ &app.cookie,+ Some(json!({ "name": "Writer B clobber" })),+ ))+ .await+ .unwrap();+ let (status, body) = body_json(r).await;+ assert_eq!(status, 428, "PATCH without If-Match must 428: {body}");+ assert_eq!(body["error"]["code"], "precondition_required", "{body}");++ // PUT without If-Match → 428 as well.+ let r = app+ .router+ .clone()+ .oneshot(req(+ "PUT",+ &format!("/_xerj-console/api/v1/dashboards/{dash_id}"),+ &app.cookie,+ Some(json!({ "name": "Writer B clobber", "visibility": "private" })),+ ))+ .await+ .unwrap();+ let (status, body) = body_json(r).await;+ assert_eq!(status, 428, "PUT without If-Match must 428: {body}");++ // Neither headerless write took effect.+ let r = app+ .router+ .clone()+ .oneshot(req(+ "GET",+ &format!("/_xerj-console/api/v1/dashboards/{dash_id}"),+ &app.cookie,+ None,+ ))+ .await+ .unwrap();+ let (_, body) = body_json(r).await;+ assert_eq!(+ body["data"]["name"], "Original",+ "rejected write must not land"+ );+ assert_eq!(body["data"]["version"], 1);++ // The same PATCH with a correct If-Match still succeeds.+ let ok = Request::builder()+ .method("PATCH")+ .uri(format!("/_xerj-console/api/v1/dashboards/{dash_id}"))+ .header("cookie", &app.cookie)+ .header("content-type", "application/json")+ .header("if-match", "W/\"1\"")+ .body(Body::from(json!({ "name": "Legit edit" }).to_string()))+ .unwrap();+ let r = app.router.clone().oneshot(ok).await.unwrap();+ let (status, body) = body_json(r).await;+ assert_eq!(status, 200, "write WITH If-Match must pass: {body}");+ assert_eq!(body["data"]["version"], 2);+}+#[tokio::test]async fn dashboards_unauth_returns_401() {let app = boot_with_session().await;diff --git a/xerj-ux/src/data/dashboard-api.js b/xerj-ux/src/data/dashboard-api.jsindex ea20541ec..94d9ac92d 100644--- a/xerj-ux/src/data/dashboard-api.js+++ b/xerj-ux/src/data/dashboard-api.js@@ -10,10 +10,13 @@// Every method returns the parsed Dashboard doc (or the list envelope).// Optimistic concurrency: PUT/PATCH send `If-Match: W/"<version>"` built// from the doc's own `version` field (the primary concurrency source);-// the ETag response header is captured too as a convenience.+// the ETag response header is captured too as a convenience. The backend+// REQUIRES the header on writes (issue #210): a missing If-Match is 428+// Precondition Required, a stale one is 409 Conflict — both recoverable+// by re-GET + retry with the fresh version.//-// Errors bubble up as Error objects carrying `.status` (409/403/404/…)-// so the store can branch on a stale-etag 409 and re-GET.+// Errors bubble up as Error objects carrying `.status` (409/428/403/…)+// so the store can branch on a stale/missing-etag error and re-GET.// ============================================================import { apiRaw } from '../xerj-console-auth.js';diff --git a/xerj-ux/src/data/dashboard-store.js b/xerj-ux/src/data/dashboard-store.jsindex 39f6e3096..39e44b484 100644--- a/xerj-ux/src/data/dashboard-store.js+++ b/xerj-ux/src/data/dashboard-store.js@@ -94,7 +94,9 @@ function enqueue(id, fn) {}/** PATCH a doc, adopting the returned (version-bumped) server doc. On a- * 409 (stale etag) re-GET and retry once with the fresh version. */+ * 409 (stale etag) or 428 (missing If-Match — the backend requires the+ * header on writes, issue #210) re-GET and retry once with the fresh+ * version. */async function pushPatch(id, partial) {const doc = DOCS[id];if (!doc || doc.__local) return; // offline-only doc: nothing to push@@ -102,7 +104,7 @@ async function pushPatch(id, partial) {const { doc: fresh } = await api.patch(id, partial, doc.version);DOCS[id] = fresh; mirror();} catch (e) {- if (e && e.status === 409) {+ if (e && (e.status === 409 || e.status === 428)) {try {const { doc: server } = await api.get(id);// Re-apply our field(s) on top of the server's fresh version.