diff --git a/api/internal/adminhandler/ratelimit.go b/api/internal/adminhandler/ratelimit.go index 6c5971e..80dfe51 100644 --- a/api/internal/adminhandler/ratelimit.go +++ b/api/internal/adminhandler/ratelimit.go @@ -8,10 +8,11 @@ import ( // rateLimiter is a simple fixed-window per-key limiter used to throttle // anonymous public submissions (basic anti-spam; captcha can be added later). type rateLimiter struct { - mu sync.Mutex - hits map[string][]time.Time - limit int - window time.Duration + mu sync.Mutex + hits map[string][]time.Time + limit int + window time.Duration + lastPrune time.Time } func newRateLimiter(limit int, window time.Duration) *rateLimiter { @@ -26,12 +27,19 @@ func (r *rateLimiter) allow(key string) bool { r.mu.Lock() defer r.mu.Unlock() - kept := r.hits[key][:0] - for _, t := range r.hits[key] { - if t.After(cutoff) { - kept = append(kept, t) + if now.Sub(r.lastPrune) > r.window { + for expiredKey, hits := range r.hits { + kept := pruneRateLimitHits(hits, cutoff) + if len(kept) == 0 { + delete(r.hits, expiredKey) + } else { + r.hits[expiredKey] = kept + } } + r.lastPrune = now } + + kept := pruneRateLimitHits(r.hits[key], cutoff) if len(kept) >= r.limit { r.hits[key] = kept return false @@ -39,3 +47,13 @@ func (r *rateLimiter) allow(key string) bool { r.hits[key] = append(kept, now) return true } + +func pruneRateLimitHits(hits []time.Time, cutoff time.Time) []time.Time { + kept := hits[:0] + for _, hit := range hits { + if hit.After(cutoff) { + kept = append(kept, hit) + } + } + return kept +} diff --git a/api/internal/adminhandler/ratelimit_test.go b/api/internal/adminhandler/ratelimit_test.go new file mode 100644 index 0000000..32cd7c0 --- /dev/null +++ b/api/internal/adminhandler/ratelimit_test.go @@ -0,0 +1,31 @@ +package adminhandler + +import ( + "testing" + "time" +) + +func TestRateLimiterPrunesExpiredKeysAndPreservesLiveLimits(t *testing.T) { + window := time.Minute + now := time.Now() + limiter := newRateLimiter(2, window) + limiter.hits["expired"] = []time.Time{now.Add(-2 * window)} + limiter.hits["live"] = []time.Time{now.Add(-time.Second)} + limiter.lastPrune = now.Add(-2 * window) + + if !limiter.allow("live") { + t.Fatal("allow rejected a live key below its limit") + } + if _, ok := limiter.hits["expired"]; ok { + t.Fatal("expired key was not pruned") + } + if got := len(limiter.hits["live"]); got != 2 { + t.Fatalf("live key hit count = %d, want 2", got) + } + if limiter.allow("live") { + t.Fatal("allow accepted a live key at its limit") + } + if got := len(limiter.hits["live"]); got != 2 { + t.Fatalf("live key hit count after rejection = %d, want 2", got) + } +}