Files
Crussell/backend/handlers/payments/idempotency_helpers.go
T
popertots 36887167c6 fix: loop-A fresh review (503c326 baseline) — overflow-guard bypass, discounted-deposit retry, GDPR audit scrub, till cap, sweep rescue, 2FA reissue + SCA retry, consolidation round
Loop A fresh money/security/dup-mod review of the whole payments overhaul. 28 consolidated findings fixed:

MONEY:
- HIGH-1: B12 overflow guard now uses the discounted obligation — a pre-start deposit can never mint an unintended tip; the discount is never truncated to £0 when the customer pays the discounted deposit
- HIGH-2: discounted-deposit pending-reuse retry compares pendingStoredAmountPence vs chargeAmount (the actual Square amount), not req.Amount — no more permanent amount_mismatch 400 on lost-response retries
- MEDIUM-3: sweep rescue now carves overflow as a tip record + runs completion side-effects (was booking overflow as service revenue, skipping completion)
- MEDIUM-4 (shared w/ security): admin_audit_log.admin_id made nullable + anonymize_user/delete_guest_user NULL it + scrub details.card_last4 — 2fa_fallback_charge PII no longer survives account deletion
- MEDIUM-5: till gift-card payment now passes the £5,000/day admin cap (giftcard_limits)
- LOW-6: expired gift-card balance surfaced as expired/zero in GetUserGiftCardBalance

SECURITY:
- 2FA single-use consume made atomic at verify time for all 5 saved-card gates (fresh charges consume; pending-reuse retries don't); deferred consumption removed
- reissueTwoFACodeAfterFailedCharge routed through the fail-closed issuance gate (pepper check, cooldown) + fresh-only semantics (only when a code was actually consumed)
- family-alive cache invalidated on the stale-family cleanup DELETE (no 30s warm window after expiry)
- frontend 503-retry no longer reuses a consumed 2FA code — aligns with backend re-issue

DUP/MOD:
- reissue helper single-sourced (5 call sites), squareRefundStatusToLocal (10 inline switches), writeChargeSnapshot (7 sites, immutability guard on gift-card/till), postChargeRecheck (3+1 sites), scanIdempotencySlot (2), applyVATToChargeRecord (3 patterns), user_saved_cards upsert (2), BuyGiftCard pending INSERT via service
- till completed-dedup now re-validates paymentHasLiveRefund (aligns with booking/tip/gift-card)
- frontend 402 idempotency-key regeneration added to PaymentModal (aligns with other CIT surfaces)
- PAYMENT_METHOD_SAVED_CARD constant standardised ('saved_card' everywhere)
- admin audit coverage added for AdminRefundBooking + gift-card buy/top-up
- audit-helper cross-package dedup (user/twofa.go now calls payments' exported insert)

Verified: 26/26 dev + 24/24 prod packages, both vet tags, frontend tests + build, gitleaks clean.
2026-08-22 00:34:50 +01:00

100 lines
4.3 KiB
Go

package payments
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"strings"
"crussell/internal/square"
)
// maxIdempotencyKeyLength caps idempotency keys at Square's /v2/payments limit
// (45 chars). The same key is replayed to CreatePayment, so the stricter
// 45-char cap applies even where a destination (e.g. CreateCheckout) allows 64.
// Client-supplied keys are validated against it ("omitempty,max=45") and
// server-derived keys are truncated to it via truncateIdempotencyKey.
// Aliased from the square package — the client to Square, whose limit this is —
// so there is a single source of the constant, not a per-package drift surface.
const maxIdempotencyKeyLength = square.MaxIdempotencyKeyLength
// truncateIdempotencyKey applies the deterministic >45-char sha256 truncation
// shared by the derive* idempotency-key helpers: a candidate longer than
// maxIdempotencyKeyLength is hashed with SHA-256 and returned as
// "<prefix>-<hex of the first 16 hash bytes>", which stays within Square's
// 45-char /v2/payments limit. The hash is deterministic, so identical
// candidates always truncate to the same key — a lost-response retry re-derives
// the same truncated key and Square dedups the charge. Candidates at or under
// the limit are returned verbatim.
func truncateIdempotencyKey(prefix, candidate string) string {
if len(candidate) <= maxIdempotencyKeyLength {
return candidate
}
sum := sha256.Sum256([]byte(candidate))
return prefix + "-" + hex.EncodeToString(sum[:16])
}
// nextIdempotencyCandidate returns the idempotency-key candidate for slot
// sequence seq: the base key itself at seq 0, or "base-seq" at seq >= 1, then
// truncated via truncateIdempotencyKey so the final key stays inside Square's
// 45-char /v2/payments limit. The truncation prefix is derived from the base
// key ("gc-..." -> "gc", "till-..." -> "till") so the truncated form keeps the
// caller's namespace prefix. The slot-scan callers (scanTillIdempotencyKeySlot,
// deriveGiftCardIdempotencyKey) use this under their advisory lock so the
// scan-and-insert sequence is stable across retries.
func nextIdempotencyCandidate(base string, seq int) string {
candidate := base
if seq > 0 {
candidate = fmt.Sprintf("%s-%d", base, seq)
}
prefix := base
if i := strings.IndexByte(base, '-'); i > 0 {
prefix = base[:i]
}
return truncateIdempotencyKey(prefix, candidate)
}
// scanIdempotencySlot iterates the candidate sequence for baseKey (seq 0, 1,
// 2, ...) until it finds a slot NOT occupied by a terminal row, returning the
// first free candidate. occupied reports whether the candidate is taken; the
// caller supplies the table-specific occupancy check. Shared by the gift-card
// purchase key derivation (deriveGiftCardIdempotencyKey) and the till-sale key
// derivation (scanTillIdempotencyKeySlot), which must agree on the
// completed/failed-occupies, pending-never-occupies rule so a lost-response
// retry reuses the same key instead of minting a second charge. Must be called
// under the caller's advisory lock so the scan-and-insert races no concurrent
// identical request.
func scanIdempotencySlot(ctx context.Context, baseKey string, occupied func(candidate string) (bool, error)) (string, error) {
for seq := 0; ; seq++ {
candidate := nextIdempotencyCandidate(baseKey, seq)
isOccupied, err := occupied(candidate)
if err != nil {
return "", err
}
if !isOccupied {
return candidate, nil
}
}
}
// IsExplicitDevOrMockEnv reports whether SQUARE_ENVIRONMENT explicitly selects
// the dev/mock Square stack. Only these exact values are treated as dev; an
// empty or unknown value is NOT dev (fail-closed), because in production an
// unset/mistyped env var must never bypass the 2FA gate or decrypt/encrypt
// snapshot expectations (A9). It lives here — the neutral idempotency helper
// file — because it gates far more than 2FA: snapshot encryption
// (charge_helpers.go), the sweep's replay checks and snapshot decryption
// (sweep.go), the till snapshot refresh (till.go), the gift-card reuse
// snapshot handling (giftcards.go), and main.go's startup warnings. The
// exported name is stable for main.go; in-package callers use it directly.
func IsExplicitDevOrMockEnv() bool {
switch os.Getenv("SQUARE_ENVIRONMENT") {
case "mock", "dev", "development", "test":
return true
default:
return false
}
}