Files
Crussell/backend/handlers/webhooks/webhooks_test.go
T
popertots 6d82535780 fix: adversarial review round — replay-rescue double-charge, discount credit, 2FA/per-IP limits, snapshot encryption, refund reconciliation, VAT, frontend parity, tests+docs
Addresses the adversarial fresh-eyes audit (findings A1-A20) plus review-round fixes:
- CRITICAL A1: replay-by-key rescue cross-checks replayed CreatedAt; ccof blind-fail leaves pending with CRITICAL + notification instead of clawing back
- A2/A3/A4: till idempotency key restored to unconditional hash; tip rejected in CreateBookingPayment; campaign discount now reduces the charged amount (deposit credit)
- A5: admin notifications on blind-fail, manual-refund re-arm, cap-stranded charge-group, webhook FAILED/REJECTED refunds
- A6/A10: BuyGiftCard idempotency user-scoped; gift-card slot scan advances past failed rows
- A7/A14/A15: 2FA user+IP limiter, SNAPSHOT_ENC_KEY startup validation, accurate pepper/log-delivery docs
- A8/A9: snapshot encryption on all write+reuse sites; MPV->SPV effective voucher type (single VAT point)
- A11/A12/A13/A16: amount-aware refund reconciliation; completed-booking refund re-validation; till retry dedup; PaymentWasRefunded on SquareClient interface
- A17/A18/A19/A20: CI runs npm test; confirm_overflow_tip frontend dialog; unknown-event admin notification; mock token redaction
- M7 ConfirmOverflowTip, M9 snapshot encryption, C1 discount ordering regression test
- Frontend vitest framework (41 tests), backend coverage for fixed functions, docs corrected (2,269 tests, SUPPORT_EMAIL tokens, resolution status)

All 25 backend packages pass; frontend 41/41; build + env-docs green.
2026-08-22 00:34:50 +01:00

1022 lines
38 KiB
Go

//go:build test
package webhooks
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"unicode/utf8"
"crussell/db"
"github.com/jackc/pgx/v5/pgxpool"
)
// =============================================================================
// Unit tests — verifySquareSignature (pure function)
// =============================================================================
func TestVerifySquareSignature_ValidSignature(t *testing.T) {
t.Parallel()
body := []byte(`{"type":"payment.updated","event_id":"evt_1"}`)
key := "test-signing-key"
notificationURL := "http://localhost:8080/webhooks/square"
payload := notificationURL + string(body)
mac := hmac.New(sha256.New, []byte(key))
mac.Write([]byte(payload))
expectedSig := base64.StdEncoding.EncodeToString(mac.Sum(nil))
if !verifySquareSignature(body, expectedSig, key, notificationURL) {
t.Error("expected valid signature to verify")
}
}
func TestVerifySquareSignature_InvalidSignature(t *testing.T) {
t.Parallel()
body := []byte(`{"type":"payment.updated"}`)
key := "test-signing-key"
notificationURL := "http://localhost:8080/webhooks/square"
if verifySquareSignature(body, "invalid-signature", key, notificationURL) {
t.Error("expected invalid signature to fail")
}
}
func TestVerifySquareSignature_WrongKey(t *testing.T) {
t.Parallel()
body := []byte(`{"type":"payment.updated"}`)
notificationURL := "http://localhost:8080/webhooks/square"
payload := notificationURL + string(body)
mac := hmac.New(sha256.New, []byte("correct-key"))
mac.Write([]byte(payload))
sig := base64.StdEncoding.EncodeToString(mac.Sum(nil))
// Verify with a different key
if verifySquareSignature(body, sig, "wrong-key", notificationURL) {
t.Error("expected wrong key to produce failing verification")
}
}
func TestVerifySquareSignature_EmptyBody(t *testing.T) {
t.Parallel()
key := "test-signing-key"
notificationURL := "http://localhost:8080/webhooks/square"
payload := notificationURL + string([]byte{})
mac := hmac.New(sha256.New, []byte(key))
mac.Write([]byte(payload))
expectedSig := base64.StdEncoding.EncodeToString(mac.Sum(nil))
if !verifySquareSignature([]byte{}, expectedSig, key, notificationURL) {
t.Error("expected empty body verification to succeed with matching signature")
}
}
func TestVerifySquareSignature_TamperedBody(t *testing.T) {
t.Parallel()
body := []byte(`{"type":"payment.updated","event_id":"evt_1"}`)
key := "test-signing-key"
notificationURL := "http://localhost:8080/webhooks/square"
payload := notificationURL + string(body)
mac := hmac.New(sha256.New, []byte(key))
mac.Write([]byte(payload))
sig := base64.StdEncoding.EncodeToString(mac.Sum(nil))
// Verify with a tampered body
tamperedBody := []byte(`{"type":"payment.updated","event_id":"evt_2"}`)
if verifySquareSignature(tamperedBody, sig, key, notificationURL) {
t.Error("expected tampered body to fail verification")
}
}
func TestTruncateDisputeReason_RuneSafe(t *testing.T) {
// 191 ASCII bytes + a 4-byte emoji: byte-slicing at 192 would split the
// emoji into an incomplete rune (invalid UTF-8). Rune-safe truncation must
// keep the whole emoji and stay valid UTF-8.
edge := strings.Repeat("a", 191) + "\U0001F600"
got := truncateDisputeReason(edge)
if !utf8.ValidString(got) {
t.Errorf("expected valid UTF-8 after truncation, got %q", got)
}
if !strings.HasSuffix(got, "\U0001F600") {
t.Errorf("expected the 4-byte rune to be preserved intact, got %q", got)
}
if len(got) != 195 { // 191 ASCII + 4-byte emoji
t.Errorf("expected 195 bytes (191 ASCII + 4-byte emoji), got %d", len(got))
}
// An over-long multi-byte reason truncates to exactly 192 runes.
got = truncateDisputeReason(strings.Repeat("界", 300))
if r := []rune(got); len(r) != 192 {
t.Errorf("expected exactly 192 runes after truncation, got %d", len(r))
}
if !utf8.ValidString(got) {
t.Errorf("expected valid UTF-8 after truncation, got %q", got)
}
// Short and ASCII reasons pass through untouched.
if got := truncateDisputeReason("NO_KNOWLEDGE"); got != "NO_KNOWLEDGE" {
t.Errorf("expected short reason unchanged, got %q", got)
}
}
// =============================================================================
// Integration tests — HandleSquareWebhook
// =============================================================================
func makeWebhookRequest(body []byte, signature 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)
}
HandleSquareWebhook(w, req)
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) {
t.Helper()
tKey := "test-signing-key"
tURL := "http://localhost:8080/webhooks/square"
mac := hmac.New(sha256.New, []byte(tKey))
mac.Write([]byte(tURL))
mac.Write(body)
t.Setenv("SQUARE_WEBHOOK_SIGNATURE_KEY", tKey)
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
// countWebhookEvents returns how many dedup rows exist for an event_id. The
// handler commits its dedup insert to the pool (no per-test transaction), so a
// fresh query sees it.
func countWebhookEvents(t *testing.T, eventID string) int {
t.Helper()
var n int
if err := db.Conn.QueryRow(context.Background(),
"SELECT COUNT(*) FROM square_webhook_events WHERE event_id = $1", eventID).Scan(&n); err != nil {
t.Fatalf("failed to count square_webhook_events rows: %v", err)
}
return n
}
// testDBHost mirrors testdb.dbHost so the broken-pool test can reach the same
// Postgres instance without importing testdb internals.
func testDBHost() string {
if h := os.Getenv("TEST_DB_HOST"); h != "" {
return h
}
if h := os.Getenv("POSTGRES_HOST"); h != "" {
return h
}
return "localhost"
}
func TestHandleSquareWebhook_PaymentUpdated(t *testing.T) {
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_payment_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"payment_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d. body: %s", w.Code, w.Body.String())
}
if w.Body.String() != "ok" {
t.Errorf("expected body 'ok', got %q", w.Body.String())
}
}
func TestHandleSquareWebhook_RefundUpdated(t *testing.T) {
event := SquareWebhookEvent{
Type: "refund.updated",
EventID: "evt_refund_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"refund_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d. body: %s", w.Code, w.Body.String())
}
}
func TestHandleSquareWebhook_DisputeCreated(t *testing.T) {
event := SquareWebhookEvent{
Type: "dispute.created",
EventID: "evt_dispute_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"dispute_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusOK {
t.Errorf("expected 200 for dispute.created, got %d. body: %s", w.Code, w.Body.String())
}
}
// TestHandleSquareWebhook_UnknownEventType verifies a signed event whose type
// prefix matches NEITHER the handled switch cases NOR a known family
// (e.g. frobnicator.created) is NOT acknowledged 200. The handler returns 501
// Not Implemented with body "unhandled webhook event type", so Square's retry
// policy re-delivers the event and it stays visible in the delivery history —
// the event is surfaced and retried, never silently acked. No dedup row is
// written on the 501 path, so a retry (or a future code path supporting the
// type) is always re-dispatched.
func TestHandleSquareWebhook_UnknownEventType(t *testing.T) {
event := SquareWebhookEvent{
Type: "frobnicator.created",
EventID: "evt_unknown_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"frob_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
notifBefore := countCriticalNotifications(t)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusNotImplemented {
t.Errorf("expected 501 Not Implemented for unknown event type, got %d. body: %s", w.Code, w.Body.String())
}
if got := strings.TrimSpace(w.Body.String()); got != "unhandled webhook event type" {
t.Errorf("expected body 'unhandled webhook event type', got %q", w.Body.String())
}
// The 501 path returns before the dedup commit (like the dispatch-error
// path): Square must be allowed to retry, so no dedup row may be persisted.
if n := countWebhookEvents(t, event.EventID); n != 0 {
t.Errorf("expected no dedup row for an unhandled event type (Square must retry), got %d", n)
}
// A19: the event must still surface in the admin notification centre —
// without it, after Square's ~24h retry window the event is silently gone.
// The notification is a SEPARATE table, so the no-dedup-row assertion above
// still holds.
if n := countCriticalNotifications(t) - notifBefore; n != 1 {
t.Errorf("expected exactly 1 critical_payment_log admin notification for the unknown event (A19), got %d", n)
}
}
// TestHandleSquareWebhook_KnownNonMoneyEvent_Acknowledged verifies a signed
// event from a KNOWN NON-MONEY family this app will never process
// (e.g. customer.created) is deliberately acknowledged 200 WITH a committed
// dedup row so Square stops retrying it. These events carry no money state the
// app tracks, so acking loses nothing — and retrying them would fill the
// subscription's retry queue until Square suspends it, silently killing
// money-event delivery (payment.created/updated). The ack is logged at WARN.
func TestHandleSquareWebhook_KnownNonMoneyEvent_Acknowledged(t *testing.T) {
event := SquareWebhookEvent{
Type: "customer.created",
EventID: "evt_nonmoney_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"cust_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
var buf bytes.Buffer
oldOutput := log.Writer()
log.SetOutput(&buf)
defer log.SetOutput(oldOutput)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusOK {
t.Errorf("expected 200 for acknowledged non-money event, got %d. body: %s", w.Code, w.Body.String())
}
if w.Body.String() != "ok" {
t.Errorf("expected body 'ok', got %q", w.Body.String())
}
// Exactly one dedup row is committed so Square stops retrying.
if n := countWebhookEvents(t, event.EventID); n != 1 {
t.Errorf("expected exactly 1 dedup row for an acknowledged non-money event (Square stops retrying), got %d", n)
}
out := buf.String()
if !strings.Contains(out, "WARNING: acknowledged unhandled non-money event") {
t.Errorf("expected WARN ack log for non-money event, got:\n%s", out)
}
}
// TestHandleSquareWebhook_UnhandledMoneyEvent_NotAcknowledged verifies a
// MONEY-STATE family event that is NOT one of the explicitly handled switch
// cases (e.g. payment.checkout_offer_created) is NOT acknowledged 200: the
// handler returns 501 with body "unhandled webhook event type" and writes NO
// dedup row, so Square's retry re-delivers it. A money event this app does not
// yet handle is never a safe 200-ack — the caller would commit the dedup row
// and the event would be dropped forever.
func TestHandleSquareWebhook_UnhandledMoneyEvent_NotAcknowledged(t *testing.T) {
event := SquareWebhookEvent{
Type: "payment.checkout_offer_created",
EventID: "evt_money_unhandled_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"pco_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
notifBefore := countCriticalNotifications(t)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusNotImplemented {
t.Errorf("expected 501 Not Implemented for unhandled money-family event, got %d. body: %s", w.Code, w.Body.String())
}
if got := strings.TrimSpace(w.Body.String()); got != "unhandled webhook event type" {
t.Errorf("expected body 'unhandled webhook event type', got %q", w.Body.String())
}
// The 501 path returns before the dedup commit: the event must be retried,
// so no dedup row may be persisted.
if n := countWebhookEvents(t, event.EventID); n != 0 {
t.Errorf("expected no dedup row for an unhandled money-family event (Square must retry), got %d", n)
}
// A19: the unhandled money event must still surface in the admin
// notification centre before the retry window closes.
if n := countCriticalNotifications(t) - notifBefore; n != 1 {
t.Errorf("expected exactly 1 critical_payment_log admin notification for the unhandled money-family event (A19), got %d", n)
}
}
func TestHandleSquareWebhook_InvalidJSON(t *testing.T) {
body := []byte(`{invalid json}`)
sig := webhookTestEnv(t, body)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusBadRequest {
t.Errorf("expected 400 for invalid JSON, got %d. body: %s", w.Code, w.Body.String())
}
}
// TestHandleSquareWebhook_EmptyEventID_Rejected verifies a signed event with an
// empty event_id is rejected with 400 — fail-safe: no dispatch, no dedup row.
// Square's retry policy treats 4xx as non-retryable, so the malformed event is
// dropped without side effects.
func TestHandleSquareWebhook_EmptyEventID_Rejected(t *testing.T) {
body := []byte(`{"type":"payment.updated","event_id":"","data":{"id":"payment_empty_id"}}`)
sig := webhookTestEnv(t, body)
var buf bytes.Buffer
oldOutput := log.Writer()
log.SetOutput(&buf)
defer log.SetOutput(oldOutput)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for empty event_id, got %d. body: %s", w.Code, w.Body.String())
}
out := buf.String()
if !strings.Contains(out, "Rejecting event with empty event_id (400)") {
t.Errorf("expected empty event_id rejection log, got:\n%s", out)
}
if strings.Contains(out, "Received event: payment.updated") {
t.Errorf("expected empty event_id to skip dispatch, got:\n%s", out)
}
// No dedup row may be written for an empty event_id.
if n := countWebhookEvents(t, ""); n != 0 {
t.Errorf("expected no dedup row for empty event_id, got %d", n)
}
}
func TestHandleSquareWebhook_BodyTooLarge(t *testing.T) {
// 600KB body exceeds the 512KB limit
largeBody := []byte(strings.Repeat("a", 600*1024))
sig := webhookTestEnv(t, largeBody)
w := makeWebhookRequest(largeBody, sig, context.Background())
if w.Code != http.StatusRequestEntityTooLarge {
t.Errorf("expected 413 for oversized body, got %d. body: %s", w.Code, w.Body.String())
}
}
func TestHandleSquareWebhook_ValidSignatureWithEnvKey(t *testing.T) {
// Well-formed payment.updated event carrying the full nested payment object
// (data.object.payment with id/status) so handlePaymentUpdated can parse
// and dispatch it — a known money event whose payload fails to parse
// returns 503 without a dedup row (Square retries), which is NOT this
// test's intent. The unique event_id and square_payment_id avoid colliding
// with the other tests' dedup rows and payment fixtures.
body := []byte(`{"type":"payment.updated","event_id":"evt_envkey_1","created_at":"2025-01-01T00:00:00Z","data":{"object":{"payment":{"id":"sqp_env_key_1","status":"COMPLETED","amount_money":{"amount":5000,"currency":"GBP"},"updated_at":"2025-01-01T00:00:00Z"}}}}`)
key := "env-signing-key"
notificationURL := "http://localhost:8080/webhooks/square"
payload := notificationURL + string(body)
mac := hmac.New(sha256.New, []byte(key))
mac.Write([]byte(payload))
sig := base64.StdEncoding.EncodeToString(mac.Sum(nil))
t.Setenv("SQUARE_WEBHOOK_SIGNATURE_KEY", key)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusOK {
t.Errorf("expected 200 with valid signature, got %d. body: %s", w.Code, w.Body.String())
}
}
func TestHandleSquareWebhook_InvalidSignatureWithEnvKey(t *testing.T) {
body := []byte(`{"type":"payment.updated","event_id":"evt_1"}`)
t.Setenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "env-signing-key")
w := makeWebhookRequest(body, "bad-signature", context.Background())
if w.Code != http.StatusForbidden {
t.Errorf("expected 403 with invalid signature, got %d. body: %s", w.Code, w.Body.String())
}
}
func TestHandleSquareWebhook_NoSignatureWhenKeySet(t *testing.T) {
body := []byte(`{"type":"payment.updated","event_id":"evt_1"}`)
t.Setenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "env-signing-key")
// No x-square-signature header at all
w := makeWebhookRequest(body, "", context.Background())
if w.Code != http.StatusForbidden {
t.Errorf("expected 403 when signature key is set but header missing, got %d. body: %s", w.Code, w.Body.String())
}
}
func TestHandleSquareWebhook_RejectedWhenKeyEmpty(t *testing.T) {
t.Setenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "")
body := []byte(`{"type":"payment.updated","event_id":"evt_1"}`)
// Fail-closed: an unset signing key means the webhook cannot be verified,
// so the request is rejected rather than accepted with a bad signature.
w := makeWebhookRequest(body, "some-signature", context.Background())
if w.Code != http.StatusServiceUnavailable {
t.Errorf("expected 503 when no key configured (fail-closed), got %d. body: %s", w.Code, w.Body.String())
}
}
func TestHandleSquareWebhook_NoRawPayloadInLogs(t *testing.T) {
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_pii_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"payment_pii_1","buyer_email_address":"secret@example.com",
"card_details":{"card":{"brand":"VISA","last_4":"1234","cardholder_name":"Jane Doe"}}}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
var buf bytes.Buffer
oldOutput := log.Writer()
log.SetOutput(&buf)
defer log.SetOutput(oldOutput)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d. body: %s", w.Code, w.Body.String())
}
out := buf.String()
for _, pii := range []string{"secret@example.com", "VISA", "1234", "Jane Doe", "payment_pii_1_full"} {
if strings.Contains(out, pii) {
t.Errorf("log output leaked PII %q:\n%s", pii, out)
}
}
if !strings.Contains(out, "data.id=payment_pii_1") {
t.Errorf("expected log to include object id, got:\n%s", out)
}
if !strings.Contains(out, "Received event: payment.updated") {
t.Errorf("expected log to reference event type, got:\n%s", out)
}
}
// =============================================================================
// Dedup — event_id replay protection
// =============================================================================
func TestHandleSquareWebhook_DuplicateEventID(t *testing.T) {
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_http_dup_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"payment_dup_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
// First delivery processes the event.
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusOK {
t.Fatalf("expected first delivery 200, got %d. body: %s", w.Code, w.Body.String())
}
// Replay of the same signed event returns 200 but skips dispatch.
w2 := makeWebhookRequest(body, sig, context.Background())
if w2.Code != http.StatusOK {
t.Fatalf("expected replay 200, got %d. body: %s", w2.Code, w2.Body.String())
}
if w2.Body.String() != "ok" {
t.Errorf("expected replay body 'ok', got %q", w2.Body.String())
}
// The persistent dedup row is written exactly once despite both deliveries.
if n := countWebhookEvents(t, event.EventID); n != 1 {
t.Errorf("expected exactly 1 persisted dedup row, got %d", n)
}
}
func TestHandleSquareWebhook_DistinctEventIDs(t *testing.T) {
for _, id := range []string{"evt_distinct_1", "evt_distinct_2"} {
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: id,
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"p"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusOK {
t.Fatalf("expected 200 for %s, got %d. body: %s", id, w.Code, w.Body.String())
}
}
}
func TestSquareWebhookDedup_FirstThenDuplicate(t *testing.T) {
d := newSquareWebhookDedup(1000)
if d.register("evt_dedup_1") {
t.Error("expected first occurrence to register as new")
}
if !d.register("evt_dedup_1") {
t.Error("expected second occurrence to register as duplicate")
}
}
func TestSquareWebhookDedup_CapEvictsOldest(t *testing.T) {
d := newSquareWebhookDedup(3)
for i := 0; i < 3; i++ {
if d.register(fmt.Sprintf("evt_cap_%d", i)) {
t.Errorf("expected evt_cap_%d to register as new", i)
}
}
// The 4th distinct ID pushes out the oldest (evt_cap_0).
if d.register("evt_cap_3") {
t.Errorf("expected evt_cap_3 to register as new")
}
// Survivors still dedupe (register returns true without mutating the set).
for _, id := range []string{"evt_cap_1", "evt_cap_2", "evt_cap_3"} {
if !d.register(id) {
t.Errorf("expected %s to still be a duplicate", id)
}
}
// The evicted ID is treated as new again.
if d.register("evt_cap_0") {
t.Errorf("expected evt_cap_0 to be evicted and treated as new")
}
}
func TestSquareWebhookDedup_HasDoesNotRecord(t *testing.T) {
d := newSquareWebhookDedup(3)
if d.has("evt_has_1") {
t.Error("expected has() on empty set to return false")
}
if d.register("evt_has_1") {
t.Error("expected first register to report new")
}
if !d.has("evt_has_1") {
t.Error("expected has() to observe a registered id")
}
}
// TestHandleSquareWebhook_DedupDispatchOnce verifies the handler body runs
// exactly once across a delivery + replay, with a single persisted dedup row.
func TestHandleSquareWebhook_DedupDispatchOnce(t *testing.T) {
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_dispatch_once_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"payment_dispatch_once_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
var buf bytes.Buffer
oldOutput := log.Writer()
log.SetOutput(&buf)
defer log.SetOutput(oldOutput)
w1 := makeWebhookRequest(body, sig, context.Background())
if w1.Code != http.StatusOK {
t.Fatalf("expected first delivery 200, got %d. body: %s", w1.Code, w1.Body.String())
}
w2 := makeWebhookRequest(body, sig, context.Background())
if w2.Code != http.StatusOK {
t.Fatalf("expected replay 200, got %d. body: %s", w2.Code, w2.Body.String())
}
if w2.Body.String() != "ok" {
t.Errorf("expected replay body 'ok', got %q", w2.Body.String())
}
out := buf.String()
if got := strings.Count(out, "Received event: payment.updated"); got != 1 {
t.Errorf("expected dispatch to run exactly once, saw %d 'Received event' log lines:\n%s", got, out)
}
if n := countWebhookEvents(t, event.EventID); n != 1 {
t.Errorf("expected exactly 1 persisted dedup row, got %d", n)
}
}
// TestHandleSquareWebhook_DedupPersistsAcrossRestart simulates a restart: the
// event was handled by a previous process whose in-memory cache is gone, but
// the dedup row survived in the DB. The dedup row now commits AFTER dispatch
// (at-least-once delivery), so a replayed delivery is re-dispatched — the
// idempotent status-guarded handlers are a no-op the second time — and is
// acknowledged 200 without duplicating the persisted dedup row.
func TestHandleSquareWebhook_DedupPersistsAcrossRestart(t *testing.T) {
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_restart_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"payment_restart_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
if _, err := db.Conn.Exec(context.Background(),
"INSERT INTO square_webhook_events (event_id) VALUES ($1) ON CONFLICT (event_id) DO NOTHING", event.EventID); err != nil {
t.Fatalf("failed to seed dedup row: %v", err)
}
var buf bytes.Buffer
oldOutput := log.Writer()
log.SetOutput(&buf)
defer log.SetOutput(oldOutput)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusOK {
t.Fatalf("expected 200 for replayed event, got %d. body: %s", w.Code, w.Body.String())
}
if w.Body.String() != "ok" {
t.Errorf("expected body 'ok', got %q", w.Body.String())
}
if out := buf.String(); !strings.Contains(out, "Received event: payment.updated") {
t.Errorf("expected replayed event to be re-dispatched (at-least-once), got:\n%s", out)
}
if n := countWebhookEvents(t, event.EventID); n != 1 {
t.Errorf("expected still exactly 1 dedup row, got %d", n)
}
}
// webhookConcurrentTestSeq gives each invocation of
// TestHandleSquareWebhook_ConcurrentSameEvent_Serialized a distinct
// square_payment_id + event_id, so repeated in-process runs (-count>1, or a
// replay in the same suite) cannot collide on the process-global dedup cache
// or the shared test DB — the suite is order-independent.
var webhookConcurrentTestSeq atomic.Int64
// TestHandleSquareWebhook_ConcurrentSameEvent_Serialized verifies the in-memory
// fast-path dedup (squareWebhookEventsSeen) plus the DB ON CONFLICT (event_id)
// insert serialize CONCURRENT delivery of the same signed event_id. Two
// goroutines hitting the handler with the same payload must produce exactly one
// persisted dedup row, exactly one "already processed" short-circuit (either
// the in-memory 'skipping' fast-path or the DB-conflict 'acknowledging'
// branch), and exactly one state mutation — the status-guarded UPDATE applies
// once and the second delivery's UPDATE is a 0-row no-op.
func TestHandleSquareWebhook_ConcurrentSameEvent_Serialized(t *testing.T) {
seq := webhookConcurrentTestSeq.Add(1)
squarePaymentID := fmt.Sprintf("sqp_concurrent_same_%d", seq)
eventID := fmt.Sprintf("evt_concurrent_same_%d", seq)
payID := createWebhookTestPayment(t, squarePaymentID, "pending")
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: eventID,
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{
"type": "payment",
"id": "` + squarePaymentID + `",
"object": {
"payment": {
"id": "` + squarePaymentID + `",
"status": "COMPLETED"
}
}
}`),
}
body, err := json.Marshal(event)
if err != nil {
t.Fatalf("failed to marshal webhook event: %v", err)
}
sig := webhookTestEnv(t, body)
var buf bytes.Buffer
oldOutput := log.Writer()
log.SetOutput(&buf)
defer log.SetOutput(oldOutput)
var wg sync.WaitGroup
codes := make([]int, 2)
for i := range codes {
wg.Add(1)
go func(idx int) {
defer wg.Done()
codes[idx] = makeWebhookRequest(body, sig, context.Background()).Code
}(i)
}
wg.Wait()
for i, code := range codes {
if code != http.StatusOK {
t.Errorf("delivery %d: expected 200, got %d", i, code)
}
}
if got := getPaymentStatus(t, payID); got != "completed" {
t.Errorf("expected payment 'completed' after concurrent delivery, got %q", got)
}
if n := countWebhookEvents(t, event.EventID); n != 1 {
t.Errorf("expected exactly 1 persisted dedup row after concurrent delivery, got %d", n)
}
out := buf.String()
// Exactly one of the two deliveries hit an "already processed" path; the
// other processed fresh (both may still return 200).
if got := strings.Count(out, "already processed"); got != 1 {
t.Errorf("expected exactly 1 'already processed' short-circuit, got %d:\n%s", got, out)
}
// The status-guarded UPDATE applied exactly once — the second delivery's
// UPDATE matched 0 rows (already 'completed') and logged nothing.
if got := strings.Count(out, "→ local status completed"); got != 1 {
t.Errorf("expected exactly 1 state-mutation log line, got %d:\n%s", got, out)
}
}
// TestHandleSquareWebhook_DedupCacheEviction_Redispatches documents why the
// 500-slot in-memory dedup cache cannot permanently hide an event across the
// test suite (or a long-lived process): once an event_id is evicted from the
// bounded cache, a replayed delivery is treated as NEW and re-dispatched — the
// DB dedup row is what actually absorbs it. Concretely: process the event
// (registers it + writes the dedup row), flood the cache past its 500-entry
// cap so the event is evicted, then replay it — the handler re-dispatches (the
// "Received event" log appears again) and the DB ON CONFLICT keeps the dedup
// row at exactly 1.
func TestHandleSquareWebhook_DedupCacheEviction_Redispatches(t *testing.T) {
resetSquareWebhookEventsSeen()
defer resetSquareWebhookEventsSeen()
const squarePaymentID = "sqp_dedup_eviction"
payID := createWebhookTestPayment(t, squarePaymentID, "pending")
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_dedup_eviction_target",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{
"type": "payment",
"id": "` + squarePaymentID + `",
"object": {
"payment": {
"id": "` + squarePaymentID + `",
"status": "COMPLETED"
}
}
}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
var buf bytes.Buffer
oldOutput := log.Writer()
log.SetOutput(&buf)
defer log.SetOutput(oldOutput)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusOK {
t.Fatalf("expected first delivery 200, got %d. body: %s", w.Code, w.Body.String())
}
if n := countWebhookEvents(t, event.EventID); n != 1 {
t.Fatalf("expected 1 dedup row after first delivery, got %d", n)
}
// Flood the 500-slot cache so the target event_id is evicted.
for i := 0; i < squareWebhookEventsSeen.max; i++ {
squareWebhookEventsSeen.register(fmt.Sprintf("evt_eviction_fill_%d", i))
}
if squareWebhookEventsSeen.has(event.EventID) {
t.Fatal("expected target event_id to be evicted from the 500-slot cache")
}
// Replay: evicted from the fast-path cache, so it is re-dispatched. The DB
// row already exists, so the ON CONFLICT insert keeps the count at 1.
w2 := makeWebhookRequest(body, sig, context.Background())
if w2.Code != http.StatusOK {
t.Fatalf("expected replay 200, got %d. body: %s", w2.Code, w2.Body.String())
}
if w2.Body.String() != "ok" {
t.Errorf("expected replay body 'ok', got %q", w2.Body.String())
}
out := buf.String()
if got := strings.Count(out, "Received event: payment.updated"); got != 2 {
t.Errorf("expected the evicted event to be re-dispatched (2 'Received event' lines), got %d:\n%s", got, out)
}
if n := countWebhookEvents(t, event.EventID); n != 1 {
t.Errorf("expected still exactly 1 dedup row after re-dispatch, got %d", n)
}
if got := getPaymentStatus(t, payID); got != "completed" {
t.Errorf("expected payment 'completed', got %q", got)
}
}
// TestHandleSquareWebhook_DedupInsertFails_FailsClosed verifies the handler
// rejects (503) when the dedup INSERT cannot be persisted, so Square retries.
func TestHandleSquareWebhook_DedupInsertFails_FailsClosed(t *testing.T) {
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_db_down_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"payment_db_down_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
orig := db.Conn
defer func() { db.Conn = orig }()
// A pool whose database does not exist fails every Exec — simulating a DB
// that is unreachable or down.
badDSN := fmt.Sprintf("postgres://myuser:mypassword@%s:5432/crussell_test_webhooks_nonexistent?sslmode=disable", testDBHost())
badPool, err := pgxpool.New(context.Background(), badDSN)
if err != nil {
t.Fatalf("failed to create broken pool: %v", err)
}
defer badPool.Close()
db.Conn = db.NewPoolProxy(badPool)
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusServiceUnavailable {
t.Fatalf("expected 503 when dedup write fails, got %d. body: %s", w.Code, w.Body.String())
}
}
// TestHandleSquareWebhook_DedupNilConn_FailsClosed verifies the handler also
// rejects (503) when the DB was never wired at all (defensive fail-closed).
func TestHandleSquareWebhook_DedupNilConn_FailsClosed(t *testing.T) {
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_nil_conn_1",
CreatedAt: "2025-01-01T00:00:00Z",
Data: json.RawMessage(`{"id":"payment_nil_conn_1"}`),
}
body, _ := json.Marshal(event)
sig := webhookTestEnv(t, body)
orig := db.Conn
db.Conn = nil
defer func() { db.Conn = orig }()
w := makeWebhookRequest(body, sig, context.Background())
if w.Code != http.StatusServiceUnavailable {
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)
}
}