package main import ( "bytes" "encoding/json" "io" "math" "net" "net/http" "strconv" "strings" "sync" "time" ) // Budgets for the credential-bearing auth routes. Client IPs are resolved with // clientIP, so they honour X-Forwarded-For only from TRUSTED_PROXIES. const ( authIPLimit = 30 authIPWindow = time.Minute loginFailureLimit = 10 loginFailureWindow = 15 * time.Minute // loginBodyLimit matches the body cap AuthGuard's login handler reads. loginBodyLimit = 128 * 1024 // rateLimiterMaxKeys bounds memory held for distinct keys. rateLimiterMaxKeys = 10000 ) // rateLimiter counts events per key in fixed windows. It lives in process, so // the budgets apply to one server instance. type rateLimiter struct { mu sync.Mutex limit int window time.Duration maxKeys int now func() time.Time counts map[string]*rateWindow } type rateWindow struct { start time.Time count int } func newRateLimiter(limit int, window time.Duration) *rateLimiter { return &rateLimiter{ limit: limit, window: window, maxKeys: rateLimiterMaxKeys, now: time.Now, counts: make(map[string]*rateWindow), } } // Blocked reports whether key has spent its budget in the current window, and // how long until that window ends. func (l *rateLimiter) Blocked(key string) (bool, time.Duration) { l.mu.Lock() defer l.mu.Unlock() now := l.now() window, ok := l.counts[key] if !ok || now.Sub(window.start) >= l.window || window.count < l.limit { return false, 0 } return true, window.start.Add(l.window).Sub(now) } // Hit counts one event for key in the current window. func (l *rateLimiter) Hit(key string) { l.mu.Lock() defer l.mu.Unlock() now := l.now() window, ok := l.counts[key] if !ok || now.Sub(window.start) >= l.window { if !ok && len(l.counts) >= l.maxKeys { l.evictLocked(now) } window = &rateWindow{start: now} l.counts[key] = window } window.count++ } // evictLocked drops expired windows. If every window is still live, it clears // the map rather than let memory grow without bound. That can reset budgets // under a flood of distinct keys, which is the cost of a bounded map. func (l *rateLimiter) evictLocked(now time.Time) { for key, window := range l.counts { if now.Sub(window.start) >= l.window { delete(l.counts, key) } } if len(l.counts) >= l.maxKeys { clear(l.counts) } } // writeRateLimited answers 429 with a Retry-After in whole seconds. func writeRateLimited(w http.ResponseWriter, retryAfter time.Duration) { seconds := int(math.Ceil(retryAfter.Seconds())) if seconds < 1 { seconds = 1 } w.Header().Set("Retry-After", strconv.Itoa(seconds)) writeJSONError(w, http.StatusTooManyRequests, "Too many attempts. Try again later.") } // authRateLimits holds the budgets for the auth routes. A fresh set is built // per route registration, so tests start with empty counters. type authRateLimits struct { trusted []*net.IPNet ip *rateLimiter failures *rateLimiter } func newAuthRateLimits(trusted []*net.IPNet) *authRateLimits { return &authRateLimits{ trusted: trusted, ip: newRateLimiter(authIPLimit, authIPWindow), failures: newRateLimiter(loginFailureLimit, loginFailureWindow), } } // perClient counts every request against the client's IP and refuses it once // the IP has spent its budget. Used on setup, TOTP and token regeneration. func (l *authRateLimits) perClient(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { key := clientIP(r, l.trusted) if blocked, retryAfter := l.ip.Blocked(key); blocked { writeRateLimited(w, retryAfter) return } l.ip.Hit(key) next.ServeHTTP(w, r) }) } // login applies two budgets. Every attempt counts against the client IP. Failed // attempts (401) count against the account named in the body, so guessing one // password is capped even when the attacker rotates addresses. func (l *authRateLimits) login(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { key := clientIP(r, l.trusted) if blocked, retryAfter := l.ip.Blocked(key); blocked { writeRateLimited(w, retryAfter) return } l.ip.Hit(key) account := loginAccount(r) if account != "" { if blocked, retryAfter := l.failures.Blocked(account); blocked { writeRateLimited(w, retryAfter) return } } recorder := &statusRecorder{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(recorder, r) if account != "" && recorder.status == http.StatusUnauthorized { l.failures.Hit(account) } }) } // loginAccount returns the normalised identifier from a login body and restores // the body for the handler. It returns "" when the body names no account. func loginAccount(r *http.Request) string { if r.Body == nil { return "" } raw, err := io.ReadAll(io.LimitReader(r.Body, loginBodyLimit)) _ = r.Body.Close() r.Body = io.NopCloser(bytes.NewReader(raw)) if err != nil { return "" } var input struct { Identifier string `json:"identifier"` Email string `json:"email"` } if json.Unmarshal(raw, &input) != nil { return "" } identifier := strings.TrimSpace(input.Identifier) if identifier == "" { identifier = strings.TrimSpace(input.Email) } return strings.ToLower(identifier) } // statusRecorder notes the status code a handler writes, so login can tell a // rejected password from other outcomes. type statusRecorder struct { http.ResponseWriter status int wroteHeader bool } func (w *statusRecorder) WriteHeader(status int) { if !w.wroteHeader { w.status = status w.wroteHeader = true } w.ResponseWriter.WriteHeader(status) } func (w *statusRecorder) Write(p []byte) (int, error) { if !w.wroteHeader { w.WriteHeader(http.StatusOK) } return w.ResponseWriter.Write(p) }