Conversation
…fier) on every backend Requesting forgot password twice returned a raw duplicate-key database error on MongoDB and ArangoDB (issue #273): forgot_password calls AddVerificationRequest without deleting the pending request, and those backends did a plain insert against a unique (email, identifier) index. Cassandra, DynamoDB and Couchbase had no such constraint and silently accumulated a second pending row instead. SQL and SurrealDB already upserted. MongoDB now uses FindOneAndUpdate with upsert, ArangoDB an AQL UPSERT, and Cassandra/DynamoDB/Couchbase reuse the pending row's id so the write overwrites it in place. The storage parity test now requires upsert semantics on every backend. Fixes #273
- dynamodb: add an email GSI on verification_requests and query it instead of full-table scanning on every request; ensureGSI adds it to existing tables (best effort), and reads fall back to a scan while the index is absent or backfilling - sql: include updated_at in the on-conflict update and return the stored row; surrealdb returns the stored row on the duplicate path - cassandra/dynamodb/couchbase: delete leftover duplicate rows for the pair written by older versions - arangodb: retry once on unique-constraint violation from a concurrent first request - storage test asserts the returned id/created_at are the stored row's
lakhansamani
force-pushed
the
fix/273-verification-request-upsert
branch
from
November 26, 2026 07:06
383b4f2 to
0c5d2a2
Compare
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #273
Root cause
Calling
forgot_passwordtwice for the same account returned a raw duplicate-key database error.internal/service/forgot_password.gocallsAddVerificationRequestwithout deleting the request already pending, and backends did not agree on what that call does:(email, identifier)(clause.OnConflict, fixed in #792)InsertOneagainst the unique(email, identifier)index, so E11000 duplicate key error went straight to the userCreateDocumentagainst the unique hash index, so unique constraint violated went straight to the userinternal/storage/provider_test.goalready listed this as a known parity gap.Fix
AddVerificationRequestis now an upsert on(email, identifier)on every backend. A second call replaces the pending request's token, expiry, nonce and redirect URI in place, keeps one row, and returns the stored row: its id andcreated_atare the original request's.FindOneAndUpdatewithupsert: true, returning the document after the update. It is atomic under the existing unique index.UPSERT ... INSERT ... UPDATE ... RETURN NEWwith all values as bind vars. UPSERT's lookup and insert are not atomic, so a concurrent first request that loses to the unique index (error 1210) is retried once and takes the UPDATE branch.INSERT,PutItem, CouchbaseUpsert) overwrites it in place, then delete any other rows for the pair. Older versions inserted one row per request, so existing data can hold several. These tables have no unique constraint on the pair, so two concurrent first requests can still race into two rows. The next request for that pair cleans that up.GetVerificationRequestByEmailscanned the whole table, and every forgot-password, magic-link and signup request now goes through that lookup. There is a newemailGSI onverification_requests(query onemail, filter onidentifier):ensureTables.createTableis a no-op for an existing table, so the newensureGSIchecks the table withDescribeTableand adds a missing index withUpdateTable. It does not wait for the backfill. It is best-effort: if it fails (for example, nodynamodb:UpdateTablepermission) it logs a warning and startup continues.ValidationException. The reader falls back to the old scan in that case, so behaviour stays correct during and without the migration.tables.goafter a deployment created its tables have the same no-migration gap. This PR does not change that and only migrates this one index.updated_atis now part of the on-conflict update. The stored row is re-read and returned, because on conflict the row keeps its own id andcreated_at.Providerinterface doc now states the upsert contract and what is returned.I fixed this in the storage layer, not by adding a delete in
forgot_password, so every caller gets the same behaviour: signup, magic link, invite, update-profile and admin flows also callAddVerificationRequestwithout deleting first. One side effect on Mongo and DynamoDB: before, they silently skipped the write when the caller passed a non-emptyID. No caller does that, and they now always write.Tests
internal/storage/provider_test.gotestVerificationRequestOperations: the per-backend branching is replaced with one assertion for every backend. A duplicate(email, identifier)add must:created_at,IsNotFound),Before the fix this failed on MongoDB (
E11000 duplicate key error ... email_1_identifier_1) and ArangoDB (unique constraint violated - in index ... over 'email, identifier').internal/storage/db/dynamodb/tables_gsi_test.go(new, live, skipped when DynamoDB Local is not on :8000) covers the upgrade path. On a table created without the index, a query against it fails withValidationException(the fallback's trigger),ensureGSIadds the index, and a secondensureGSIcall is a no-op.internal/integration_tests/forgot_password_test.go: new subtestshould allow requesting forgot password twice. It runs on SQLite only, like all integration tests, so it is a regression guard and was not the failing reproduction.The cleanup of leftover rows from older versions has no automated test, because the public API can no longer create duplicate rows.
Verification (run locally on this branch)
go build ./...andgo vet ./...: passmake test(SQLite): passmake lint: clean (golangci-lint v2.15.0, the version the Makefile pins, plus prettier)make test-mongodbandmake test-arangodbpassed on the first commit.make test-couchbaseandmake test-dynamodbwere run on the review-fix code.make test-couchbasepassed; its first attempt hit a transientport 8095 already in useand was re-run. Themake test-dynamodbrun passed every DynamoDB test, including the newTestEnsureGSIOnExistingTable. Its only failure was a static Cassandra check,TestEveryTableUsesOneTimestampDomain, which flagged a variable table name in the new Cassandra code. I fixed that, and the check now passes inmake test.TestStorageProvider+TestNotFound*per backend (TEST_DBS=<db>, one fresh container each): sqlite, mongodb, arangodb, surrealdb, dynamodb, cassandradb and couchbase all pass, andVerification_Request_Operationsran on every one.