Registry Mirror
Skip to content

Conversation

@lakhansamani

@lakhansamani lakhansamani commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #273

Root cause

Calling forgot_password twice for the same account returned a raw duplicate-key database error. internal/service/forgot_password.go calls AddVerificationRequest without deleting the request already pending, and backends did not agree on what that call does:

Backend Before
SQL (all GORM dialects) upsert on (email, identifier) (clause.OnConflict, fixed in #792)
SurrealDB upsert (create, then UPDATE on duplicate)
MongoDB InsertOne against the unique (email, identifier) index, so E11000 duplicate key error went straight to the user
ArangoDB CreateDocument against the unique hash index, so unique constraint violated went straight to the user
Cassandra / DynamoDB / Couchbase plain insert keyed by a fresh id, with no constraint, so a second pending row piled up silently

internal/storage/provider_test.go already listed this as a known parity gap.

Fix

AddVerificationRequest is 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 and created_at are the original request's.

  • MongoDB: FindOneAndUpdate with upsert: true, returning the document after the update. It is atomic under the existing unique index.
  • ArangoDB: AQL UPSERT ... INSERT ... UPDATE ... RETURN NEW with 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.
  • Cassandra / DynamoDB / Couchbase: list the rows for the pair, reuse the first row's id so the write (CQL INSERT, PutItem, Couchbase Upsert) 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.
  • DynamoDB lookup no longer full-scans. Before, GetVerificationRequestByEmail scanned the whole table, and every forgot-password, magic-link and signup request now goes through that lookup. There is a new email GSI on verification_requests (query on email, filter on identifier):
    • New tables get it from ensureTables.
    • createTable is a no-op for an existing table, so the new ensureGSI checks the table with DescribeTable and adds a missing index with UpdateTable. It does not wait for the backfill. It is best-effort: if it fails (for example, no dynamodb:UpdateTable permission) it logs a warning and startup continues.
    • While the index is absent or still backfilling, DynamoDB rejects queries against it with ValidationException. The reader falls back to the old scan in that case, so behaviour stays correct during and without the migration.
    • Other GSIs added to tables.go after a deployment created its tables have the same no-migration gap. This PR does not change that and only migrates this one index.
  • SQL: updated_at is now part of the on-conflict update. The stored row is re-read and returned, because on conflict the row keeps its own id and created_at.
  • SurrealDB: on the duplicate path the updated record is re-read and returned.
  • The Provider interface 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 call AddVerificationRequest without deleting first. One side effect on Mongo and DynamoDB: before, they silently skipped the write when the caller passed a non-empty ID. No caller does that, and they now always write.

Tests

  • internal/storage/provider_test.go testVerificationRequestOperations: the per-backend branching is replaced with one assertion for every backend. A duplicate (email, identifier) add must:

    • succeed,
    • replace token, nonce and redirect URI,
    • return the stored row's id and created_at,
    • make the old token stop resolving (IsNotFound),
    • leave exactly one row for the pair.

    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 with ValidationException (the fallback's trigger), ensureGSI adds the index, and a second ensureGSI call is a no-op.

  • internal/integration_tests/forgot_password_test.go: new subtest should 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 ./... and go vet ./...: pass
  • make test (SQLite): pass
  • make lint: clean (golangci-lint v2.15.0, the version the Makefile pins, plus prettier)
  • Full DB targets: make test-mongodb and make test-arangodb passed on the first commit. make test-couchbase and make test-dynamodb were run on the review-fix code. make test-couchbase passed; its first attempt hit a transient port 8095 already in use and was re-run. The make test-dynamodb run passed every DynamoDB test, including the new TestEnsureGSIOnExistingTable. 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 in make test.
  • Final code, TestStorageProvider + TestNotFound* per backend (TEST_DBS=<db>, one fresh container each): sqlite, mongodb, arangodb, surrealdb, dynamodb, cassandradb and couchbase all pass, and Verification_Request_Operations ran on every one.
  • Not run: ScyllaDB (same provider code as Cassandra) and the other SQL dialects (same GORM code as SQLite).

…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
lakhansamani force-pushed the fix/273-verification-request-upsert branch from 383b4f2 to 0c5d2a2 Compare November 26, 2026 07:06
@lakhansamani
lakhansamani merged commit 6a69251 into main Nov 26, 2026
@lakhansamani
lakhansamani deleted the fix/273-verification-request-upsert branch November 26, 2026 07:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Dont return database errors

1 participant