fix: review round 6 — P0 deposit charge, idempotency rotation, dev-safety guard, 2FA/webhook hardening

Sixth fresh-eyes review pass (5 agents: goal, QA, code-quality, security,
context-mining). QA FAILED the deposit-required new-card flow; the P0 root
cause was backend + frontend, now fixed. All 20 packages green.

P0 money-safety:
- Deposit-required bookings now actually charge the deposit on new-card
  payment. Two-part fix: (1) CreateBookingHandler re-reads the
  trigger-maintained total_amount/total_duration_minutes from the DB after the
  booking_services insert (the INSERT..RETURNING row predates the recalc
  trigger, so TotalAmount serialized as 0 and DepositPaid computed TRUE on an
  unpaid booking — the frontend gate trusted deposit_paid:true, never charged,
  and confirmed the booking with zero payment rows); (2) BookingFlow.svelte
  gates the confirmation view on depositPaid and guards against re-creating a
  booking on retry. Regression test
  TestBookings_Create_DepositPaidFalseOnUnpaidBooking.

Payments (idempotency + money):
- deriveBookingPaymentIdempotencyKey: no-client-key fallback now advances a
  sequence for repeatable types (partial) and rotates past refunded completed
  rows, so refund-then-repay and equal-amount partials diverge onto distinct
  keys; an un-refunded completed row keeps its key (double-charge protection
  holds). Dedup hits on refunded rows now 409, never stale success.
- chargeFailureStatus default is 503 (ambiguous), never 402; table test.
- Flaky TestBookingPayment_FullPayment_SplitsIntoDepositAndBalance fixed
  (ORDER BY payment_type).
- resolveChargeSource: orphaned card-on-file disabled via DeleteCardOnFile
  when SaveCardForUser fails (best-effort, redacted log); retry path preserved.

Square client:
- Dev builds HARD-FAIL (panic) on SQUARE_ENVIRONMENT=production without
  SQUARE_ALLOW_REAL_API=1; sandbox routes with a loud banner.
- Mock fault-injection FailAfterCommit (commit-then-5xx) exercises the exact
  lost-response same-key retry; SimulateCardTokenUsed; 45-char idempotency-key
  cap parity; SquareEnvironment/SquareLocationID shared env helpers used by
  the sweep (env contract no longer comment-only).
- listRefunds truncation now errors (money-sensitive reconcile retries
  instead of over-refunding); getCardsOnFile truncation loudly logged.

Webhooks + 2FA:
- square-environment header checked fail-closed (403) when configured env is
  production/sandbox; dispatch DB work bounded by 30s timeout contexts.
- 2FA codes HMAC-SHA256 pepper'd (TWO_FACTOR_PEPPER) with legacy-hash
  migration + upgrade-on-verify; disable-flow mint cooldown (1/min, 429) caps
  the brute-force loop; in-lockout records never LRU-evicted.

Repo hygiene:
- env-docs CI gate green again (FRONTEND_ORIGIN + SQUARE_ALLOW_REAL_API +
  TWO_FACTOR_PEPPER documented; Vite DEV built-in allowlisted).
- Dead square_deposits schema dropped; obsidian/README/legal-page drift fixed
  (consumeradvice.scot signposting, CORS allowlist, p11 R3/P13, T1).
- 2FA disable residual documented; P6 email/SMS delivery and P12 sandbox
  smoke test remain the pre-go-live gates.

Verification: go test -tags test,dev -count=1 -parallel 8 ./... (20/20 ok),
go build ./... + -tags dev, go vet clean, svelte-check 0 errors, env-docs
gate OK, live deposit-required flow re-verified end-to-end (deposit £11
charged, square_payment_id recorded).
This commit is contained in:
2026-08-22 00:34:49 +01:00
parent 39cc42b239
commit 67cf5b9a45
31 changed files with 1946 additions and 192 deletions
+134
View File
@@ -16,6 +16,7 @@ import (
"os"
"strings"
"testing"
"time"
"unicode/utf8"
"crussell/db"
@@ -149,6 +150,23 @@ func makeWebhookRequest(body []byte, signature string, ctx context.Context) *htt
return w
}
// makeWebhookRequestWithEnv is makeWebhookRequest plus an explicit
// square-environment header (Square sends one on every real delivery).
func makeWebhookRequestWithEnv(body []byte, signature, env string, ctx context.Context) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/webhooks/square", bytes.NewReader(body))
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
if signature != "" {
req.Header.Set("x-square-hmacsha256-signature", signature)
}
if env != "" {
req.Header.Set("square-environment", env)
}
HandleSquareWebhook(w, req)
return w
}
// webhookTestEnv sets a signing key and returns a valid signature for the body
// (the fail-closed handler requires a verifiable signature on every request).
func webhookTestEnv(t *testing.T, body []byte) (signature string) {
@@ -621,3 +639,119 @@ func TestHandleSquareWebhook_DedupNilConn_FailsClosed(t *testing.T) {
t.Fatalf("expected 503 when DB is not wired, got %d. body: %s", w.Code, w.Body.String())
}
}
// =============================================================================
// square-environment header validation (finding a)
// =============================================================================
// TestHandleSquareWebhook_EnvMismatch_Rejected verifies fail-closed behavior: a
// correctly-signed event carrying a square-environment header that contradicts
// the configured SQUARE_ENVIRONMENT (e.g. a sandbox subscription mis-pointed at
// the production URL + key) is rejected with 403. 403 is correct here because
// the mismatch is a permanent configuration error — Square treats 4xx as
// non-retryable, so the retry loop stops instead of hammering a condition no
// retry can fix. No dispatch and no dedup row.
func TestHandleSquareWebhook_EnvMismatch_Rejected(t *testing.T) {
t.Setenv("SQUARE_ENVIRONMENT", "production")
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_env_mismatch_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"payment_env_mismatch_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
w := makeWebhookRequestWithEnv(body, sig, "sandbox", context.Background())
if w.Code != http.StatusForbidden {
t.Fatalf("expected 403 on environment mismatch, got %d. body: %s", w.Code, w.Body.String())
}
if n := countWebhookEvents(t, event.EventID); n != 0 {
t.Errorf("expected no dedup row for a rejected event, got %d", n)
}
}
// TestHandleSquareWebhook_EnvMatch_Accepted verifies a matching environment
// header passes the check and dispatches normally.
func TestHandleSquareWebhook_EnvMatch_Accepted(t *testing.T) {
t.Setenv("SQUARE_ENVIRONMENT", "production")
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_env_match_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"payment_env_match_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
w := makeWebhookRequestWithEnv(body, sig, "production", context.Background())
if w.Code != http.StatusOK {
t.Fatalf("expected 200 on matching environment, got %d. body: %s", w.Code, w.Body.String())
}
if n := countWebhookEvents(t, event.EventID); n != 1 {
t.Errorf("expected 1 dedup row after successful dispatch, got %d", n)
}
}
// TestHandleSquareWebhook_EnvHeaderAbsent_Allowed verifies an absent header is
// allowed through (local mock/dev posting), even in an enforced deployment —
// the signature check remains the authentication gate.
func TestHandleSquareWebhook_EnvHeaderAbsent_Allowed(t *testing.T) {
t.Setenv("SQUARE_ENVIRONMENT", "production")
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_env_absent_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"payment_env_absent_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
w := makeWebhookRequestWithEnv(body, sig, "", context.Background())
if w.Code != http.StatusOK {
t.Fatalf("expected 200 when the environment header is absent, got %d. body: %s", w.Code, w.Body.String())
}
}
// TestHandleSquareWebhook_EnvMismatch_DevNotEnforced verifies the header check
// is NOT enforced when the configured SQUARE_ENVIRONMENT is a dev/mock value
// (the same interpretation IsExplicitDevOrMockEnv uses elsewhere), so a header
// carrying "sandbox" against an explicit "mock" config still dispatches.
func TestHandleSquareWebhook_EnvMismatch_DevNotEnforced(t *testing.T) {
t.Setenv("SQUARE_ENVIRONMENT", "mock")
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_env_dev_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"payment_env_dev_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
w := makeWebhookRequestWithEnv(body, sig, "sandbox", context.Background())
if w.Code != http.StatusOK {
t.Fatalf("expected 200 in dev mode (check not enforced), got %d. body: %s", w.Code, w.Body.String())
}
}
// =============================================================================
// Bounded post-dispatch DB contexts (finding b)
// =============================================================================
// TestWebhookDBContext_HasTimeout verifies webhookDBContext returns a
// Background-derived context with a deadline, so a hung DB call cannot hold a
// pgx pool connection forever while still surviving a client disconnect.
func TestWebhookDBContext_HasTimeout(t *testing.T) {
ctx, cancel := webhookDBContext()
defer cancel()
deadline, ok := ctx.Deadline()
if !ok {
t.Fatal("expected webhookDBContext to carry a deadline")
}
if remaining := time.Until(deadline); remaining <= 0 || remaining > webhookDBTimeout {
t.Errorf("expected remaining budget within (0, %v], got %v", webhookDBTimeout, remaining)
}
if got := ctx.Err(); got != nil {
t.Errorf("expected a fresh context to be active, got %v", got)
}
}