Skip to content

feat(labeler): mutation guard and operator action audit (W9.2) - #2008

Merged
ascorbic merged 2 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-mutation-guard
Jul 13, 2026
Merged

ascorbic merged 2 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-mutation-guard

Conversation

@ascorbic

@ascorbic ascorbic commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

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:

  1. JSON content type — media type must be application/json (optional utf-8 charset only) → 415. Also a CSRF layer: HTML forms can't produce it.
  2. Same-origin — Origin and Sec-Fetch-Site are checked when present; absence passes (non-browser clients — Access service tokens, curl — send neither, and browsers attach Origin to every cross-origin POST) → 403.
  3. Required custom header (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 the CF_Authorization cookie), but header + JSON + origin block every browser forgery vector via CORS preflight.
  4. Freshly verified Access identity — 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.
  5. Role check — hasRole against 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 as admin — it may not be in the reviewers list at all).
  6. Body validation — required trimmed reason (≤1000 chars) and idempotencyKey (^[A-Za-z0-9._:-]{8,200}$), then the endpoint's parseBody → 400 with static messages that never echo request contents.
  7. Idempotency — globally unique key with a SHA-256 request fingerprint (canonical JSON, key excluded): replay with an identical fingerprint returns the stored result without re-running the effect; a different fingerprint → 409.

commitMutation batches 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 from service.ts's ON CONFLICT DO NOTHING precedent — 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 the ON CONFLICT form 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 private reason. Guard error responses use core's wire shape ({ error: { code, message } }).

The audit lands in a new operator_actions table (migration 0004): append-only via BEFORE UPDATE/BEFORE DELETE RAISE(ABORT) triggers (the issuance_actions convention), indefinite retention (spec §19). It is distinct from issuance_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 the operatorTriggerId anchor for reruns. Ratified decisions recorded in spec §14.4: the table name, nullable subject_uri (subject-less admin actions), and the action vocabulary as a typed union in the guard (sole writer) rather than a SQL CHECK.

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

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes
  • pnpm test passes (or targeted tests for my change)
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation (if applicable). Do not include messages.po changes except in translation PRs — a workflow extracts catalogs on merge to main.
  • I have added a changeset (if this PR changes a published package)
  • New features link to an approved Discussion: RFC RFC: Decentralized Plugin Registry #694

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

  • This PR includes AI-generated code — model/tool: Claude Code with Claude Fable 5 (coordination), Opus 4.8 subagents (design, implementation, and adversarial review)

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; mismatching Origin, Sec-Fetch-Site: cross-site, literal Origin: 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 to ON CONFLICT), audit immutability (UPDATE/DELETE abort), UNIQUE-violation detection pinned against the real miniflare error, spoofed plaintext identity header → 401
  • Typecheck (tsgo --noEmit) clean; lint: 0 diagnostics in apps/labeler (repo baseline of 19 pre-existing no-redundant-type-constituents false 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.

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
@changeset-bot

changeset-bot Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: c955172

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions

Copy link
Copy Markdown
Contributor

Scope check

This 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.

@github-actions github-actions Bot added review/needs-review No maintainer or bot review yet cla: signed labels Jul 13, 2026
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-cache c955172 Jul 13 2026, 09:27 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-do c955172 Jul 13 2026, 09:26 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-playground c955172 Jul 13 2026, 09:26 AM

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. commitMutation returns the current request's result when the stored result is NULL, instead of returning the stored result. If the winner committed with result = undefined, JSON.stringify(undefined) is undefined, so D1 stores NULL. A losing concurrent/replayed request with the same fingerprint reaches the stored.resultJson === null shortcut and returns its own result rather than undefined. This breaks the documented replay contract.

  2. assertJsonContentType accepts parameters other than charset. The PR description ratifies "media type must be application/json (optional utf-8 charset only)". The implementation silently skips non-charset parameters, so application/json; boundary=foo is 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.

Comment thread apps/labeler/src/mutation-guard.ts Outdated
if (!stored) throw error;
if (stored.requestFingerprint !== ctx.fingerprint)
throw new MutationGuardError("IDEMPOTENCY_KEY_CONFLICT");
if (stored.resultJson === null) return result;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Suggested change
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).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +252 to +266
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");
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Suggested change
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");
}
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Jul 13, 2026
…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
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/awaiting-author Reviewed; waiting on the author to respond labels Jul 13, 2026
@ascorbic ascorbic added bot:review Trigger an emdashbot code review on this PR and removed bot:review Trigger an emdashbot code review on this PR labels Jul 13, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of PR #2008. Both of my prior findings have been fixed in this revision.

  1. Stored undefined result no longer leaks the caller's own result. In the guard's replay path (apps/labeler/src/mutation-guard.ts:172) and in commitMutation's lost-key race path (apps/labeler/src/mutation-guard.ts:249-250), the code now returns undefined when resultJson is SQL NULL, and JSON.parse(...) otherwise. This makes replay and concurrent-race losers observably match the winner's stored response.

  2. Content-Type parameter enforcement now matches the ratified spec. assertJsonContentType rejects any parameter other than a single charset=utf-8 (case-insensitive, optionally quoted), and rejects repeated or malformed parameters (apps/labeler/src/mutation-guard.ts:266 onward). 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.

@github-actions github-actions Bot added review/approved Approved; no new commits since and removed review/needs-rereview New commits since the last review labels Jul 13, 2026
@ascorbic
ascorbic merged commit 6474590 into feat/plugin-registry-labelling-service Jul 13, 2026
18 checks passed
@ascorbic
ascorbic deleted the feat/labeler-mutation-guard branch July 13, 2026 10:40
@ascorbic ascorbic mentioned this pull request Jul 14, 2026
60 of 81 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:review Trigger an emdashbot code review on this PR cla: signed review/approved Approved; no new commits since size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant