From f849b8a22cf3f1aeaf3e44e8042feca3461f15c3 Mon Sep 17 00:00:00 2001 From: Seth Hoenig Date: Wed, 2 Dec 2026 10:46:16 -0600 Subject: [PATCH] limits: create a rate limiter and middleware --- README.md | 23 +++++++ middles/ratelimit.go | 55 +++++++++++++++ middles/ratelimit_test.go | 132 ++++++++++++++++++++++++++++++++++++ ratelimit/ratelimit.go | 84 +++++++++++++++++++++++ ratelimit/ratelimit_test.go | 100 +++++++++++++++++++++++++++ 5 files changed, 394 insertions(+) create mode 100644 middles/ratelimit.go create mode 100644 middles/ratelimit_test.go create mode 100644 ratelimit/ratelimit.go create mode 100644 ratelimit/ratelimit_test.go diff --git a/README.md b/README.md index ddd2078..e8ba50b 100644 --- a/README.md +++ b/README.md @@ -264,6 +264,29 @@ handler := &middles.SecurityHTTP{ } ``` +The `RateLimitHTTP` middleware enforces a fixed-window rate limit on the +requests it serves, keyed by client IP by default. + +```go +handler := &middles.RateLimitHTTP{ + Limiter: ratelimit.New(33, time.Hour), // 33 requests per hour + H: router, +} +``` + +#### package webtools/ratelimit + +Provides a thread-safe fixed-window rate limiter for stopping +denial-of-service attacks, keyed by an arbitrary string such as a client IP +address. + +```go +limiter := ratelimit.New(33, time.Hour) +if !limiter.Allow(clientIP) { + // too many requests +} +``` + #### package webtools/httpclient Provides a sharable `http.Client` that sets sensible values for maintaining a diff --git a/middles/ratelimit.go b/middles/ratelimit.go new file mode 100644 index 0000000..6567301 --- /dev/null +++ b/middles/ratelimit.go @@ -0,0 +1,55 @@ +package middles + +import ( + "io" + "net/http" + "strconv" + "time" + + "cattlecloud.net/go/webtools" + "cattlecloud.net/go/webtools/ratelimit" +) + +// RateLimitHTTP is a middleware that enforces a fixed-window rate limit on the +// requests it serves, keyed per request. +// +// By default the key is the originating client IP address, resolved via +// webtools.Origins. Set Key to a custom function to derive a different key, +// for example an authenticated user identifier. +// +// When a request exceeds the limit it is not passed to H. By default the +// middleware responds with HTTP 429 Too Many Requests, a Retry-After header +// set to the limiter window, and a plain text body. Set Reject to a custom +// handler to control that response instead. +type RateLimitHTTP struct { + Limiter *ratelimit.Limiter + Key func(*http.Request) string + Reject http.Handler + H http.Handler +} + +func (rl *RateLimitHTTP) ServeHTTP(w http.ResponseWriter, r *http.Request) { + key := webtools.Origins(r).From() + if rl.Key != nil { + key = rl.Key(r) + } + + if rl.Limiter.Allow(key) { + rl.H.ServeHTTP(w, r) + return + } + + if rl.Reject != nil { + rl.Reject.ServeHTTP(w, r) + return + } + + reject(w, rl.Limiter.Window()) +} + +func reject(w http.ResponseWriter, window time.Duration) { + webtools.SetContentType(w, webtools.ContentTypeText) + w.Header().Set("Retry-After", strconv.Itoa(int(window.Seconds()))) + w.WriteHeader(http.StatusTooManyRequests) + _, _ = io.WriteString(w, "too many requests") +} diff --git a/middles/ratelimit_test.go b/middles/ratelimit_test.go new file mode 100644 index 0000000..29a30f0 --- /dev/null +++ b/middles/ratelimit_test.go @@ -0,0 +1,132 @@ +package middles + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "cattlecloud.net/go/webtools/ratelimit" + "github.com/shoenig/test/must" +) + +func TestRateLimitHTTP_Allows(t *testing.T) { + t.Parallel() + + run := new(atomic.Bool) + rl := &RateLimitHTTP{ + Limiter: ratelimit.New(1, time.Hour), + H: http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { + run.Store(true) + }), + } + + w := httptest.NewRecorder() + r, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + r.RemoteAddr = "203.0.113.7:1234" + rl.ServeHTTP(w, r) + + must.Eq(t, 200, w.Code) + must.True(t, run.Load()) +} + +func TestRateLimitHTTP_DefaultReject(t *testing.T) { + t.Parallel() + + run := new(atomic.Bool) + rl := &RateLimitHTTP{ + Limiter: ratelimit.New(1, time.Hour), + H: http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { + run.Store(true) + }), + } + + // first request consumes the single allowed attempt + r, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + r.RemoteAddr = "203.0.113.7:1234" + rl.ServeHTTP(httptest.NewRecorder(), r) + + // second request is rejected + w := httptest.NewRecorder() + rl.ServeHTTP(w, r) + + must.Eq(t, http.StatusTooManyRequests, w.Code) + must.Eq(t, "3600", w.Header().Get("Retry-After")) + must.Eq(t, "too many requests", w.Body.String()) + must.True(t, run.Load()) +} + +func TestRateLimitHTTP_CustomReject(t *testing.T) { + t.Parallel() + + run := new(atomic.Bool) + rejected := new(atomic.Bool) + rl := &RateLimitHTTP{ + Limiter: ratelimit.New(1, time.Hour), + Reject: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + rejected.Store(true) + w.WriteHeader(http.StatusTeapot) + }), + H: http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { + run.Store(true) + }), + } + + r, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + r.RemoteAddr = "203.0.113.7:1234" + + rl.ServeHTTP(httptest.NewRecorder(), r) + w := httptest.NewRecorder() + rl.ServeHTTP(w, r) + + must.Eq(t, http.StatusTeapot, w.Code) + must.True(t, rejected.Load()) + must.True(t, run.Load()) +} + +func TestRateLimitHTTP_CustomKey(t *testing.T) { + t.Parallel() + + rl := &RateLimitHTTP{ + Limiter: ratelimit.New(1, time.Hour), + Key: func(r *http.Request) string { return r.URL.Path }, + H: http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}), + } + + // same RemoteAddr but distinct keys; each is allowed once + mk := func(path string) *http.Request { + r, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, path, nil) + r.RemoteAddr = "203.0.113.7:1234" + return r + } + + rl.ServeHTTP(httptest.NewRecorder(), mk("/one")) + rl.ServeHTTP(httptest.NewRecorder(), mk("/two")) + + // a second request to /one is now over its independent limit + w := httptest.NewRecorder() + rl.ServeHTTP(w, mk("/one")) + must.Eq(t, http.StatusTooManyRequests, w.Code) +} + +func TestRateLimitHTTP_DefaultKeyIP(t *testing.T) { + t.Parallel() + + rl := &RateLimitHTTP{ + Limiter: ratelimit.New(1, time.Hour), + H: http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}), + } + + mk := func(ip string) *http.Request { + r, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil) + r.RemoteAddr = ip + ":1234" + return r + } + + // distinct IPs are independent + rl.ServeHTTP(httptest.NewRecorder(), mk("203.0.113.7")) + w := httptest.NewRecorder() + rl.ServeHTTP(w, mk("203.0.113.8")) + must.Eq(t, 200, w.Code) +} diff --git a/ratelimit/ratelimit.go b/ratelimit/ratelimit.go new file mode 100644 index 0000000..4e1cc1b --- /dev/null +++ b/ratelimit/ratelimit.go @@ -0,0 +1,84 @@ +// Package ratelimit provides a fixed-window rate limiter for stopping +// denial-of-service attacks, keyed by an arbitrary string such as a client IP +// address. +package ratelimit + +import ( + "sync" + "time" + + "github.com/shoenig/lang" +) + +// maxBuckets is the number of distinct keys to keep track of before sweeping +// the expired entries. +const maxBuckets = 4096 + +// Limiter enforces a fixed-window rate limit keyed by some string, typically +// an IP address. +type Limiter struct { + limit int + window time.Duration + now func() time.Time + + lock *sync.Mutex + buckets map[string]*bucket +} + +// bucket counts the attempts observed within a single fixed window +type bucket struct { + count int + start time.Time +} + +// New returns a Limiter permitting at most limit attempts per window. +func New(limit int, window time.Duration) *Limiter { + return &Limiter{ + limit: limit, + window: window, + now: time.Now, + lock: new(sync.Mutex), + buckets: make(map[string]*bucket), + } +} + +// Allow records an attempt for key and reports whether that attempt is within +// the limit for the current window. +func (l *Limiter) Allow(key string) bool { + now := l.now() + + return lang.CriticalGet(l.lock, func() bool { + l.sweep(now) + + b, ok := l.buckets[key] + if !ok || now.Sub(b.start) >= l.window { + b = &bucket{start: now} + l.buckets[key] = b + } + + b.count++ + + return b.count <= l.limit + }) +} + +// Window returns the duration over which limit attempts are counted. +func (l *Limiter) Window() time.Duration { + return l.window +} + +// sweep removes expired buckets once the map grows past maxBuckets. The +// sweep is lazy: it only runs when the map is already large, so the common +// case does no extra work +func (l *Limiter) sweep(now time.Time) { + if len(l.buckets) <= maxBuckets { + return + } + + // rare O(n) sweep; purges stale buckets + for key, b := range l.buckets { + if now.Sub(b.start) >= l.window { + delete(l.buckets, key) + } + } +} diff --git a/ratelimit/ratelimit_test.go b/ratelimit/ratelimit_test.go new file mode 100644 index 0000000..a618289 --- /dev/null +++ b/ratelimit/ratelimit_test.go @@ -0,0 +1,100 @@ +package ratelimit + +import ( + "strconv" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/shoenig/test/must" +) + +func TestAllow_WithinLimit(t *testing.T) { + t.Parallel() + + l := New(3, time.Hour) + + must.True(t, l.Allow("ip")) + must.True(t, l.Allow("ip")) + must.True(t, l.Allow("ip")) + must.False(t, l.Allow("ip")) +} + +func TestAllow_WindowResets(t *testing.T) { + t.Parallel() + + l := New(2, time.Hour) + now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + l.now = func() time.Time { return now } + + must.True(t, l.Allow("ip")) + must.True(t, l.Allow("ip")) + must.False(t, l.Allow("ip")) + + // advance past the window boundary; the count must reset + now = now.Add(time.Hour + time.Second) + must.True(t, l.Allow("ip")) + must.True(t, l.Allow("ip")) + must.False(t, l.Allow("ip")) +} + +func TestAllow_KeysIndependent(t *testing.T) { + t.Parallel() + + l := New(1, time.Hour) + + must.True(t, l.Allow("one")) + must.True(t, l.Allow("two")) + must.False(t, l.Allow("one")) +} + +func TestAllow_SweepsExpired(t *testing.T) { + t.Parallel() + + l := New(1, time.Hour) + now := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + l.now = func() time.Time { return now } + + // fill the map past the sweep threshold with distinct keys + for i := 0; i < maxBuckets+1; i++ { + must.True(t, l.Allow("ip-"+strconv.Itoa(i))) + } + must.Eq(t, maxBuckets+1, len(l.buckets)) + + // once the window elapses the next Allow sweeps all expired buckets + now = now.Add(2 * time.Hour) + must.True(t, l.Allow("fresh")) + must.Eq(t, 1, len(l.buckets)) +} + +func TestAllow_Concurrent(t *testing.T) { + t.Parallel() + + const limit = 100 + l := New(limit, time.Hour) + + const workers = 1000 + var allowed atomic.Int64 + + var wg sync.WaitGroup + wg.Add(workers) + for range workers { + go func() { + defer wg.Done() + if l.Allow("ip") { + allowed.Add(1) + } + }() + } + wg.Wait() + + must.Eq(t, int64(limit), allowed.Load()) +} + +func TestWindow(t *testing.T) { + t.Parallel() + + l := New(3, 42*time.Second) + must.Eq(t, 42*time.Second, l.Window()) +}