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
|
package ratelimiter
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"gitlab.com/gitlab-org/gitlab-pages/internal/testhelpers"
)
var next = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
func TestSourceIPLimiter(t *testing.T) {
testhelpers.EnableRateLimiter(t)
for tn, tc := range sharedTestCases {
t.Run(tn, func(t *testing.T) {
rl := New(
WithNow(mockNow),
WithSourceIPLimitPerSecond(tc.sourceIPLimit),
WithSourceIPBurstSize(tc.sourceIPBurstSize),
)
for i := 0; i < tc.reqNum; i++ {
ww := httptest.NewRecorder()
rr := httptest.NewRequest(http.MethodGet, "https://domain.gitlab.io", nil)
rr.RemoteAddr = "172.16.123.1"
handler := rl.SourceIPLimiter(next)
handler.ServeHTTP(ww, rr)
res := ww.Result()
if i < tc.sourceIPBurstSize {
require.Equal(t, http.StatusNoContent, res.StatusCode, "req: %d failed", i)
} else {
// requests should fail after reaching tc.perDomainBurstPerSecond because mockNow
// always returns the same time
require.Equal(t, http.StatusTooManyRequests, res.StatusCode, "req: %d failed", i)
b, err := io.ReadAll(res.Body)
require.NoError(t, err)
require.Contains(t, string(b), "Too many requests.")
res.Body.Close()
}
}
})
}
}
func TestSourceIPRateLimit(t *testing.T) {
rl := New(
WithNow(mockNow),
WithSourceIPLimitPerSecond(1),
WithSourceIPBurstSize(1),
)
tcs := map[string]struct {
enabled bool
ip string
host string
expectedStatus int
}{
"disabled_rate_limit_http": {
enabled: false,
ip: "172.16.123.1",
host: "http://gitlab.com",
expectedStatus: http.StatusNoContent,
},
"disabled_rate_limit_https": {
enabled: false,
ip: "172.16.123.2",
host: "https://gitlab.com",
expectedStatus: http.StatusNoContent,
},
"enabled_rate_limit_http_does_not_block": {
enabled: true,
ip: "172.16.123.3",
host: "http://gitlab.com",
expectedStatus: http.StatusNoContent,
},
"enabled_rate_limit_https_blocks": {
enabled: true,
ip: "172.16.123.4",
host: "https://gitlab.com",
expectedStatus: http.StatusTooManyRequests,
},
}
for tn, tc := range tcs {
t.Run(tn, func(t *testing.T) {
for i := 0; i < 5; i++ {
ww := httptest.NewRecorder()
rr := httptest.NewRequest(http.MethodGet, tc.host, nil)
rr.RemoteAddr = tc.ip
if tc.enabled {
testhelpers.EnableRateLimiter(t)
}
handler := rl.SourceIPLimiter(next)
handler.ServeHTTP(ww, rr)
res := ww.Result()
if i == 0 {
require.Equal(t, http.StatusNoContent, res.StatusCode)
continue
}
// burst is 1 and limit is 1 per second, all subsequent requests should fail
require.Equal(t, tc.expectedStatus, res.StatusCode)
}
})
}
}
|