Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
55 changes: 55 additions & 0 deletions middles/ratelimit.go
Original file line number Diff line number Diff line change
@@ -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")
}
132 changes: 132 additions & 0 deletions middles/ratelimit_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
84 changes: 84 additions & 0 deletions ratelimit/ratelimit.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
Loading