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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
|
package ratelimit
import (
"context"
"testing"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func TestBasicRateLimit(t *testing.T) {
config := &Config{
RequestsPerSecond: 10,
BurstSize: 10,
}
limiter := New(config)
defer limiter.Stop()
identifier := "test-user"
method := "/test.Service/Method"
// First 10 requests should succeed (burst)
for i := 0; i < 10; i++ {
if !limiter.Allow(identifier, method) {
t.Errorf("request %d should be allowed", i)
}
}
// 11th request should be denied (burst exhausted)
if limiter.Allow(identifier, method) {
t.Error("request 11 should be denied")
}
// Wait for tokens to refill
time.Sleep(150 * time.Millisecond)
// Should allow 1 more request (1 token refilled)
if !limiter.Allow(identifier, method) {
t.Error("request after refill should be allowed")
}
}
func TestPerUserLimits(t *testing.T) {
config := &Config{
RequestsPerSecond: 10,
BurstSize: 10,
}
limiter := New(config)
defer limiter.Stop()
method := "/test.Service/Method"
// Different users should have independent limits
user1 := "user1"
user2 := "user2"
// Exhaust user1's quota
for i := 0; i < 10; i++ {
limiter.Allow(user1, method)
}
// User1 should be denied
if limiter.Allow(user1, method) {
t.Error("user1 should be rate limited")
}
// User2 should still be allowed
if !limiter.Allow(user2, method) {
t.Error("user2 should not be rate limited")
}
}
func TestMethodSpecificLimits(t *testing.T) {
config := &Config{
RequestsPerSecond: 10,
BurstSize: 10,
MethodLimits: map[string]MethodLimit{
"/test.Service/StrictMethod": {
RequestsPerSecond: 2,
BurstSize: 2,
},
},
}
limiter := New(config)
defer limiter.Stop()
identifier := "test-user"
// Regular method should allow 10 requests
regularMethod := "/test.Service/RegularMethod"
for i := 0; i < 10; i++ {
if !limiter.Allow(identifier, regularMethod) {
t.Errorf("regular method request %d should be allowed", i)
}
}
// Strict method should only allow 2 requests
strictMethod := "/test.Service/StrictMethod"
for i := 0; i < 2; i++ {
if !limiter.Allow(identifier, strictMethod) {
t.Errorf("strict method request %d should be allowed", i)
}
}
// 3rd request should be denied
if limiter.Allow(identifier, strictMethod) {
t.Error("strict method request 3 should be denied")
}
}
func TestUserSpecificLimits(t *testing.T) {
config := &Config{
RequestsPerSecond: 10,
BurstSize: 10,
UserLimits: map[string]UserLimit{
"vip-user": {
RequestsPerSecond: 100,
BurstSize: 100,
},
},
}
limiter := New(config)
defer limiter.Stop()
method := "/test.Service/Method"
// Regular user should be limited to 10
regularUser := "regular-user"
for i := 0; i < 10; i++ {
limiter.Allow(regularUser, method)
}
if limiter.Allow(regularUser, method) {
t.Error("regular user should be rate limited")
}
// VIP user should allow 100
vipUser := "vip-user"
for i := 0; i < 100; i++ {
if !limiter.Allow(vipUser, method) {
t.Errorf("vip user request %d should be allowed", i)
}
}
}
func TestSkipMethods(t *testing.T) {
config := &Config{
RequestsPerSecond: 1,
BurstSize: 1,
SkipMethods: []string{
"/health/Check",
},
}
limiter := New(config)
defer limiter.Stop()
identifier := "test-user"
// Regular method should be rate limited
regularMethod := "/test.Service/Method"
limiter.Allow(identifier, regularMethod)
if limiter.Allow(identifier, regularMethod) {
t.Error("regular method should be rate limited")
}
// Skipped method should never be rate limited
skipMethod := "/health/Check"
for i := 0; i < 100; i++ {
if !limiter.Allow(identifier, skipMethod) {
t.Error("skipped method should never be rate limited")
}
}
}
func TestSkipUsers(t *testing.T) {
config := &Config{
RequestsPerSecond: 1,
BurstSize: 1,
SkipUsers: []string{
"admin-user",
},
}
limiter := New(config)
defer limiter.Stop()
method := "/test.Service/Method"
// Regular user should be rate limited
regularUser := "regular-user"
limiter.Allow(regularUser, method)
if limiter.Allow(regularUser, method) {
t.Error("regular user should be rate limited")
}
// Admin user should never be rate limited
adminUser := "admin-user"
for i := 0; i < 100; i++ {
if !limiter.Allow(adminUser, method) {
t.Error("admin user should never be rate limited")
}
}
}
func TestStats(t *testing.T) {
config := &Config{
RequestsPerSecond: 10,
BurstSize: 5,
}
limiter := New(config)
defer limiter.Stop()
identifier := "test-user"
method := "/test.Service/Method"
// Make some requests
for i := 0; i < 5; i++ {
limiter.Allow(identifier, method) // All allowed (within burst)
}
for i := 0; i < 3; i++ {
limiter.Allow(identifier, method) // All denied (burst exhausted)
}
stats := limiter.Stats()
if stats.Allowed != 5 {
t.Errorf("expected 5 allowed, got %d", stats.Allowed)
}
if stats.Denied != 3 {
t.Errorf("expected 3 denied, got %d", stats.Denied)
}
if stats.ActiveLimiters != 1 {
t.Errorf("expected 1 active limiter, got %d", stats.ActiveLimiters)
}
expectedDenialRate := 37.5 // 3/8 * 100
if stats.DenialRate() != expectedDenialRate {
t.Errorf("expected denial rate %.1f%%, got %.1f%%", expectedDenialRate, stats.DenialRate())
}
}
func TestCleanup(t *testing.T) {
config := &Config{
RequestsPerSecond: 10,
BurstSize: 10,
CleanupInterval: 100 * time.Millisecond,
MaxIdleTime: 200 * time.Millisecond,
}
limiter := New(config)
defer limiter.Stop()
// Create limiters for multiple users
for i := 0; i < 5; i++ {
limiter.Allow("user-"+string(rune('0'+i)), "/test")
}
stats := limiter.Stats()
if stats.ActiveLimiters != 5 {
t.Errorf("expected 5 active limiters, got %d", stats.ActiveLimiters)
}
// Wait for cleanup to run
time.Sleep(350 * time.Millisecond)
stats = limiter.Stats()
if stats.ActiveLimiters != 0 {
t.Errorf("expected 0 active limiters after cleanup, got %d", stats.ActiveLimiters)
}
}
func TestUnaryInterceptor(t *testing.T) {
config := &Config{
RequestsPerSecond: 2,
BurstSize: 2,
}
limiter := New(config)
defer limiter.Stop()
interceptor := UnaryInterceptor(limiter)
// Create a test handler
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return "success", nil
}
info := &grpc.UnaryServerInfo{
FullMethod: "/test.Service/Method",
}
// Create context with metadata (simulating IP)
md := metadata.Pairs("x-real-ip", "192.168.1.1")
ctx := metadata.NewIncomingContext(context.Background(), md)
// First 2 requests should succeed
for i := 0; i < 2; i++ {
_, err := interceptor(ctx, nil, info, handler)
if err != nil {
t.Errorf("request %d should succeed, got error: %v", i, err)
}
}
// 3rd request should be rate limited
_, err := interceptor(ctx, nil, info, handler)
if err == nil {
t.Error("expected rate limit error")
}
st, ok := status.FromError(err)
if !ok {
t.Error("expected gRPC status error")
}
if st.Code() != codes.ResourceExhausted {
t.Errorf("expected ResourceExhausted, got %v", st.Code())
}
}
func TestGetLimitForMethod(t *testing.T) {
config := &Config{
RequestsPerSecond: 10,
BurstSize: 20,
MethodLimits: map[string]MethodLimit{
"/test/Method1": {
RequestsPerSecond: 5,
BurstSize: 10,
},
},
UserLimits: map[string]UserLimit{
"vip-user": {
RequestsPerSecond: 50,
BurstSize: 100,
MethodLimits: map[string]MethodLimit{
"/test/Method1": {
RequestsPerSecond: 25,
BurstSize: 50,
},
},
},
},
}
tests := []struct {
name string
pubkey string
method string
expectedRPS float64
expectedBurst int
}{
{
name: "default for regular user",
pubkey: "regular-user",
method: "/test/Method2",
expectedRPS: 10,
expectedBurst: 20,
},
{
name: "method limit for regular user",
pubkey: "regular-user",
method: "/test/Method1",
expectedRPS: 5,
expectedBurst: 10,
},
{
name: "user limit default method",
pubkey: "vip-user",
method: "/test/Method2",
expectedRPS: 50,
expectedBurst: 100,
},
{
name: "user method limit (highest precedence)",
pubkey: "vip-user",
method: "/test/Method1",
expectedRPS: 25,
expectedBurst: 50,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rps, burst := config.GetLimitForMethod(tt.pubkey, tt.method)
if rps != tt.expectedRPS {
t.Errorf("expected RPS %.1f, got %.1f", tt.expectedRPS, rps)
}
if burst != tt.expectedBurst {
t.Errorf("expected burst %d, got %d", tt.expectedBurst, burst)
}
})
}
}
func BenchmarkRateLimitAllow(b *testing.B) {
config := &Config{
RequestsPerSecond: 1000,
BurstSize: 1000,
}
limiter := New(config)
defer limiter.Stop()
identifier := "bench-user"
method := "/test.Service/Method"
b.ResetTimer()
for i := 0; i < b.N; i++ {
limiter.Allow(identifier, method)
}
}
func BenchmarkRateLimitDeny(b *testing.B) {
config := &Config{
RequestsPerSecond: 1,
BurstSize: 1,
}
limiter := New(config)
defer limiter.Stop()
identifier := "bench-user"
method := "/test.Service/Method"
// Exhaust quota
limiter.Allow(identifier, method)
b.ResetTimer()
for i := 0; i < b.N; i++ {
limiter.Allow(identifier, method)
}
}
|