fix: review-loop B — adversarial findings (sweep auto-refund, admin clamp, 2FA real challenge, opaque refresh tokens, gated client IP, GBP pence)

Loop B aggressive adversarial round (3 attack agents) + fix + secondary + verification:
- CRITICAL: sweep replay auto-refunds provably-created-later duplicate charges (gated on parseable CreatedAt); 22h legitimate-retry window == 22h sweep cutoff (no dead zone)
- HIGH: admin Take Payment clamps to remaining obligation (cash/giftcard/saved-card/terminal); no unintended tip from overflow; campaign credit against remaining
- HIGH: /api/services/eligible-for/{id} requires auth + owner-or-admin (DOB/age + patch-test health-data leak closed)
- HIGH: opaque refresh-token rotation (login/refresh return {token, jti, refreshToken}; refresh REQUIRES opaque token; single-use rotation; logout revokes; access token rejected at refresh)
- HIGH: saved-card charges require a REAL 2FA verification code (B6/B10) — backend gate on all 8 charge paths + shared TwoFactorCodeInput frontend component on all 7 surfaces; 2FA gate is no longer setup-flag-only
- MEDIUM: ungated CF-Connecting-IP in reserve/admin_reserve gated via exported mw.ClientIP; 2FA limiter keyed on userID alone (no header-rotation bypass); ChangePassword actually revokes JTI + refresh tokens; 2FA setup mint cooldown + persistent failed-attempt counter; campaign redemption race surfaces campaign_fully_redeemed
- Terminal saved-card VAT applied (was under-collected); age-guard reconcile failures notify; isWeakJWTSecret entropy gate; gift-card redeem per-card counter + per-user limiter; webhook signature key startup validation
- NEW internal/twofa package (single source of truth breaking the payments<->user import cycle); consolidation of duplicate 2FA hash/verify
- Frontend: refresh-token storage + rotation, TwoFactorCodeInput component, amountPaidPence in admin modal, B5/B6/B10 contract wiring; 70 frontend tests
- Tests: loop_b_fixes_test.go, internal/twofa tests, updated auth/services/profile/twofa/mw tests

All 26 backend packages pass (incl. internal/twofa); frontend 70/70 + build clean; env-docs 41/41.
This commit is contained in:
2026-08-22 00:34:50 +01:00
parent faceb9809c
commit fe88f2084d
55 changed files with 4180 additions and 971 deletions
+35 -31
View File
@@ -5,11 +5,8 @@ package mw
import (
"crussell/clock"
"fmt"
"net"
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
)
func NewRateLimiter(limit int, window time.Duration) *RateLimiter {
@@ -140,17 +137,17 @@ func RateLimit(limit int, window time.Duration) func(http.Handler) http.Handler
// key combines the authenticated userID (mw.UserIDKey, injected by RequireAuth)
// with the derived client IP, so a per-IP budget can never collapse into a
// single GLOBAL bucket when the backend sits behind a proxy that does not set
// TRUST_PROXY_HEADERS=true: without that flag clientIP() keys every request on
// TRUST_PROXY_HEADERS=true: without that flag ClientIP keys every request on
// RemoteAddr = the proxy's IP, so one account holder could otherwise exhaust
// the shared budget and permanently 429 the whole surface for everyone. With
// the userID in the key each account gets its own independent budget per IP.
// When no userID is present (unauthenticated path) the key falls back to
// clientIP alone, matching RateLimit's behaviour.
// ClientIP alone, matching RateLimit's behaviour.
func RateLimitByUserAndIP(limit int, window time.Duration) func(http.Handler) http.Handler {
limiter := NewRateLimiter(limit, window)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := clientIP(r)
key := ClientIP(r)
if userID, ok := GetUserID(r.Context()); ok && userID != "" {
key = userID + "|" + key
}
@@ -165,30 +162,37 @@ func RateLimitByUserAndIP(limit int, window time.Duration) func(http.Handler) ht
}
}
// clientIP derives the per-client rate-limit key. Priority:
// 1. CF-Connecting-IP header — honored ONLY when TRUST_PROXY_HEADERS=true
// (see trustProxyHeaders). A trusted edge (Cloudflare, or nginx whose
// real_ip module validated it against the set_real_ip_from ranges) has
// already overwritten it with the real client IP, so it is unspoofable
// there. Ignored by default because an origin-exposed backend must never
// trust a client-controlled value.
// 2. middleware.GetClientIP(r.Context()) — the X-Real-IP value nginx sets
// from $remote_addr, captured by middleware.ClientIPFromHeader("X-Real-IP")
// in main.go. That middleware is registered only when
// TRUST_PROXY_HEADERS=true, so it too is trusted solely behind a proxy.
// 3. net.SplitHostPort(r.RemoteAddr) / r.RemoteAddr fallback — the actual
// TCP peer; the only key source usable when the backend is origin-exposed.
func clientIP(r *http.Request) string {
if trustProxyHeaders {
if ip := r.Header.Get("CF-Connecting-IP"); ip != "" {
return ip
}
// RateLimitByUser limits requests per authenticated user ID ALONE, dropping the
// IP component entirely. This is the B8 safeguard for the 2FA surface (and the
// B16 gift-card redeem budget): when the IP is part of the key, a client that
// can rotate its source IP — or that sits behind a proxy which echoes a
// client-supplied CF-Connecting-IP when TRUST_PROXY_HEADERS is misconfigured
// true — mints a fresh bucket per IP for the SAME account, collapsing the
// per-account budget. Keying on the userID alone guarantees exactly one budget
// per account regardless of IP rotation or proxy configuration. When no userID
// is present (unauthenticated path) the key falls back to ClientIP so the
// surface still has a default budget.
func RateLimitByUser(limit int, window time.Duration) func(http.Handler) http.Handler {
limiter := NewRateLimiter(limit, window)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key, ok := GetUserID(r.Context())
if !ok || key == "" {
key = ClientIP(r)
}
if !limiter.Allow(key) {
RespondJSON(w, http.StatusTooManyRequests, map[string]string{"error": "Rate limit exceeded"})
return
}
next.ServeHTTP(w, r)
})
}
if ip := middleware.GetClientIP(r.Context()); ip != "" {
return ip
}
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil && ip != "" {
return ip
}
return r.RemoteAddr
}
// clientIP derives the per-client rate-limit key. It is a thin alias of the
// exported ClientIP (which lives in ratelimit_shared.go so it is available in
// every build configuration), kept for backward compatibility with existing
// callers.
func clientIP(r *http.Request) string { return ClientIP(r) }