Files
Crussell/backend/handlers/payments/twofa.go
T
popertots e9b0f0f2a7 fix: review-loop hardening — identical-body replay, 2FA gates, webhook at-least-once, GDPR scrub
Follow-up to the comprehensive payment-system review. Fixes the issues the
review found in the initial integration, plus the rough edges it introduced.

Money-safety:
- Replay-by-key now replays the FULL original request verbatim from a stored
  square_request_snapshot, so a retained idempotency key returns the original
  payment instead of IDEMPOTENCY_KEY_REUSED (previously the row sat pending
  forever). IDEMPOTENCY_KEY_REUSED remains ambiguous (never proof of no charge).
- Dev mock mirrors real Square for unknown-key replays: ccof: saved-card
  sources are charged and rescued; spent cnon: nonces surface
  ErrReplayKeyNotRetained. (Fixes dev/prod parity divergence.)
- Webhook dedup row committed AFTER dispatch (at-least-once); FAILED till sales
  claw back gift-card funding; event-type strings match Square's real catalog.
- Expired-gift-card cancellation refunds set creditFailed (never a phantom
  'completed' refund); cancellation refunds lock all payment rows ascending.
- Sweep never rescue-completes a gift-card purchase without delivering the card.
- Tip no-client-key fallback is a deterministic count-based key under the
  booking advisory lock (retry-safe, distinct tips don't collapse).
- M-cap subtracts completed refunds, clamped to [0, total].

2FA (PSD2 SCA stand-in) for online saved-card payments:
- Full feature: status/setup/verify/disable endpoints, gating helper wired into
  all 7 saved-card charge paths (incl. BuyGiftCard + admin saved-card), account
  admin-tab settings UI, frontend gating across all payment surfaces.
- Enforcement is FAIL-CLOSED: on unless REQUIRE_2FA=false or an explicit
  mock/dev SQUARE_ENVIRONMENT; startup warning when off in a non-dev env.
- Verify is brute-force hardened (5-attempt lockout, timing-safe compare);
  plaintext codes only logged when enforcement is off (dev).
- GDPR: anonymize_user also scrubs 2FA columns and staff notes.

Infra/docs:
- nginx: /api/ response cache removed (cross-user disclosure); port 80
  redirects to HTTPS (localhost/RFC1918 exempt, end-anchored regexes); HSTS;
  separate webhook rate-limit zone.
- Schema: users 2FA columns; payments/till_sales square_source_id +
  square_request_snapshot.
- Legal docs: gift-card cooling-off, international-transfers section, tips
  policy; Gap Backlog P3 webhooks marked done; stale counts/wording corrected.
- Flaky test race fixed (t.Parallel + global mock mutation); suite 26/26
  packages green, 2,142 tests, svelte-check clean.
2026-08-22 00:34:49 +01:00

95 lines
3.3 KiB
Go

package payments
import (
"context"
"errors"
"log"
"net/http"
"os"
"crussell/db"
"crussell/mw"
"github.com/jackc/pgx/v5"
)
// twoFactorEnforced reports whether 2FA is required for online card payments.
// It is fail-closed: enforcement is ON unless 2FA has been explicitly disabled
// (REQUIRE_2FA=false) or SQUARE_ENVIRONMENT explicitly selects the dev/mock
// stack (mock/dev/development/test). Empty or unknown SQUARE_ENVIRONMENT values
// are treated as production-enforced, so a mistyped env var can never silently
// disarm the gate — main.go logs a startup warning for that misconfiguration.
func twoFactorEnforced() bool {
if os.Getenv("REQUIRE_2FA") == "false" {
return false
}
return !IsExplicitDevOrMockEnv()
}
// 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.
func IsExplicitDevOrMockEnv() bool {
switch os.Getenv("SQUARE_ENVIRONMENT") {
case "mock", "dev", "development", "test":
return true
default:
return false
}
}
// TwoFactorEnforced is the exported form of twoFactorEnforced, so the user
// package (settings endpoints) and the profile handler can report whether 2FA
// is currently required without re-implementing the env logic.
func (s *PaymentService) TwoFactorEnforced() bool {
return twoFactorEnforced()
}
// UserTwoFactorEnabled reports whether the user has completed 2FA setup
// (users.two_factor_enabled). It is the source of truth for the card-access
// gate: an enforced environment blocks online card access for users who have
// not enabled 2FA.
func (s *PaymentService) UserTwoFactorEnabled(ctx context.Context, userID string) (bool, error) {
var enabled bool
err := db.Conn.QueryRow(ctx, `SELECT two_factor_enabled FROM users WHERE id = $1`, userID).Scan(&enabled)
if err != nil {
return false, err
}
return enabled, nil
}
// requireTwoFactorForCardAccess gates the saved-card online payment paths
// (PSD2 SCA stand-in until real SCA infra lands). It returns true when the
// request may proceed:
//
// - 2FA is not enforced (dev/mock), OR
// - the user has completed 2FA setup (two_factor_enabled).
//
// When 2FA is enforced and the user has not enabled it, a 403 JSON error is
// written (parseable by the frontend via extractErrorMessage) and false is
// returned — the caller must abort the charge.
func requireTwoFactorForCardAccess(w http.ResponseWriter, r *http.Request, service *PaymentService, userID string) bool {
if !twoFactorEnforced() {
return true
}
if service == nil {
service = &PaymentService{}
}
enabled, err := service.UserTwoFactorEnabled(r.Context(), userID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
mw.RespondError(w, http.StatusForbidden, "Two-factor authentication is required to use online card payments. Enable it in your account settings.")
return false
}
log.Printf("failed to check two-factor status for user %s: %v", userID, err)
mw.RespondError(w, http.StatusInternalServerError, "failed to check two-factor status")
return false
}
if enabled {
return true
}
mw.RespondError(w, http.StatusForbidden, "Two-factor authentication is required to use online card payments. Enable it in your account settings.")
return false
}