Files
Crussell/backend/mw/ratelimit.go
T
popertots fe88f2084d 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.
2026-08-22 00:34:50 +01:00

199 lines
5.9 KiB
Go

//go:build !dev || test
package mw
import (
"crussell/clock"
"fmt"
"net/http"
"time"
)
func NewRateLimiter(limit int, window time.Duration) *RateLimiter {
rl := &RateLimiter{
requests: make(map[string][]time.Time),
limit: limit,
window: window,
}
registerLimiter(rl)
return rl
}
func (rl *RateLimiter) Allow(key string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := clock.Now()
windowStart := now.Add(-rl.window)
var valid []time.Time
for _, t := range rl.requests[key] {
if t.After(windowStart) {
valid = append(valid, t)
}
}
if len(valid) >= rl.limit {
rl.requests[key] = valid
return false
}
rl.requests[key] = append(valid, now)
return true
}
func NewProgressiveRateLimiter() *ProgressiveRateLimiter {
return &ProgressiveRateLimiter{
requests: make(map[string]*ipProgressiveState),
}
}
// Check returns the delay in milliseconds. Returns 0 if no delay needed.
// Strategy:
// - Count requests in last 5 seconds (burst): allow up to 30
// - Count requests in last 60 seconds (sustained): allow up to 60
// - Only delay when BOTH windows are exceeded (high sustained rate with recent bursts)
// - Progressive: once throttled, delay increases with sustained rate
func (prl *ProgressiveRateLimiter) Check(ip string) (delayMs int) {
prl.mu.Lock()
defer prl.mu.Unlock()
now := clock.Now()
state, exists := prl.requests[ip]
if !exists {
prl.requests[ip] = &ipProgressiveState{
timestamps: []time.Time{now},
}
return 0
}
state.timestamps = append(state.timestamps, now)
burstCutoff := now.Add(-5 * time.Second)
burstCount := 0
for _, t := range state.timestamps {
if t.After(burstCutoff) {
burstCount++
}
}
sustainedCutoff := now.Add(-60 * time.Second)
sustainedCount := 0
for _, t := range state.timestamps {
if t.After(sustainedCutoff) {
sustainedCount++
}
}
if burstCount <= 30 && sustainedCount <= 120 {
return 0
}
// Progressive delay based on how far over the sustained limit they are
// Rate = requests per minute
switch {
case sustainedCount <= 140:
return 500 // 500ms - scraping but not too aggressively
case sustainedCount <= 200:
return 2000 // 2s - moderate spam
case sustainedCount <= 300:
return 5000 // 5s - heavy spam
default:
return 10000 // 10s - abuse
}
}
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 {
time.Sleep(time.Duration(delay) * time.Millisecond)
w.Header().Set("X-RateLimit-Delay", fmt.Sprintf("%d", delay))
}
next.ServeHTTP(w, r)
})
}
// RateLimit middleware - limits requests per IP
func RateLimit(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) {
ip := clientIP(r)
if !limiter.Allow(ip) {
RespondJSON(w, http.StatusTooManyRequests, map[string]string{"error": "Rate limit exceeded"})
return
}
next.ServeHTTP(w, r)
})
}
}
// RateLimitByUserAndIP limits requests per authenticated user + client IP. The
// 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
// 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.
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)
if userID, ok := GetUserID(r.Context()); ok && userID != "" {
key = userID + "|" + key
}
if !limiter.Allow(key) {
RespondJSON(w, http.StatusTooManyRequests, map[string]string{"error": "Rate limit exceeded"})
return
}
next.ServeHTTP(w, r)
})
}
}
// 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)
})
}
}
// 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) }