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.
84 lines
2.9 KiB
Go
84 lines
2.9 KiB
Go
//go:build test
|
|
|
|
package webhooks
|
|
|
|
// Regression test for the at-least-once webhook delivery contract: a dispatch
|
|
// error must NOT commit the dedup row, so Square's retry is not swallowed.
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"testing"
|
|
)
|
|
|
|
// TestHandleSquareWebhook_DispatchError_NoDedup_RetryReDispatches verifies the
|
|
// handler's dispatch-first/commit-dedup-after order: when the dispatch handler
|
|
// errors (here the disputes INSERT fails because the amount overflows
|
|
// NUMERIC(10,2)), the handler returns 503 and records NO dedup row — so a
|
|
// replayed delivery (Square's retry) is re-dispatched, not 200-skipped. Before
|
|
// the at-least-once ordering this invariant silently dropped events on any
|
|
// transient dispatch failure.
|
|
func TestHandleSquareWebhook_DispatchError_NoDedup_RetryReDispatches(t *testing.T) {
|
|
const squarePaymentID = "sqp_dispatch_err"
|
|
_ = createWebhookTestPayment(t, squarePaymentID, "completed")
|
|
|
|
// amount_money.amount = 9,999,999,999,999,999 pence → £99,999,999,999,999.99,
|
|
// far beyond disputes.amount NUMERIC(10,2) — the INSERT fails.
|
|
overflowEvent := SquareWebhookEvent{
|
|
Type: "dispute.created",
|
|
EventID: "evt_dispatch_err_1",
|
|
CreatedAt: "2025-01-01T00:00:00Z",
|
|
Data: json.RawMessage(`{
|
|
"type": "dispute",
|
|
"id": "dts_dispatch_err_1",
|
|
"object": {
|
|
"dispute": {
|
|
"id": "dts_dispatch_err_1",
|
|
"state": "UNDER_REVIEW",
|
|
"amount_money": {"amount": 9999999999999999, "currency": "GBP"},
|
|
"reason": "OVERFLOW",
|
|
"disputed_payment": {"payment_id": "` + squarePaymentID + `"}
|
|
}
|
|
}
|
|
}`),
|
|
}
|
|
|
|
w1 := deliverWebhook(t, overflowEvent)
|
|
if w1.Code != http.StatusServiceUnavailable {
|
|
t.Fatalf("expected 503 on dispatch error, got %d: %s", w1.Code, w1.Body.String())
|
|
}
|
|
if n := countWebhookEvents(t, overflowEvent.EventID); n != 0 {
|
|
t.Fatalf("expected NO dedup row after a dispatch error (Square must retry), got %d", n)
|
|
}
|
|
|
|
// Square retries with a well-formed payload under the SAME event_id.
|
|
retryEvent := SquareWebhookEvent{
|
|
Type: "dispute.created",
|
|
EventID: "evt_dispatch_err_1",
|
|
CreatedAt: "2025-01-01T00:00:00Z",
|
|
Data: json.RawMessage(`{
|
|
"type": "dispute",
|
|
"id": "dts_dispatch_err_1",
|
|
"object": {
|
|
"dispute": {
|
|
"id": "dts_dispatch_err_1",
|
|
"state": "UNDER_REVIEW",
|
|
"amount_money": {"amount": 1234, "currency": "GBP"},
|
|
"reason": "NO_KNOWLEDGE",
|
|
"disputed_payment": {"payment_id": "` + squarePaymentID + `"}
|
|
}
|
|
}
|
|
}`),
|
|
}
|
|
w2 := deliverWebhook(t, retryEvent)
|
|
if w2.Code != http.StatusOK {
|
|
t.Fatalf("expected retry 200, got %d: %s", w2.Code, w2.Body.String())
|
|
}
|
|
if got := getDisputeStatus(t, "dts_dispatch_err_1"); got != "open" {
|
|
t.Errorf("expected retried dispute to be recorded with status 'open', got %q", got)
|
|
}
|
|
if n := countWebhookEvents(t, retryEvent.EventID); n != 1 {
|
|
t.Errorf("expected exactly 1 dedup row after the successful retry, got %d", n)
|
|
}
|
|
}
|