-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathratelimit_test.go
More file actions
222 lines (186 loc) · 6.17 KB
/
ratelimit_test.go
File metadata and controls
222 lines (186 loc) · 6.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package api_test
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/bjaus/api"
)
func TestRateLimit(t *testing.T) {
t.Parallel()
tests := map[string]struct {
rate float64
burst int
numReqs int
wantOK int
wantLimited int
}{
"requests within rate succeed": {
rate: 100,
burst: 10,
numReqs: 5,
wantOK: 5,
wantLimited: 0,
},
"requests exceeding rate get 429": {
rate: 1,
burst: 1,
numReqs: 5,
wantOK: 1,
wantLimited: 4,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
t.Parallel()
mw := api.RateLimit(api.RateLimitConfig{
Rate: tc.rate,
Burst: tc.burst,
})
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
okCount := 0
limitedCount := 0
for range tc.numReqs {
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
switch resp.StatusCode {
case http.StatusOK:
okCount++
case http.StatusTooManyRequests:
limitedCount++
assert.NotEmpty(t, resp.Header.Get("Retry-After"), "Retry-After header should be set")
}
require.NoError(t, resp.Body.Close())
}
assert.Equal(t, tc.wantOK, okCount, "expected OK responses")
assert.Equal(t, tc.wantLimited, limitedCount, "expected rate-limited responses")
})
}
}
func TestRateLimit_custom_key_func(t *testing.T) {
t.Parallel()
mw := api.RateLimit(api.RateLimitConfig{
Rate: 1,
Burst: 1,
KeyFunc: func(r *http.Request) string {
return r.Header.Get("X-User-ID")
},
})
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
// User A makes 2 requests - second should be limited.
reqA1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/", nil)
require.NoError(t, err)
reqA1.Header.Set("X-User-ID", "user-a")
respA1, err := http.DefaultClient.Do(reqA1)
require.NoError(t, err)
require.NoError(t, respA1.Body.Close())
assert.Equal(t, http.StatusOK, respA1.StatusCode)
reqA2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/", nil)
require.NoError(t, err)
reqA2.Header.Set("X-User-ID", "user-a")
respA2, err := http.DefaultClient.Do(reqA2)
require.NoError(t, err)
require.NoError(t, respA2.Body.Close())
assert.Equal(t, http.StatusTooManyRequests, respA2.StatusCode)
// User B should still get through because different key.
reqB, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/", nil)
require.NoError(t, err)
reqB.Header.Set("X-User-ID", "user-b")
respB, err := http.DefaultClient.Do(reqB)
require.NoError(t, err)
require.NoError(t, respB.Body.Close())
assert.Equal(t, http.StatusOK, respB.StatusCode)
}
func TestRateLimit_default_keyfunc_splithost_error(t *testing.T) {
t.Parallel()
mw := api.RateLimit(api.RateLimitConfig{
Rate: 100,
Burst: 10,
})
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
// Call handler directly with a RemoteAddr that has no port (causes SplitHostPort error).
rec := httptest.NewRecorder()
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil)
require.NoError(t, err)
req.RemoteAddr = "10.0.0.1" // no port
handler.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
}
func TestRateLimit_cleanup_expired_limiters(t *testing.T) {
t.Parallel()
mw := api.RateLimit(api.RateLimitConfig{
Rate: 100,
Burst: 100,
CleanupInterval: time.Millisecond,
MaxIdle: time.Millisecond,
})
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
// First request creates a limiter entry.
req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/", nil)
require.NoError(t, err)
resp1, err := http.DefaultClient.Do(req1)
require.NoError(t, err)
require.NoError(t, resp1.Body.Close())
assert.Equal(t, http.StatusOK, resp1.StatusCode)
// Wait for entries to become idle.
time.Sleep(5 * time.Millisecond)
// Second request triggers cleanup of the expired entry and creates a new one.
req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/", nil)
require.NoError(t, err)
resp2, err := http.DefaultClient.Do(req2)
require.NoError(t, err)
require.NoError(t, resp2.Body.Close())
assert.Equal(t, http.StatusOK, resp2.StatusCode)
}
func TestRateLimit_custom_on_limit(t *testing.T) {
t.Parallel()
mw := api.RateLimit(api.RateLimitConfig{
Rate: 1,
Burst: 1,
OnLimit: func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusServiceUnavailable)
//nolint:errcheck,gosec
w.Write([]byte(`{"error":"custom limit"}`))
},
})
handler := mw(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
// First request should pass.
req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/", nil)
require.NoError(t, err)
resp1, err := http.DefaultClient.Do(req1)
require.NoError(t, err)
require.NoError(t, resp1.Body.Close())
assert.Equal(t, http.StatusOK, resp1.StatusCode)
// Second request should trigger the custom OnLimit handler.
req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, srv.URL+"/", nil)
require.NoError(t, err)
resp2, err := http.DefaultClient.Do(req2)
require.NoError(t, err)
defer func() { require.NoError(t, resp2.Body.Close()) }()
assert.Equal(t, http.StatusServiceUnavailable, resp2.StatusCode)
assert.Equal(t, "application/json", resp2.Header.Get("Content-Type"))
}