Implement every finding from the deep payment review (P0-P2, minors, nitpicks), then close the post-implementation re-review items, then align card-form typography and roll out the Square trust badge. Backend - Square API alignment: - tip_settings.allow_tipping nested under device_options (was top-level: terminal tips were silently lost in prod) - CreateCardOnFile now accepts customerID and sends card.customer_id; saved-card (ccof:) charges forward square_customer_id as CustomerID - New SquareClient methods GetPayment, CreateCustomer, CancelCheckout - SCA verification_token accepted + forwarded in all charge paths - ExpMonth/ExpYear -> *int; URL-path id validation; CancelCheckout NOT_FOUND-only no-op (dropped unverified NOOP); exported ErrorCode/ ErrorDetail helpers; mock rejects raw PANs, RList locks, redacts emails, ForceRefundPending hook Backend - money safety: - sweepManualPendingSquareRefunds reconciles rows WITH square_refund_id instead of stranding them forever - SweepStalePendingPayments reconciles at Square before failing (tri-state: leave pending on transport error, rescue completed, fail definitively) - GetCheckoutStatus cancellation-recheck; terminal CANCELED resolution; SweepStaleTerminalCheckouts covers terminal_checkouts table - till gift-card clawback on definitive failure incl. retry path + INSUFFICIENT_FUNDS/ADDRESS_VERIFICATION_FAILURE/TRANSACTION_LIMIT - cross-user saved-card collision fixed (UNIQUE(user_id,square_card_id)) - customer provisioning (lazy, save-only); one-off/guest mint no customer - discount preview/apply unified in discounts.go (global-milestone visible in preview, N+1 eliminated, redemption counter preserved on failures) - webhook event_id dedup; refund loop dedup; stale comment fixes - test-isolation t.Cleanup on committed sweep tests Frontend: - SCA tokenizeWithVerification across all charge flows (amount as major-units decimal), 5-min token-expiry re-tokenize, verification_token in request bodies - PaymentModal synchronous double-click + zero/negative-amount guards - till online-card UI wired to /api/admin/till/sale - policyPopover generalised; new /privacy-policy route; consent checkbox copy + Square privacy link - Square card iframe styled to app typography (Inter 14px, oklch tokens); mock form md:text-sm parity - 'Secure payment powered by Square' badge on all 8 card-payment flows Schema/docs: terminal_checkouts + square_customer_id + per-user card constraint in init-script.sql; README migrations; P14 plan + backlog + Technical Manual updated. Includes 39 modified/new test files; full backend suite (25 pkgs), -race on payments+square, and frontend build are green.
346 lines
11 KiB
Go
346 lines
11 KiB
Go
//go:build test
|
|
|
|
package webhooks
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// =============================================================================
|
|
// 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")
|
|
}
|
|
}
|
|
|
|
// =============================================================================
|
|
// 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
|
|
}
|
|
|
|
// 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))
|
|
}
|
|
|
|
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())
|
|
}
|
|
}
|
|
|
|
func TestHandleSquareWebhook_UnknownEventType(t *testing.T) {
|
|
event := SquareWebhookEvent{
|
|
Type: "invoice.created",
|
|
EventID: "evt_unknown_1",
|
|
CreatedAt: "2025-01-01T00:00:00Z",
|
|
Data: json.RawMessage(`{"id":"inv_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 unknown event type, got %d. body: %s", w.Code, w.Body.String())
|
|
}
|
|
}
|
|
|
|
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())
|
|
}
|
|
}
|
|
|
|
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) {
|
|
|
|
body := []byte(`{"type":"payment.updated","event_id":"evt_1"}`)
|
|
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())
|
|
}
|
|
}
|
|
|
|
// =============================================================================
|
|
// 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())
|
|
}
|
|
}
|
|
|
|
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")
|
|
}
|
|
}
|