Repository navigation
fix(api): wrap event registration's user upsert and create in one transaction - #686
sydevs-bot wants to merge 8 commits into
Conversation
…nsaction `registerForEvent` upserted the registrant and created the registration as two independent writes. Anything refusing between them — the registrations write-guard's captcha, its URL scan, the `questions` validation 400 — left an orphan `users` row that no registration referenced. The naive wrap was not available: `upsertUserByEmail` handled a concurrent registration by catching a failed `create` and re-finding the row. Inside a Postgres transaction that recovery cannot work, because the unique violation aborts the transaction and the recovery read fails with "current transaction is aborted" — turning a handled race into a 500 on a live public write path. So the upsert is atomic instead of retrying: `INSERT … ON CONFLICT (email) DO NOTHING RETURNING id` through Drizzle's own typed builder, reached via `payload.db` (approach (c) on the ticket, and no custom SQL — the reviewer asked for a built-in and `onConflictDoNothing` is one). With no failing statement there is nothing to abort, and the race becomes a database guarantee rather than application retry logic. Two consequences the ticket called out, both handled here: - A Drizzle-level write runs no Payload hooks, so the write-guard plugin's `users.create` policy silently stopped applying. `applyWriteGuard` is now exported from the plugin — the whole gate in one function, which `writeGuardBeforeValidate` also calls — and `upsertUserByEmail` invokes it from the same policy map. Not a second copy of the rules. - A Drizzle write does not pick up the caller's transaction on its own. `adapter.sessions[transactionID].db` is the handle that does, mirroring `getTransaction` in `@payloadcms/drizzle`; that package is transitive here, so the one line is inlined with the citation rather than imported. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Gs5urfyVkUqxiyYuTutp5B
The code-review pass found the half of the hook seam the first commit did not restore. `applyWriteGuard` covers content — disposable domains, URLs in free text — and only for a `clients` caller; Payload's own `required` and `email` validation is what refused a blank name or a malformed address from anyone else, and the raw insert skipped it. `event-submissions` is where that bites: `prepareSubmission` forwards `submitterInfo.name` unchecked, so an empty one used to fail with "The following field is invalid: Name" and would now have silently stored a nameless registrant. `registrantSchema` restates the `users` collection's two constrained fields. Restating them is proportionate only because the collection is two fields wide; the docblock says a third belongs there too. Also adds the coverage that pass asked for. The conflict branch of `ON CONFLICT DO NOTHING` needs two live transactions, which no caller's spec can produce, so it gets its own file. The first draft raced two whole calls with `Promise.all` and did NOT reach the branch — it passed with the conflict target deliberately broken. The committed version drives the interleave: A inserts and holds, B reads (missing) and blocks on A's row, A commits, B's insert returns no row and re-reads. Watched failing three ways — a wrong conflict target raises `duplicate key value violates unique constraint "users_email_idx"`, a dropped re-read throws the helper's own error, and a dropped schema check lets both validation cases store a row. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Gs5urfyVkUqxiyYuTutp5B
…te guard The rule doc says the plugin covers every client-originated write, which is what makes "endpoints don't re-implement the guard" safe to rely on. That is now true with one deliberate exception, and an exception nobody wrote down is how the next reader concludes the seam is universal. Also states the part that has no failure mode: a new constrained field on `Users` needs adding to `registrantSchema`, because nothing breaks if you forget. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Gs5urfyVkUqxiyYuTutp5B
|
🚅 Deployed to the SahajCloud-pr-686 environment in sahajcloud
1 service not affected by this PR
|
Both review passes landed on the same latent hazard independently, which is usually the sign it is real. `transactionalDrizzle` mirrored the adapter's `getTransaction`, including its fall back to `adapter.drizzle` when a `transactionID` resolves to no session. That fall back is right for upstream, which uses it for reads after a transaction has ended. It is wrong here: it would issue the registrant insert on the pool instead of the caller's transaction, resurrecting exactly the orphan row this branch removes — silently, and only in the state nobody writes a test for. No call path can reach it today. The throw is what keeps that true. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Gs5urfyVkUqxiyYuTutp5B
|
Marked ready for review by a later run — this PR was left as a draft by the run that built it, which stopped before finishing. Nothing about the code changed; I have pushed no commits.
Flagging it plainly rather than quietly fixing it: that run also posted no journal entry, so between roughly 16:46Z and 17:53Z there is work on #684, #671, SahajAtlasWeb#192 and this PR that today's journal did not record until now. 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
The shape is right and the diff is the size of the problem. #673 asked for one transaction around two writes via approach (c); the diff is 443 lines over 7 files, of which 209 are specs and 29 are docs — the source change is ~205 lines and most of that is docblocks. Nothing here is an abstraction for one caller or a refactor smuggled in beside the fix: applyWriteGuard is extracted because the Drizzle insert cannot reach beforeValidate, and that is the only structural change.
The "prefer built-in over custom SQL" instruction is honoured about as well as it can be. onConflictDoNothing through payload.db.drizzle/payload.db.tables is the documented escape hatch and there is no raw SQL. The one place it reaches past a public API is adapter.sessions[transactionID].db — an internal of a transitive package, inlined rather than imported — and that is load-bearing: get it wrong and the insert silently lands outside the transaction, which is the bug this PR exists to fix. It is pinned, though, not hoped: event-registration.int.spec.ts's "creates no REGISTRANT either" fails the moment the insert stops joining the transaction, so a Payload upgrade that moves sessions goes red rather than quiet. I checked the security enumeration in the PR body independently and it holds — users picks up four beforeOperation hooks from usagePlugin, and three are no-ops on a create (usageTrackingBeforeOperationHook returns unless operation === 'read', rateLimitHook is an edge no-op, validateClientQueryParamsHook is read-shaped), leaving validateClientOriginHook, which all three callers do run upstream.
What I would want settled before merge is the one systemic consequence, not the mechanism. The transaction now spans a Turnstile siteverify call bounded at 10s, on a public write path, against a pool sized at 20/replica by a formula in docs/architecture.md that assumes short queries. That is a new class of connection-hold and the sizing note does not mention it.
Findings
should-fix
registerForEvent.ts:197— the transaction can hold a pooled connection and theusersrow lock for up to 10s (verifyTurnstile.ts:23);docs/architecture.md's pool section is not updated, and the naive "verify beforeinitTransaction" fix is blocked byapplyWriteGuardhonouring the same globalskipWriteGuardflag.
consider
upsertUserByEmail.ts:26— theregistrantSchemaduplication you flagged is a symptom ofsubmitterInfobeing an unvalidatedjsonfield on a client-writable collection. Payload'sjsonSchemacloses it at the seam and would let the restatement go; follow-up ticket, not this PR.upsertUserByEmail.ts:137— "same gate, not a second copy" is true of the logic, not the policy map: the hook takes the configuredpolicies, this call site hard-codesDEFAULT_WRITE_GUARD_POLICIES. Nothing passes the option — delete it.tests/int/upsert-user-by-email.int.spec.ts:75— one ordering (B'sSELECTlanding after A's commit) still makes the conflict case vacuous, and the int lane runs 4 parallel forks against one Postgres.writeGuardPlugin.ts:101— the exception is documented here and indocs/rules/api-clients.md, butwriteGuardPlugin.ts:24andpolicies.ts:36-38still state the rule as absolute.
No blockers. Nothing in the four consider items is a correctness defect; the should-fix is a sizing/documentation gap rather than a broken path.
What was checked
Ticket and its thread. #673 (body, acceptance criteria, "first thing to check"), all three comments — including the 2 Sep steer approving (c) with "first search and ensure that there is no built-in PayloadCMS method … always prefer built-in and pre-existing methods", which is the bar the mechanism was measured against above.
Diff. git fetch + git diff origin/main...origin/claude/fix-registration-transaction — 7 files, 5 commits. Read whole, not as hunks.
Surrounding source, read in full: src/lib/users/upsertUserByEmail.ts, src/collections/Events/endpoints/registerForEvent.ts (all 300 lines, including the post-commit best-effort sends and the outer catch), src/plugins/writeGuard/writeGuardPlugin.ts, src/plugins/writeGuard/policies.ts, src/collections/Users/Users.ts, src/lib/turnstile/verifyTurnstile.ts, src/lib/antiSpam/antiSpamGuard.ts (verifyTurnstileOrFail), src/plugins/usage/usagePlugin.ts + hooks.ts (asTrustedReq, usageTrackingBeforeOperationHook), src/collections/Registrations/hooks/syncFullness.ts, src/collections/EventSubmissions/hooks/prepareSubmission.ts, src/collections/EventSubmissions/EventSubmissions.ts (the submitterInfo field), src/collections/UserMessages/hooks/prepareUserMessage.ts.
The three consumers of the changed helper were followed, since its contract changed: registerForEvent (bounded by bodySchema), prepareUserMessage (name derived from the address), prepareSubmission (unbounded json — the gap behind finding 2).
Claims verified rather than taken:
ON CONFLICT (email)has an index to infer —CREATE UNIQUE INDEX "users_email_idx" ON "users" USING btree ("email"),src/migrations/20260608_174939.ts:347.- The raw insert cannot violate NOT NULL on the timestamps —
created_at/updated_atcarryDEFAULT now()in the same DDL (lines 252-260). - One adapter everywhere, so no SQLite path where
adapter.sessions/tablesdiffer —postgresAdapterin bothpayload.config.ts:160andtests/utils/testHelpers.ts:107. - Transactions are actually on (no
transactionOptions: false), which the whole change depends on —payload.config.ts:160-180. asTrustedReqspreadsreq, sotransactionIDsurvives into the helper's reads —usage/hooks.ts:26-28.- Turnstile is not memoized per request (
antiSpamGuard.ts:57), which is what rules out the otherwise-obvious "retry the transaction on a unique violation" alternative to this whole design — a retry would re-verify a single-use token and refuse every real registration. That is the strongest argument for the Drizzle route and it is worth stating, because the PR body does not make it. - Pool sizing and the assumption behind it —
src/lib/env/server.ts:59,docs/architecture.md§"Database connection pool & depth caps". - Int-lane parallelism behind finding 4 —
vitest.config.mts(intMaxForks,min(cpuCount, 4)in CI, shared Postgres).
Not re-run: the author-side /code-review and /security-review passes documented in the PR body. CI (Lint, Test & Smoke) is green on 4f34a50.
Reviewer profile: workflow/skills/adversarial-review/reviewer-profile.md, read and applied — no style, naming or test-volume findings raised, and the two payload.db as unknown as PostgresAdapter casts were left alone as author-side territory.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
…s race Addresses the five findings from the adversarial review on #686. **The pool finding's premise was wrong, and the corrected version is what went into `docs/architecture.md`.** The review said this PR introduces the first public write path that can hold a connection for seconds. It does not: `payload.create` opens the operation's transaction *before* it runs collection hooks (`payload/dist/collections/operations/create.js` — `initTransaction` at the top, `beforeValidate` inside, `commitTransaction` at the end), and the write guard's Turnstile check runs in `beforeValidate`. So every guarded create has held a pooled connection across siteverify since #629. What #673 genuinely adds is the *row lock*: the registrant row is now inserted before the captcha is verified, in the same transaction, so it is locked for as long as siteverify takes. That is what the pool section now records, with the 10s bound named and `connectionTimeoutMillis` compared against it. The review's (b) — tighten the timeout on this path — is not taken: with the premise corrected there is no path-specific exposure to tighten, and lowering `VERIFY_TIMEOUT_MS` changes the captcha gate for every caller, which is its own PR. **The `policies` option is deleted rather than wired up.** The review is right that "one gate, two callers" was true of the logic and not of the map: the hook took whatever was injected, the new call site hard-coded `DEFAULT_WRITE_GUARD_POLICIES`. Nothing ever passed the option and `write-guard-policies.spec.ts` pins the map directly, so removing the knob makes the map genuinely single-source instead of adding a second wire. **The race case no longer hopes B blocked; it asserts it.** A fixed sleep only guarantees A commits late — if B's SELECT is starved past that commit it takes the plain `findByEmail` hit, never inserts, and the case stays green with `onConflictDoNothing`'s target broken. `waitForBlockedInsert` polls `pg_stat_activity` for a backend waiting on a lock against this suite's own schema-qualified `users` table, and throws if none appears. Watched failing at the site that causes it — committing A before B reads gives "B never blocked on A's uncommitted row, so the conflict branch was not exercised" in 3s. **Two docblocks that still stated the guard's rule as absolute** now carry the exception, since they are what a reader auditing the public write surface hits first. **`registrantSchema` stays, and now points at #687** — the hole is `submitterInfo` being a schemaless `json` field on a client-writable collection, which is where Payload's own `jsonSchema` closes it and lets this restatement go. Filed rather than folded in: different collection. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01TyMdTC6dqhJn4dSHq2Z2ug
There was a problem hiding this comment.
Could this file be converted into a more generic "update by field" helper?
There was a problem hiding this comment.
I'd rather not, and the reason is that almost nothing in the file is about "a field" — it's about users specifically. Happy to be overruled, but here is what generalising would actually cost.
First a naming correction that matters to the answer: this never updates. It is find-or-create — on a hit it returns the existing id untouched, and ON CONFLICT DO NOTHING means the create path writes nothing when it loses a race. So the generic shape would be findOrCreateByUniqueField, not "update by field".
Five of the six things it does are users-specific, and each would become a parameter:
| In the file | What a generic version needs from the caller |
|---|---|
onConflictDoNothing({ target: users.email }) |
the conflict-target column — and a promise that a unique index covers it |
registrantSchema (Users' two fields, restated) |
a zod schema per collection |
applyWriteGuard(… DEFAULT_WRITE_GUARD_POLICIES.users) |
the policy key |
email.toLowerCase() |
a normalizer |
overrideAccess: true on both reads |
a flag, because users is admin-only and most collections are not |
The conflict target is the one I would genuinely fear. ON CONFLICT (col) needs a matching unique index or Postgres raises there is no unique or exclusion constraint matching the ON CONFLICT specification — at runtime, on the first write, not at compile time. Today that index is pinned (users_email_idx, src/migrations/20260608_174939.ts:347) and the target is a literal three lines from it. Behind a parameter it becomes a caller obligation that the type system cannot state, on the atomic-insert path this PR exists to make safe.
And the demand is one shape, three times. All three callers — registerForEvent.ts:200, prepareSubmission.ts:107, prepareUserMessage.ts:63 — do the identical thing: find-or-create a registrant by email. There is no second collection asking for this, and the two other things a client can cause to be written (event-submissions, user-messages) are ordinary payload.creates that want hooks and validation to run, which is exactly what this helper gives up. So a generic version would be a seven-parameter abstraction serving one concrete use, and its first real second caller would almost certainly want DO UPDATE rather than DO NOTHING — a different statement, not a different argument.
What I do think is worth doing, and it points the other way: the file is 60% restatement of things that exist elsewhere because the Drizzle insert goes around them — registrantSchema restates Users' fields, the explicit applyWriteGuard restates the collection seam. #687 deletes the first of those. The shrinking is in removing the restatements, not in widening the signature.
Say the word if you'd still like it generic and I'll do it — I'd want the second collection in hand first, so the parameters are chosen against two real callers instead of one imagined one.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
There was a problem hiding this comment.
Investigate this plugin but don't take any action yet, this might be a follow-up ticket. What is the purpose of this plugin? It seems excessive and it seems to duplicate the domain of the access plugin. We need a multiple simpler and easy to maintain system, currently this seems very cumbersome and error-prone.
There was a problem hiding this comment.
Investigated, nothing changed. Short version: the two plugins answer different questions and I would not merge them — but your instinct is right about one thing, and it is a real (currently harmless) divergence I can show you.
Purpose. accessPlugin decides may this caller write here at all — roles, projects, locales, region subtree, returning true/false/a Where. writeGuard decides is this content abusive, for writes access control has already allowed, and only when req.user.collection === 'clients'. Captcha header, URLs in free text, disposable email domains. A manager posting a URL is fine; an anonymous API client doing it is the spam we were getting.
They cannot practically be one thing, and the reason is mechanical rather than aesthetic:
- Payload's
accessfunctions are per-operation authorization. They do not reliably receive the documentdata(oncreatethey get none), so a content scan cannot live there. - The captcha check is an outbound network call to Cloudflare siteverify. Putting a 10-second-bounded HTTP request inside an access function would run it on every access evaluation, including the ones Payload calls speculatively for the admin UI.
beforeValidateis the only seam that sees the merged data before field validation, which is where a content check has to be to return a 400 rather than a 500.
On "excessive" — the volume does not support it. The whole plugin is 285 lines across three files, of which 116 are comments; the actual mechanism is valueAtPath, stringLeaves, runPolicy, applyWriteGuard and 20 lines of hook wiring. src/plugins/access/ is 2,623 lines. The checks themselves live in src/lib/antiSpam/antiSpamGuard.ts (158 lines) and are shared, not duplicated.
Where you are right, and it is worth a ticket
The duplication is not the mechanism, it is the inventory — and that half genuinely is error-prone.
DEFAULT_WRITE_GUARD_POLICIES' docblock asserts "This is the whole public write surface". That is a claim about what accessPlugin grants, written down inside the anti-spam plugin, and nothing checks it. Two files have to agree about which (collection, operation) pairs a client can write, and only one of them is tested.
They already disagree. accessConfigs.ts:125-131 grants a clients caller update on registrations — the confirm/deny vote, scoped to the row whose uuid the caller proves it holds. DEFAULT_WRITE_GUARD_POLICIES.registrations declares create only. So that update runs no write-guard checks at all.
It is harmless today, and only for a reason living in a third file: restrictClientRegistrationUpdate (Registrations/hooks/eventFeedback.ts:32) reverts every field except eventFeedback to its stored value, so there is no free text or email left to scan. Three mechanisms, three files, and the safety is an emergent property of all three. Widen that whitelist to include, say, a comment box and nothing anywhere goes red.
So my recommendation is the opposite of merging them: make the inventory checkable. A unit spec that derives from the access config the set of (collection, operation) pairs a clients user can write, and asserts it equals DEFAULT_WRITE_GUARD_POLICIES' keys plus an explicit waiver list carrying a reason per entry. registrations.update would be the first waiver, citing the field whitelist. That turns the docblock's claim into a gate, costs one spec, and removes the class of bug rather than one instance — where merging the plugins would mean putting a network call inside authorization.
Not filed, per your "don't take any action yet." Say the word and I'll raise it — my estimate is Effort: Easy, Priority: Medium, one spec file and a waiver list, no production change.
What was read
src/plugins/writeGuard/{index,policies,writeGuardPlugin}.ts whole; src/lib/antiSpam/antiSpamGuard.ts; src/plugins/access/accessPlugin.ts, accessConfigs.ts (the operation closure at 85-140), index.ts, permissions.ts and types.ts; src/collections/Registrations/hooks/eventFeedback.ts. Client write grants traced by grepping clients across src/plugins/access/. Line counts from wc -l and a comment-line grep, quoted above.
Not measured: I did not run the suite for this — nothing was changed. The registrations.update divergence is read off the two files, not reproduced against a live request; reproducing it would need a client credential and a registration uuid, and it would demonstrate only that no check runs, which the absent update key already states.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
|
Both of your comments are answered on their threads; no code changed, because neither asked for any. I've left both unresolved — they're your calls, not mine to close.
🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
Closed in favour of a complete overhaul of the registrations code as detailed in #695 |
) Rewrites every in-scope prose file (67 of 69 flagged by the audit) into strict Simplified Technical English and retires D1/Cloudflare Workers-era debris three months after the Postgres/Railway migration. Tracked *.md (excluding CLAUDE.md symlinks and the vendored .agents/skills/payload/ skill, left untouched pending ownership confirmation) drops from 770,090 to 600,797 chars (22%). The five hot-path files auto-imported every session (AGENTS.md, docs/architecture.md, docs/environment.md, docs/code-style.md, .claude/workflow.json) drop from 84,492 to 36,397 chars (57%). Deleted (dead, zero referrers, grepped clean): seed-issues-report.md, src/migrations/README.md (its one fact folded into src/migrations/AGENTS.md). Merged: DEPLOYMENT.md + RAILWAY_RUNBOOK.md split by lifecycle (how it runs today vs. provision-from-scratch/disaster-recovery), resolving their D1-decommission contradiction — PR #468 (merged 2026-06-08) confirms the Worker is gone, so the stale "Remaining (gated)" TODOs are removed, not reworded. Legacy debris fixed (D1/SQLite/Cloudflare-Workers-as-current retired): migration-reviewer.md's whole persona rewritten for Postgres/Drizzle, seeds/wemeditate/AGENTS.md's Dual-Database table corrected to Postgres, src/globals/AGENTS.md's json_array() rationale corrected to Postgres's real FUNC_MAX_ARGS=100 limit, docs/mcp-setup.md's cloudflare-docs row drops Workers/D1. grep for D1|SQLite|Cloudflare Workers across .claude/agents/, seeds/wemeditate/, src/globals/, docs/mcp-setup.md is clean. README.md's stale `cd sy-devs-cms` corrected to `cd SahajCloud`. Mandatory AGENTS.md fixes applied: dropped the nonexistent `pnpm test:e2e`, replaced the broken dev-server.sh path with the `/workflow:dev-server` skill, fixed the seeds/atlas/MIGRATION_PLAN.md:103 anchor (now resolves to `AGENTS.md#website-selection-rules-584`), collapsed duplicate PR-workflow/test-tier prose into single pointers to testing-reqs.md and the finalize-pr skill. Traps preserved (compressed, never deleted): the conflicted-PR "zero CI" diagnostic with its docs/why.md anchor and #632/#653 numbers; the Cache Rule authorization-header predicate and root-endpoint fix; DB_QUERY_LOGGING and TURNSTILE_SECRET_KEY footguns; storage.md's preview/prod asset-isolation risk; the payload-cli silent-exit/hang ladder; the migration snapshot out-of-order duplicate-re-emission trap; access.md's per-locale-roles gotcha (#665); endpoints.md's root-endpoint hook gap; email.md's two- token-URL-shapes bug; seeds/atlas/AGENTS.md's silent-rollback-on-trashed- relation trap; the never-name-a-global-field-locales rule. The 2026-08-27 dated Admin Access exception is kept (still current). Comment sweep: rewrote comments to STE in every file the audit flagged as touched (route.ts's mandatory dead-comment deletions, r2NativeAdapter.ts, Icon.tsx, scalarPlugin.ts, env/server.ts, localizedRolesAuth.ts, plus the full tests/seeds/scripts/.claude/root-config/.github sweep — 227 files total). Verified comment-only: every changed line in every .ts/.tsx/.mjs/ .cjs/.sh/.py file has an identical code portion before its comment marker; zero functional changes. Deleted a dead `sharp` import and several doc- duplicating/obvious comments (e.g. vitest.setup.ts's two narrate-the- obvious lines). Verification run as finisher: pnpm lint, typecheck, typecheck:tests, and the full unit lane (1564 tests) all pass, plus targeted integration specs for every touched collection/access path (events, regions, role-based- access — 79 tests, live Postgres). ste-lint.py run on all 40 changed .md files: hard violations cut from 169 to 118, concentrated in five already- dense reference docs (admin-ui/api-clients/email/endpoints/openapi/ storage.md) where the prior compression pass already prioritized fidelity over the linter's raw sentence-length cap; remaining flags are verified domain terms (Railway's "Health Check", Zod's "Validate", literal HTTP methods GET/DELETE, SQL "cascade delete", TS "type erasure") or residue in those five files. rule-delta.mjs vs main on AGENTS.md/docs/rules/*.md/ migration-reviewer.md: 3 directives flagged REMOVED, all three verified as de-bolded (not deleted) — "GET /api/events/geojson always excluded, no opt-out" (api-clients.md) and the two CPU parallel-test-run rules (testing-reqs.md) all still present as plain bullets/cells, content identical. 1 flagged ADDED is the same pass-by-reference comment rule gaining full-sentence bold (previously invisible to the tool since only "Do not" was bold). Sequencing: PRs #692 (UNKNOWN), #686 (BLOCKED, not CONFLICTING), #691 (CLEAN) show no current CONFLICTING/DIRTY state, so this PR is not blocked today, though #692/#691 touch overlapping files and should land or be watched. securityReview trigger paths (access/, storage/, api routes, webhook scripts) all confirmed comment-only. Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Summary
usersupsert and theregistrationscreate are one transaction, so a refused captcha, a URL in the name or thequestionsvalidation 400 all leave nothing.INSERT … ON CONFLICT (email) DO NOTHING RETURNING id. The oldcreate-then-catch race handler could not survive being wrapped: a unique violation aborts a Postgres transaction, so its recovery read would have 500'd the registration path.onConflictDoNothingthroughpayload.db— the built-in you asked me to look for before writing SQL.Changes
src/lib/users/upsertUserByEmail.ts— the atomic insert, plus the two halves of the Payload seam it goes around:applyWriteGuardfor the anti-spam policy,registrantSchemafor the field constraints.src/plugins/writeGuard/writeGuardPlugin.ts—applyWriteGuardis the whole gate in one function;writeGuardBeforeValidateis now a wrapper over it, so there is one definition and two callers rather than two copies.src/collections/Events/endpoints/registerForEvent.ts—initTransaction/commitTransaction/killTransactionaround the pair, opened after the client's own reads.docs/architecture.md— the connection-pool section, which is where the cost of holding a transaction across a network call belongs.tests/int/upsert-user-by-email.int.spec.ts— new; the conflict branch and the field validation, neither reachable from a caller's spec.What changed in review
The adversarial pass left five findings; all five are answered and their threads are resolved. Nothing is outstanding, and there is no question waiting on you.
registrantSchemaduplicatesUsers' own constraintsapplyWriteGuard's policy map reaches its two callers differentlypoliciesoption is deletedThe pool finding's premise was wrong, and correcting it is what went into the docs. This is not the first public write path that holds a pooled connection across a Turnstile call:
payload.createopens the operation's transaction before it runs collection hooks (payload/dist/collections/operations/create.js—initTransactionat 26, thebeforeValidateloop at 108,commitTransactionat 324), and the write guard's captcha check is abeforeValidatehook. So everyevent-submissions/user-messages/registrationscreate has done this since #629.What #673 genuinely adds is the row lock — the registrant row is inserted before the captcha is verified, so it is locked for up to
VERIFY_TIMEOUT_MS(10s). That is whatdocs/architecture.mdnow records, alongside the comparison againstconnectionTimeoutMillisand an instruction to re-measure before raising registration throughput. The review's second half — tighten the timeout on this path — is deliberately not taken: with the premise corrected there is no path-specific exposure, and loweringVERIFY_TIMEOUT_MSchanges the captcha gate for every caller. Say the word and I'll file it, but I'd want real siteverify latency measured first.Preview
Railway builds the per-PR preview on push. Nothing here is reachable from a URL — the change is a write path behind a client API key — so there is no route to deep-link. The observable surface is
POST /api/events/{id}/register.Test results
d363013: ✓pnpm lint, ✓pnpm typecheck, ✓pnpm typecheck:tests, ✓pnpm test:unit— 120 files / 1553 specsevent-registration,upsert-user-by-email,user-messages,event-submissions— the last two being the helper's other callers, which is the cross-check that matteredManual verification
userstable gains nothing.Every new assertion was watched FAILING — including the race guard added in review
Per
docs/rules/testing-reqs.md, at the site that would really cause it:initTransaction/commit/killremovedcreates no REGISTRANT eitherandleaves no registrant … when the questions payload is refused—expected 1 to be +0. The second fires with no captcha involved, which is what says the orphan was never captcha-specificapplyWriteGuardcall droppedexpected 201 to be 400, i.e. a disposable address would have succeededonConflictDoNothingtarget pointed atusers.idduplicate key value violates unique constraint "users_email_idx", which is the abort this PR exists to avoidracedre-read droppedregistrantSchemacheck droppedupsertUserByEmail race: B never blocked on A's uncommitted row, so the conflict branch was not exercised, in 3sTwo of these were vacuous first, which is the warning worth carrying.
The conflict test began as
Promise.allover two wholeupsertUserByEmailcalls — and it passed with the conflict target deliberately broken, because A finished outright and B took the ordinaryfindByEmailhit. Racing two calls does not produce the interleave.Driving it with a fixed 250ms sleep fixed the common case and left one ordering open, which the review found: a sleep only guarantees A commits late, and if B's
SELECTis starved past that commit B never inserts at all.waitForBlockedInsertcloses it by asking Postgres — it pollspg_stat_activityfor a backend waiting on a lock whose statement names this suite's schema-qualifieduserstable, and throws if none appears. Suites share one database and are isolated by schema, so the qualifier is what stops a sibling fork satisfying it.adapter.poolis thepgPool andpgis a direct dependency, so this reaches for no transitive package.The security sweep, and the premise the ticket said to verify first
The security pass found nothing exploitable, and its useful output is the enumeration rather than the verdict: it went through every mechanism attached to a collection write and asked which the raw insert lost.
Usershas no hooks, no versions, no drafts, no localized fields;accessPluginwas already bypassed by the oldoverrideAccess: true;cachePluginattaches nothing tousers. The one genuine loss isvalidateClientOriginHook, and it is unreachable — all three callers run it upstream on the same clientreqbefore the insert. It also checked thatkillTransactioncannot un-consume a Turnstile token, since consumption is recorded at Cloudflare rather than locally.Both passes independently flagged the same latent hazard, which is why it is fixed rather than noted:
transactionalDrizzlemirrored the adapter'sgetTransactionincluding its fall back toadapter.drizzlewhen atransactionIDresolves to no session. Upstream uses that for reads after a transaction ends; here it would have issued the insert on the pool and resurrected the orphan row. It throws now."Whether a Drizzle-level write joins the caller's transaction" — it does, but only through the session map, and that is not automatic.
adapter.sessions[transactionID].dbis thetxobject Drizzle hands the adapter insidebeginTransaction;payload.db.drizzleis the pool and would have written outside the transaction.@payloadcms/drizzlehas its owngetTransactionhelper doing this, but that package is transitive here, so the logic is inlined with the citation rather than imported.The isolation the shape depends on is the default. No
transactionOptionsare configured, so READ COMMITTED:ON CONFLICT DO NOTHINGwaits on a concurrent uncommitted insert, returns zero rows once that commits, and the followingSELECTin the same transaction sees the row.The old inverted assertion, and the docs changes
event-registration.int.spec.tscarried a case pinning the buggy behaviour —still creates the registrant row — the two writes share no transaction— with a comment saying to flip it when a transaction landed. It is flipped rather than deleted.docs/rules/api-clients.mdsaid the write-guard plugin covers every client-originated write, which is what makes "endpoints don't re-implement the guard" safe to rely on. That now has one exception, so it is written down — along with the part that has no failure mode: a new constrained field onUsersneeds adding toregistrantSchema, and nothing breaks if you forget. The two in-source docblocks that stated the same rule absolutely (writeGuardPlugin.ts's header,policies.ts's map comment) now carry it too, since those are what a reader auditing the public write surface hits first.Closes #673
🤖 Written by the sydevs autonomous loop — see what this is
🤖 Generated with Claude Code
https://claude.ai/code/session_01TyMdTC6dqhJn4dSHq2Z2ug