fix: round-2 loop-A fresh review (503c326 baseline) — B1 replay cap, A6 discount record, 2FA reissue+cooldown, notification flood, lockout saturation, VAT/refund-status consolidation

Round 2 Loop A fresh money/security/dup-mod review. 23 findings fixed:

MONEY:
- CRITICAL: B1 duplicate auto-refund gains an attempt cap (b1_attempts col, cap 3) —
  a rejected auto-refund no longer re-replays the expired key every sweep run
  (which minted a stacking unauthorized charge each time); FAILED-webhook
  demotion respects the cap; never re-replay a key whose B1 refund failed
- HIGH: A6 deposit_covered_by_discount skip path now APPLIES the eligible
  campaign discount rows immediately (capped) instead of skipping with no
  discount recorded — no more promised-discount-not-recorded overcharge
- MEDIUM: 2FA code burned by the SAVE gate is re-issued on failed
  new-card+save_card charges (re-issue guard now covers req.SaveCard)
- LOW: GetBookingPaymentSummary excludes tip rows from paidAmount (remaining
  now matches the authoritative tip-excluded balance)

SECURITY:
- MEDIUM: unacknowledged CRITICAL admin-notification flood capped (global cap
  on critical_payment_log + refresh_token_reuse rows)
- MEDIUM: 2FA reissue no longer bypasses the mint cooldown (Check no longer
  clears LastMintAt on gate-verify; cleared on terminal charge success)
- MEDIUM: twofa.StateFor map-saturation returns a shared permanently-locked
  state instead of a fresh 5-guess budget per request
- MEDIUM: ProgressiveRateLimit rejects 429 past maxProgressiveSleepDelayMs
  instead of sleeping unboundedly; login bcrypt concurrency semaphore added
- LOW: loginInProgress 409->429; webhook key-set/URL-unset startup check;
  email-verification per-user attempt counter

DUP/MOD:
- formatCurrency single source (frontend format.ts, 7 files consolidated);
  SquareRefundStatusToLocal single source (errors.go, all sites); admin
  audit-log helper dedup; SCA retry model unified (proactive on all 6
  surfaces); buyDailyTotal/daily-cap mirror via backend; lock TTL from
  backend; generateUUID at all card-form sites; magic numbers named
  (defaultPostgresHost, epsilon, fee constants); admin CASH + gift-card
  terminal charges now audited; DAV_SKIP_INIT documented in manuals

Verified: 26/26 dev + 24/24 prod (GO_TESTING=1, the CI condition), both vet
tags, frontend tests+build, env-docs 42/42.
This commit is contained in:
2026-08-22 00:34:50 +01:00
parent 4e64e32f09
commit 3866cc5963
36 changed files with 2032 additions and 719 deletions
+17 -1
View File
@@ -102,12 +102,28 @@ func (prl *ProgressiveRateLimiter) Check(ip string) (delayMs int) {
}
}
// maxProgressiveSleepDelayMs is the largest delay the progressive per-IP
// limiter still absorbs by sleeping. Beyond it the request is rejected 429
// immediately instead (Round 2 Loop A finding 4a): sleeping 5-10s ties up a
// goroutine per throttled request while the client keeps hammering, so one
// client can stack many sleeping goroutines in front of the bcrypt wall on
// /login and /register. The small progressive tiers (500ms / 2s) are
// unchanged.
const maxProgressiveSleepDelayMs = 2000
func ProgressiveRateLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := clientIP(r)
delay := globalProgressiveLimiter.Check(ip)
if delay > 0 {
switch {
case delay > maxProgressiveSleepDelayMs:
// Far past the sustained budget — reject now instead of parking a
// goroutine for 5-10s. The rejection is a clean 429; the client
// retries after the burst window lapses.
RespondJSON(w, http.StatusTooManyRequests, map[string]string{"error": "Rate limit exceeded"})
return
case delay > 0:
time.Sleep(time.Duration(delay) * time.Millisecond)
w.Header().Set("X-RateLimit-Delay", fmt.Sprintf("%d", delay))
}
+42
View File
@@ -651,3 +651,45 @@ func TestProgressiveRateLimiter_DelayEscalatesWithSustainedRate(t *testing.T) {
}
}
}
// TestProgressiveRateLimit_RejectsBeyondSleepCap pins finding 4a: once the
// computed delay exceeds maxProgressiveSleepDelayMs (2s), the middleware
// rejects the request 429 immediately instead of sleeping a goroutine for
// 5-10s (a per-client goroutine-parking amplifier in front of bcrypt). The
// small progressive tiers (500ms / 2s) still sleep.
func TestProgressiveRateLimit_RejectsBeyondSleepCap(t *testing.T) {
globalProgressiveLimiter.mu.Lock()
saved := globalProgressiveLimiter.requests
globalProgressiveLimiter.requests = make(map[string]*ipProgressiveState)
globalProgressiveLimiter.mu.Unlock()
t.Cleanup(func() {
globalProgressiveLimiter.mu.Lock()
globalProgressiveLimiter.requests = saved
globalProgressiveLimiter.mu.Unlock()
})
// Seed the 10s abuse tier (sustained > 300) for this IP.
seedProgressiveTimestamps(t, globalProgressiveLimiter, "198.51.100.99", 31, 320)
nextCalled := false
handler := ProgressiveRateLimit(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nextCalled = true
w.WriteHeader(http.StatusOK)
}))
req := httptest.NewRequest(http.MethodPost, "/login", nil)
req.RemoteAddr = "198.51.100.99:1234"
w := httptest.NewRecorder()
start := time.Now()
handler.ServeHTTP(w, req)
if nextCalled {
t.Error("next handler must NOT be called when the delay exceeds the sleep cap")
}
if w.Code != http.StatusTooManyRequests {
t.Errorf("expected 429, got %d", w.Code)
}
if elapsed := time.Since(start); elapsed >= 5*time.Second {
t.Errorf("the 5-10s tiers must reject immediately, not sleep (took %s)", elapsed)
}
}