Fix payment review round 3: saved-card idempotency, stale-pending sweep, webhook fail-closed

R1/R4: saved_card branch in CreateTerminalPayment now mirrors CreateTipPayment
- advisory lock (crussell:payment:<bookingID>) serializes concurrent double-clicks
- deterministic key bookingID-sc-type-amount-cardID (<=45 chars) so a lost-response
  retry derives the same key and dedups instead of double-charging
- idempotency switch inside the lock: completed -> dedup, pending -> reuse with
  pence amount-guard, failed -> clean 409
- success response includes card_brand/card_last4 (frontend already reads them)

R2: add 'failed' case to all four retry switches (tip, booking, gift card, till)
- a swept/definitively-rejected record returns 409 instead of 500-ing on the
  idempotency_key UNIQUE constraint

R3: extend SweepStalePendingPayments to till_sales card rows
- sweeps pending till_sales (online_square/in_person_card) past Square's ~24h
  key retention, closing the double-charge window for till sales
- swept rows logged with the same CRITICAL manual-reconciliation marker as the
  refund sweep

Webhook fail-closed: reject 503 when SQUARE_WEBHOOK_SIGNATURE_KEY unset, 403 on
bad signature (was: skip verification in dev)

Refund status resolution: refunds now resolve by Square status
(COMPLETED/PENDING/FAILED/REJECTED) instead of assuming completed; real error
codes (REFUND_AMOUNT_INVALID, PAYMENT_NOT_REFUNDABLE, REFUND_ALREADY_PENDING)
added to the definitive/processed classification

HTTP client: CreateCard key truncated to <=45 chars, device_options always sent
(env SQUARE_TERMINAL_DEVICE_ID fallback), processing_fee reads amount_money,
ListCards cursor loop, refund keys hashed to <=45 chars

Other fixes: payment/till/gift-card advisory-lock + FOR UPDATE asymmetries,
GetPaymentByID NULL scans, loyalty redemption lock, card upsert on conflict,
mock ccof: prefix parity, IsValidSquareCheckoutID for real Square IDs,
isAdminRequest defense-in-depth on all 6 admin payment handlers, webhook
signature docs, M8/L5 debug markers removed

Docs: README/FC/TM/Overview updated (22 jobs, 20 CRITICAL sites, 23-section
GDPR export, sweep jobs, webhook fail-closed); P11 plan marks remaining items
(sandbox smoke test, M-8 customer_id, saved-card key dedup trade-off) as
deferred with rationale; gap backlog pruned of completed items
This commit is contained in:
2026-08-22 00:34:49 +01:00
parent dcc70df75a
commit 7439fa86c1
30 changed files with 1239 additions and 184 deletions
+31 -16
View File
@@ -111,8 +111,20 @@ func makeWebhookRequest(body []byte, signature string, ctx context.Context) *htt
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) {
t.Parallel()
event := SquareWebhookEvent{
Type: "payment.updated",
EventID: "evt_payment_1",
@@ -120,7 +132,8 @@ func TestHandleSquareWebhook_PaymentUpdated(t *testing.T) {
Data: json.RawMessage(`{"id":"payment_1"}`),
}
body, _ := json.Marshal(event)
w := makeWebhookRequest(body, "", context.Background())
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())
}
@@ -130,7 +143,6 @@ func TestHandleSquareWebhook_PaymentUpdated(t *testing.T) {
}
func TestHandleSquareWebhook_RefundUpdated(t *testing.T) {
t.Parallel()
event := SquareWebhookEvent{
Type: "refund.updated",
EventID: "evt_refund_1",
@@ -138,14 +150,14 @@ func TestHandleSquareWebhook_RefundUpdated(t *testing.T) {
Data: json.RawMessage(`{"id":"refund_1"}`),
}
body, _ := json.Marshal(event)
w := makeWebhookRequest(body, "", context.Background())
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) {
t.Parallel()
event := SquareWebhookEvent{
Type: "dispute.created",
EventID: "evt_dispute_1",
@@ -153,14 +165,14 @@ func TestHandleSquareWebhook_DisputeCreated(t *testing.T) {
Data: json.RawMessage(`{"id":"dispute_1"}`),
}
body, _ := json.Marshal(event)
w := makeWebhookRequest(body, "", context.Background())
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) {
t.Parallel()
event := SquareWebhookEvent{
Type: "invoice.created",
EventID: "evt_unknown_1",
@@ -168,25 +180,27 @@ func TestHandleSquareWebhook_UnknownEventType(t *testing.T) {
Data: json.RawMessage(`{"id":"inv_1"}`),
}
body, _ := json.Marshal(event)
w := makeWebhookRequest(body, "", context.Background())
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) {
t.Parallel()
w := makeWebhookRequest([]byte(`{invalid json}`), "", context.Background())
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) {
t.Parallel()
// 600KB body exceeds the 512KB limit
largeBody := []byte(strings.Repeat("a", 600*1024))
w := makeWebhookRequest(largeBody, "", context.Background())
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())
}
@@ -236,14 +250,15 @@ func TestHandleSquareWebhook_NoSignatureWhenKeySet(t *testing.T) {
}
}
func TestHandleSquareWebhook_SignatureSkippedWhenKeyEmpty(t *testing.T) {
func TestHandleSquareWebhook_RejectedWhenKeyEmpty(t *testing.T) {
t.Setenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "")
body := []byte(`{"type":"payment.updated","event_id":"evt_1"}`)
// Bad signature but key is empty, so verification should be skipped
// 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.StatusOK {
t.Errorf("expected 200 when no key configured (dev stub), got %d. body: %s", w.Code, w.Body.String())
if w.Code != http.StatusServiceUnavailable {
t.Errorf("expected 503 when no key configured (fail-closed), got %d. body: %s", w.Code, w.Body.String())
}
}