From 51e28db1770b08487b3052836b370c955eb42ed2 Mon Sep 17 00:00:00 2001 From: xyz <2523269+antojoseph@users.noreply.github.com> Date: Thu, 30 Apr 2026 17:49:03 -0400 Subject: [PATCH 1/2] security: idempotent ledger credits prevent Stripe double-billing Add a unique partial index on ledger_entries(entry_type, reference) where reference is non-empty. This enforces at the DB level that a given Stripe session ID can only be credited once, even under concurrent or duplicate webhook delivery. creditTx now also checks for an existing reference before updating the balance, returning early without crediting if a duplicate is detected. The ON CONFLICT DO NOTHING on the ledger insert is a final race-safe guard. --- coordinator/internal/store/postgres.go | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/coordinator/internal/store/postgres.go b/coordinator/internal/store/postgres.go index dbea9e43..7bba8d8b 100644 --- a/coordinator/internal/store/postgres.go +++ b/coordinator/internal/store/postgres.go @@ -195,6 +195,7 @@ func (s *PostgresStore) migrate(ctx context.Context) error { created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() )`, `CREATE INDEX IF NOT EXISTS idx_ledger_account ON ledger_entries(account_id, created_at DESC)`, + `CREATE UNIQUE INDEX IF NOT EXISTS idx_ledger_reference ON ledger_entries(entry_type, reference) WHERE reference <> ''`, // Referral system tables `CREATE TABLE IF NOT EXISTS referrers ( @@ -838,6 +839,24 @@ func nullableCreatedAt(ts time.Time) any { } func creditTx(ctx context.Context, tx pgx.Tx, accountID string, amountMicroUSD int64, entryType LedgerEntryType, reference string, createdAt time.Time) error { + // Idempotency guard: if a non-empty reference has already been recorded for + // this entry_type, skip the credit entirely. Prevents double-crediting on + // duplicate Stripe webhook deliveries. The unique index on + // (entry_type, reference) enforces this at the DB level even under races. + if reference != "" { + var exists bool + err := tx.QueryRow(ctx, + `SELECT EXISTS(SELECT 1 FROM ledger_entries WHERE entry_type = $1 AND reference = $2)`, + string(entryType), reference, + ).Scan(&exists) + if err != nil { + return fmt.Errorf("store: check ledger reference: %w", err) + } + if exists { + return nil + } + } + _, err := tx.Exec(ctx, `INSERT INTO balances (account_id, balance_micro_usd, updated_at) VALUES ($1, $2, NOW()) @@ -860,7 +879,8 @@ func creditTx(ctx context.Context, tx pgx.Tx, accountID string, amountMicroUSD i _, err = tx.Exec(ctx, `INSERT INTO ledger_entries (account_id, entry_type, amount_micro_usd, balance_after, reference, created_at) - VALUES ($1, $2, $3, $4, $5, COALESCE($6, NOW()))`, + VALUES ($1, $2, $3, $4, $5, COALESCE($6, NOW())) + ON CONFLICT (entry_type, reference) WHERE reference <> '' DO NOTHING`, accountID, string(entryType), amountMicroUSD, balanceAfter, reference, nullableCreatedAt(createdAt), ) if err != nil { From e9e396ce0c37275aac6e971ca4a078ecd0913db1 Mon Sep 17 00:00:00 2001 From: xyz <2523269+antojoseph@users.noreply.github.com> Date: Sun, 3 May 2026 23:33:15 -0400 Subject: [PATCH 2/2] fix: scope ledger reference uniqueness to account_id and abort on race MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three changes: 1. Unique index now covers (account_id, entry_type, reference) — not the previous global (entry_type, reference) — so reused generic references like 'reservation_refund' across different accounts remain valid 2. Pre-check also scopes to account_id 3. Ledger insert no longer uses ON CONFLICT DO NOTHING; instead the unique index causes a constraint error if a race slips through the pre-check, rolling back the balance update so no orphaned credit can occur. ErrAlreadyCredited is returned for clean idempotent duplicates. --- coordinator/internal/store/postgres.go | 30 +++++++++++++++++--------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/coordinator/internal/store/postgres.go b/coordinator/internal/store/postgres.go index 7bba8d8b..c184a2d6 100644 --- a/coordinator/internal/store/postgres.go +++ b/coordinator/internal/store/postgres.go @@ -195,7 +195,7 @@ func (s *PostgresStore) migrate(ctx context.Context) error { created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() )`, `CREATE INDEX IF NOT EXISTS idx_ledger_account ON ledger_entries(account_id, created_at DESC)`, - `CREATE UNIQUE INDEX IF NOT EXISTS idx_ledger_reference ON ledger_entries(entry_type, reference) WHERE reference <> ''`, + `CREATE UNIQUE INDEX IF NOT EXISTS idx_ledger_reference ON ledger_entries(account_id, entry_type, reference) WHERE reference <> ''`, // Referral system tables `CREATE TABLE IF NOT EXISTS referrers ( @@ -838,22 +838,26 @@ func nullableCreatedAt(ts time.Time) any { return ts } +// ErrAlreadyCredited is returned by creditTx when the (account_id, entry_type, +// reference) tuple already exists, indicating an idempotent duplicate. +var ErrAlreadyCredited = errors.New("store: credit already applied for this reference") + func creditTx(ctx context.Context, tx pgx.Tx, accountID string, amountMicroUSD int64, entryType LedgerEntryType, reference string, createdAt time.Time) error { - // Idempotency guard: if a non-empty reference has already been recorded for - // this entry_type, skip the credit entirely. Prevents double-crediting on - // duplicate Stripe webhook deliveries. The unique index on - // (entry_type, reference) enforces this at the DB level even under races. + // Idempotency guard: check before touching balances so a duplicate returns + // ErrAlreadyCredited without any side-effects. The index is scoped to + // (account_id, entry_type, reference) so reusing a reference string across + // different accounts (e.g. "reservation_refund") is safe. if reference != "" { var exists bool err := tx.QueryRow(ctx, - `SELECT EXISTS(SELECT 1 FROM ledger_entries WHERE entry_type = $1 AND reference = $2)`, - string(entryType), reference, + `SELECT EXISTS(SELECT 1 FROM ledger_entries WHERE account_id = $1 AND entry_type = $2 AND reference = $3)`, + accountID, string(entryType), reference, ).Scan(&exists) if err != nil { return fmt.Errorf("store: check ledger reference: %w", err) } if exists { - return nil + return ErrAlreadyCredited } } @@ -877,10 +881,13 @@ func creditTx(ctx context.Context, tx pgx.Tx, accountID string, amountMicroUSD i return fmt.Errorf("store: read balance: %w", err) } + // No ON CONFLICT here: the pre-check above is the idempotency gate. + // A race that slips past the pre-check will hit the unique index and + // return a constraint error, causing the caller's transaction to roll back + // (including the balance update), so balances stay consistent. _, err = tx.Exec(ctx, `INSERT INTO ledger_entries (account_id, entry_type, amount_micro_usd, balance_after, reference, created_at) - VALUES ($1, $2, $3, $4, $5, COALESCE($6, NOW())) - ON CONFLICT (entry_type, reference) WHERE reference <> '' DO NOTHING`, + VALUES ($1, $2, $3, $4, $5, COALESCE($6, NOW()))`, accountID, string(entryType), amountMicroUSD, balanceAfter, reference, nullableCreatedAt(createdAt), ) if err != nil { @@ -936,6 +943,9 @@ func (s *PostgresStore) Credit(accountID string, amountMicroUSD int64, entryType defer tx.Rollback(ctx) if err := creditTx(ctx, tx, accountID, amountMicroUSD, entryType, reference, time.Time{}); err != nil { + if errors.Is(err, ErrAlreadyCredited) { + return nil + } return err }