Repository navigation
Conversation
guardMutation runs content-type, origin, CSRF-header, Access verification, role, body, and idempotency checks in fail-fast order; commitMutation batches an append-only operator_actions audit row atomically with the effect, aborting the whole batch on a duplicate idempotency key so a losing concurrent request can never commit a side effect. Replay returns the stored result only. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
|
Scope checkThis PR changes 1,453 lines across 5 files. Large PRs are harder to review and more likely to be closed without review. If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs. See CONTRIBUTING.md for contribution guidelines. |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-cache | c955172 | Jul 13 2026, 09:27 AM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-do | c955172 | Jul 13 2026, 09:26 AM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-playground | c955172 | Jul 13 2026, 09:26 AM |
There was a problem hiding this comment.
This PR adds the labeler operator console's mutation guard and audit table in a way that matches the ratified W9.2 design. The approach is sound: fail-fast transport/CSRF checks before Access verification, role inheritance recorded correctly in the audit row, plain INSERT batched with effects so a lost idempotency-key race rolls the effect back, and replay responses deliberately avoid leaking the private reason. It is scoped only to apps/labeler, so the core EmDash conventions that don't apply to this private Worker app (Lingui, RTL-safe Tailwind, ec_* locale filtering) are correctly treated as n/a, and no changeset is needed because the package is private.
I checked the diff, the full source of the new files, the existing access-auth.ts/service.ts/assessment-lifecycle.ts conventions, and wrangler.jsonc/vitest.config.ts migration wiring. The migration is forward-only and the new table is auto-discovered.
I found one contract bug in the idempotency replay path and one spec deviation in Content-Type parsing:
-
commitMutationreturns the current request'sresultwhen the stored result is NULL, instead of returning the stored result. If the winner committed withresult = undefined,JSON.stringify(undefined)isundefined, so D1 stores NULL. A losing concurrent/replayed request with the same fingerprint reaches thestored.resultJson === nullshortcut and returns its ownresultrather thanundefined. This breaks the documented replay contract. -
assertJsonContentTypeaccepts parameters other thancharset. The PR description ratifies "media type must beapplication/json(optionalutf-8charset only)". The implementation silently skips non-charset parameters, soapplication/json; boundary=foois accepted. This is not a CSRF bypass (the request remains non-simple), but it is a deviation from the ratified spec.
Both are fixable with small inline changes; see the line-anchored comments.
| if (!stored) throw error; | ||
| if (stored.requestFingerprint !== ctx.fingerprint) | ||
| throw new MutationGuardError("IDEMPOTENCY_KEY_CONFLICT"); | ||
| if (stored.resultJson === null) return result; |
There was a problem hiding this comment.
[needs fixing] The replay path returns the current request's result when the stored result_json is NULL, which breaks the idempotency contract. A winning request that committed with result = undefined stores NULL (because JSON.stringify(undefined) is undefined). When a losing/replayed request with the same fingerprint reaches this line, it returns its own result instead of the stored undefined. This means two identical-idempotency-key requests can observably disagree on the replay result.
Return the stored undefined instead.
| if (stored.resultJson === null) return result; | |
| if (stored.requestFingerprint !== ctx.fingerprint) | |
| throw new MutationGuardError("IDEMPOTENCY_KEY_CONFLICT"); | |
| const winnerResult: TResult = | |
| stored.resultJson === null ? (undefined as TResult) : JSON.parse(stored.resultJson); | |
| return winnerResult; |
Please also add a regression test: two guardMutation/commitMutation races with the same key + body where the winner commits undefined; assert the loser also resolves to undefined (not its own non-undefined result).
There was a problem hiding this comment.
Applied in c955172 — and your finding concealed a second, write-side bug: JSON.stringify(undefined) doesn't store NULL, it's undefined, which D1 refuses to bind (D1_TYPE_ERROR), so committing an undefined result threw outright. Fixed both sides: the insert binds JSON.stringify(result) ?? null, and both read-back paths (commitMutation loser and the guard's replay branch) deserialize a NULL result_json to undefined and return that stored value, never the caller's own result. Regression test drives winner-commits-undefined through both paths and was verified to fail with the read-back reverted.
~ 🤖 Fable
| const [rawMedia, ...params] = header.split(";"); | ||
| if ((rawMedia ?? "").trim().toLowerCase() !== "application/json") | ||
| throw new MutationGuardError("UNSUPPORTED_MEDIA_TYPE"); | ||
| for (const param of params) { | ||
| const eq = param.indexOf("="); | ||
| if (eq === -1) continue; | ||
| if (param.slice(0, eq).trim().toLowerCase() !== "charset") continue; | ||
| const charset = param | ||
| .slice(eq + 1) | ||
| .trim() | ||
| .toLowerCase() | ||
| .replace(QUOTED_VALUE, "$1"); | ||
| if (charset !== "utf-8") throw new MutationGuardError("UNSUPPORTED_MEDIA_TYPE"); | ||
| } | ||
| } |
There was a problem hiding this comment.
[suggestion] assertJsonContentType accepts any Content-Type parameter whose name is not charset. The PR description ratifies "media type must be application/json (optional utf-8 charset only)", but a header like application/json; boundary=foo or application/json; custom=bar is accepted. This is not a CSRF bypass — the request is still non-simple and triggers CORS preflight — but it does not match the spec.
Reject any parameter that is not a charset with value utf-8.
| const [rawMedia, ...params] = header.split(";"); | |
| if ((rawMedia ?? "").trim().toLowerCase() !== "application/json") | |
| throw new MutationGuardError("UNSUPPORTED_MEDIA_TYPE"); | |
| for (const param of params) { | |
| const eq = param.indexOf("="); | |
| if (eq === -1) continue; | |
| if (param.slice(0, eq).trim().toLowerCase() !== "charset") continue; | |
| const charset = param | |
| .slice(eq + 1) | |
| .trim() | |
| .toLowerCase() | |
| .replace(QUOTED_VALUE, "$1"); | |
| if (charset !== "utf-8") throw new MutationGuardError("UNSUPPORTED_MEDIA_TYPE"); | |
| } | |
| } | |
| function assertJsonContentType(request: Request): void { | |
| const header = request.headers.get("Content-Type"); | |
| if (header === null) throw new MutationGuardError("UNSUPPORTED_MEDIA_TYPE"); | |
| const [rawMedia, ...params] = header.split(";"); | |
| if ((rawMedia ?? "").trim().toLowerCase() !== "application/json") | |
| throw new MutationGuardError("UNSUPPORTED_MEDIA_TYPE"); | |
| for (const param of params) { | |
| const eq = param.indexOf("="); | |
| if (eq === -1) throw new MutationGuardError("UNSUPPORTED_MEDIA_TYPE"); | |
| if (param.slice(0, eq).trim().toLowerCase() !== "charset") | |
| throw new MutationGuardError("UNSUPPORTED_MEDIA_TYPE"); | |
| const charset = param | |
| .slice(eq + 1) | |
| .trim() | |
| .toLowerCase() | |
| .replace(QUOTED_VALUE, "$1"); | |
| if (charset !== "utf-8") throw new MutationGuardError("UNSUPPORTED_MEDIA_TYPE"); | |
| } | |
| } |
There was a problem hiding this comment.
Applied in c955172 — the only parameter accepted is now a single charset=utf-8 (case-insensitive, optionally quoted); any other parameter name, a malformed parameter, or a repeated charset → 415. Negative tests added for boundary=foo, custom=bar, a charset+boundary combination, and a duplicated charset.
~ 🤖 Fable
…alue on replay JSON.stringify(undefined) is undefined, which D1 refuses to bind — committing an undefined result threw outright, and the loser read-back returned the caller's own result instead of the stored one. Content-Type now also rejects parameters other than a single utf-8 charset. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
There was a problem hiding this comment.
Re-review of PR #2008. Both of my prior findings have been fixed in this revision.
-
Stored
undefinedresult no longer leaks the caller's own result. In the guard's replay path (apps/labeler/src/mutation-guard.ts:172) and incommitMutation's lost-key race path (apps/labeler/src/mutation-guard.ts:249-250), the code now returnsundefinedwhenresultJsonis SQLNULL, andJSON.parse(...)otherwise. This makes replay and concurrent-race losers observably match the winner's stored response. -
Content-Type parameter enforcement now matches the ratified spec.
assertJsonContentTyperejects any parameter other than a singlecharset=utf-8(case-insensitive, optionally quoted), and rejects repeated or malformed parameters (apps/labeler/src/mutation-guard.ts:266onward). Tests now cover non-charset parameters, repeated charsets, and the quoted charset case.
The remaining code is consistent with the W9.2 design: fail-fast ordering, plain INSERT batched before effect statements so a duplicate idempotency key aborts the whole batch, role inheritance recorded as the actually-held role in the audit row, and replay responses narrowed to { result, actionId } to avoid leaking the private reason. The migration is additive and forward-only, indexes match the established convention, and the tests added in this revision explicitly pin both previously-reported bugs.
No new blocking issues or AGENTS.md violations found.
6474590
into
feat/plugin-registry-labelling-service
What does this PR do?
Adds the labeler operator console's mutation-protection guard and operator-action audit — plan item W9.2, spec §12/§14.4. Every state-changing console endpoint (W9.4–W9.6) will route through
guardMutation→commitMutation, so an effect physically cannot commit without passing all protections and writing its audit row.The guard runs the ratified protections in fail-fast order:
application/json(optionalutf-8charset only) → 415. Also a CSRF layer: HTML forms can't produce it.OriginandSec-Fetch-Siteare checked when present; absence passes (non-browser clients — Access service tokens, curl — send neither, and browsers attachOriginto every cross-origin POST) → 403.X-EmDash-Request: 1, core's convention) → 403. Ratified decision (2026-07-13, spec §12 updated): this replaces the CSRF token/double-submit wording — the Access assertion is not itself a CSRF defense (the edge injects it from theCF_Authorizationcookie), but header + JSON + origin block every browser forgery vector via CORS preflight.verifyAccessRequest(W9.1, feat(labeler): Cloudflare Access operator authentication (W9.1) #2005) on every request; identity is never cached or read from a session → 401.hasRoleagainst the endpoint's required role → 403. The audit row records the role the actor actually held that satisfied the check (an admin passing a reviewer gate via inheritance is recorded asadmin— it may not be in the reviewers list at all).reason(≤1000 chars) andidempotencyKey(^[A-Za-z0-9._:-]{8,200}$), then the endpoint'sparseBody→ 400 with static messages that never echo request contents.commitMutationbatches a plain audit insert atomically with the effect statements: a duplicate idempotency key aborts the whole batch, so a losing concurrent request can never commit a side effect — idempotent or not. The caught UNIQUE violation (matched against D1's column-qualified message, so an unrelated PK conflict is never swallowed) triggers a read-back: matching fingerprint → the winner's stored result (replay), differing → 409. This deliberately diverges fromservice.ts'sON CONFLICT DO NOTHINGprecedent — that pattern is safe only because issuance effects are keyed-idempotent by construction, and the adversarial pass proved (with a probe that became a permanent regression test) that with opaque guard effects theON CONFLICTform lets a conflicting loser's effect commit before its 409. Replay outcomes carry only the stored result and action id — never the full audit record — so routes physically cannot leak the privatereason. Guard error responses use core's wire shape ({ error: { code, message } }).The audit lands in a new
operator_actionstable (migration 0004): append-only viaBEFORE UPDATE/BEFORE DELETERAISE(ABORT)triggers (theissuance_actionsconvention), indefinite retention (spec §19). It is distinct fromissuance_actions(the signing-layer audit) because operator actions like rerun and pause-issuance never issue a label and can't be represented there; its row id doubles as theoperatorTriggerIdanchor for reruns. Ratified decisions recorded in spec §14.4: the table name, nullablesubject_uri(subject-less admin actions), and the action vocabulary as a typed union in the guard (sole writer) rather than a SQLCHECK.No routes are wired yet — W9.3 mounts
/admin/api/*and W9.4–W9.6 add the endpoints. One routing requirement this hands to W9.3, recorded in spec §12: console API routes must never emit cross-origin CORS allow headers, or the preflight defense collapses.Implemented by an Opus subagent from an Opus-authored, Matt-ratified design, then adversarially reviewed by an independent Opus pass (bypass ordering,
Origin: null, fingerprint canonicalization, idempotency TOCTOU, batch atomicity, test honesty).Stacked on #2005 (merged). Targets
feat/plugin-registry-labelling-service. Related to #1909 and RFC #694.Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain.Admin i18n and changeset are n/a — this touches only
apps/labeler, a private, unpublished Worker app (no admin UI in this PR, not on npm). The migration is forward-only and additive (new table only).AI-generated code disclosure
Screenshots / test output
pnpm --filter @emdash-cms/labeler exec vitest run: 348 pass (21 files) — 43 new W9.2 tests: per-protection negative matrix (content-type variants incl. quoted/wrong charset; mismatchingOrigin,Sec-Fetch-Site: cross-site, literalOrigin: null; missing/wrong CSRF header; missing/invalid token; reviewer vs admin gate with the inheritance case pinned in both the context and the persisted audit row; reason and key format bounds), fingerprint stability/injectivity, replay returning the stored result without re-running the effect, same-key/different-body 409, concurrent non-idempotent effects: exactly one commits in both the same- and different-fingerprint races (fail-without-fix verified by reverting toON CONFLICT), audit immutability (UPDATE/DELETEabort), UNIQUE-violation detection pinned against the real miniflare error, spoofed plaintext identity header → 401tsgo --noEmit) clean; lint: 0 diagnostics inapps/labeler(repo baseline of 19 pre-existingno-redundant-type-constituentsfalse positives in unrelated packages, unchanged)https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
Try this PR
Open a fresh playground →
A full working EmDash site, deployed from this branch. Each visit gets its own session-scoped sandbox: no login needed and no shared state. Try the admin, edit content, hit the public site.
Tracks
feat/labeler-mutation-guard. Updated automatically when the playground redeploys.