mirror of
https://github.com/xerj-org/xerj.git
synced 2026-12-03 20:11:52 +08:00
fix(console-api): require If-Match on dashboard writes — 428 when missing (#210)
Motivation Two people editing the same dashboard could silently overwrite each other. enforce_etag (dashboards.rs) treated If-Match as optional: its comment said "optional but recommended" and it returned Ok(()) when the header was absent, so the 409 lost-update protection only applied to clients that opted in. Two writers that never sent the header both got 200 and the second one won — no error, no warning. Same family as #204: a documented safety mechanism that does nothing unless the caller opts in. Root cause enforce_etag's missing-header arm was `return Ok(())`, making the concurrency check opt-in at both write call sites (PUT replace and PATCH, dashboards.rs:300/:332). What changed - enforce_etag now rejects a missing If-Match with a new ConsoleApiError::PreconditionRequired → 428 Precondition Required (RFC 6585 §3), with a message telling the caller the current version to retry with. A present-but-stale header still 409s exactly as before; weak (W/"7") and strong ("7") forms both still accepted. - error.rs: new PreconditionRequired variant mapped to StatusCode::PRECONDITION_REQUIRED / code "precondition_required". - Module doc updated: the etag is required on every write, private dashboards included (one owner with two tabs open is still two writers). The old doc claimed private dashboards skip the check. - Console client: dashboard-api.js already sends If-Match built from doc.version on every PUT/PATCH (ifMatch()); docs updated. The one 409-recovery branch in dashboard-store.js (pushPatch) now also retries on 428 via the same re-GET + reapply path. - CREATE (POST) and the privileged whole-set _bulk endpoint are unchanged: POST has no prior version to guard, and _bulk is an admin/owner-only intentional overwrite used by seeding. - DELETE remains etag-free (unchanged surface, out of this issue's scope; the client already sends If-Match on remove() if the server later chooses to enforce it). Evidence - New test phase3_user_state::dashboard_write_without_if_match_is_428: headerless PATCH and PUT must 428 with code "precondition_required", the rejected write must not land (name/version unchanged), and the same PATCH with If-Match: W/"1" still succeeds. Verified it fails before the fix (headerless PATCH returned 200 and "Writer B clobber" landed) and passes after. - cargo test --release -p xerj-console-api: all suites green (43+3+3+10+7+15+13+2+6+6 = 108 tests, 0 failed). - ES-YAML conformance gate against this build (fresh data dir, port 9710): 1365 passed / 0 failed / 3 skipped. Retrieval xc.py xerj-search queried twice (If-Match/precondition/version-conflict phrasings); top hits were S3 blob-store ETag fixtures and dense-vector mapper code — irrelevant to document-write concurrency, so no peer implementation was drawn on. The fix follows RFC 6585 §3 / RFC 9110 If-Match semantics and this crate's existing 409 path. Files - engine/crates/xerj-console-api/src/dashboards.rs (enforce_etag + docs) - engine/crates/xerj-console-api/src/error.rs (PreconditionRequired) - engine/crates/xerj-console-api/tests/phase3_user_state.rs (new test) - xerj-ux/src/data/dashboard-api.js (docs) - xerj-ux/src/data/dashboard-store.js (428 retry branch) Closes #210
This commit is contained in:
@@ -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('"');
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user