Welcome to mirror list, hosted at ThFree Co, Russian Federation.

middleware_test.go « ratelimiter « internal - gitlab.com/gitlab-org/gitlab-pages.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a410b8b8a98365c4771a0296c1bd2c38d2c64908 (plain)
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
package ratelimiter

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/testutil"
	testlog "github.com/sirupsen/logrus/hooks/test"
	"github.com/stretchr/testify/require"

	"gitlab.com/gitlab-org/gitlab-pages/internal/feature"
	"gitlab.com/gitlab-org/gitlab-pages/internal/request"
	"gitlab.com/gitlab-org/gitlab-pages/internal/testhelpers"
)

const (
	remoteAddr = "192.168.1.1"
)

var next = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusNoContent)
})

func TestMiddlewareWithDifferentLimits(t *testing.T) {
	hook := testlog.NewGlobal()

	for tn, tc := range sharedTestCases {
		t.Run(tn, func(t *testing.T) {
			rl := New(
				"rate_limiter",
				WithNow(mockNow),
				WithLimitPerSecond(tc.limit),
				WithBurstSize(tc.burstSize),
				WithCloseConnection(true),
			)

			handler := rl.Middleware(next)

			for i := 0; i < tc.reqNum; i++ {
				r := requestFor(remoteAddr, "http://gitlab.com")
				code, body, _ := testhelpers.PerformRequest(t, handler, r)

				if i < tc.burstSize {
					require.Equal(t, http.StatusNoContent, code, "req: %d failed", i)
				} else {
					// requests should fail after reaching tc.perDomainBurstPerSecond because mockNow
					// always returns the same time
					require.Equal(t, http.StatusTooManyRequests, code, "req: %d failed", i)
					require.Contains(t, body, "Too many requests.")
					assertSourceIPLog(t, hook)
				}
			}
		})
	}
}

func TestMiddlewareDenyRequestsAfterBurst(t *testing.T) {
	hook := testlog.NewGlobal()
	blocked, cachedEntries, cacheReqs := newTestMetrics(t)

	tcs := map[string]struct {
		expectedStatus int
	}{
		"enabled_rate_limit_http_blocks": {
			expectedStatus: http.StatusTooManyRequests,
		},
	}

	for tn, tc := range tcs {
		t.Run(tn, func(t *testing.T) {
			rl := New(
				"rate_limiter",
				WithCachedEntriesMetric(cachedEntries),
				WithCachedRequestsMetric(cacheReqs),
				WithBlockedCountMetric(blocked),
				WithNow(mockNow),
				WithLimitPerSecond(1),
				WithBurstSize(1),
				WithCloseConnection(true),
			)

			// middleware is evaluated in reverse order
			handler := rl.Middleware(next)

			for i := 0; i < 5; i++ {
				r := requestFor(remoteAddr, "http://gitlab.com")
				code, _, _ := testhelpers.PerformRequest(t, handler, r)

				if i == 0 {
					require.Equal(t, http.StatusNoContent, code)
					continue
				}

				// burst is 1 and limit is 1 per second, all subsequent requests should fail
				require.Equal(t, tc.expectedStatus, code)
				assertSourceIPLog(t, hook)
			}

			blockedCount := testutil.ToFloat64(blocked.WithLabelValues("rate_limiter"))
			require.Equal(t, float64(4), blockedCount, "blocked count")
			blocked.Reset()

			cachedCount := testutil.ToFloat64(cachedEntries.WithLabelValues("rate_limiter"))
			require.Equal(t, float64(1), cachedCount, "cached count")
			cachedEntries.Reset()

			cacheReqMiss := testutil.ToFloat64(cacheReqs.WithLabelValues("rate_limiter", "miss"))
			require.Equal(t, float64(1), cacheReqMiss, "miss count")
			cacheReqHit := testutil.ToFloat64(cacheReqs.WithLabelValues("rate_limiter", "hit"))
			require.Equal(t, float64(4), cacheReqHit, "hit count")
			cacheReqs.Reset()
		})
	}
}

func TestMiddlewareWithDifferentLimitsWithFFCloseConnectionEnabled(t *testing.T) {
	hook := testlog.NewGlobal()
	t.Setenv(feature.RateLimiterCloseConnection.EnvVariable, "true")

	for tn, tc := range sharedTestCases {
		t.Run(tn, func(t *testing.T) {
			rl := New(
				"rate_limiter",
				WithNow(mockNow),
				WithLimitPerSecond(tc.limit),
				WithBurstSize(tc.burstSize),
				WithCloseConnection(true),
			)

			handler := rl.Middleware(next)

			for i := 0; i < tc.reqNum; i++ {
				r := requestFor(remoteAddr, "http://gitlab.com")
				code, body, header := testhelpers.PerformRequest(t, handler, r)

				if i < tc.burstSize {
					require.Equal(t, http.StatusNoContent, code, "req: %d failed", i)
				} else {
					// requests should fail after reaching tc.perDomainBurstPerSecond because mockNow
					// always returns the same time
					require.Equal(t, http.StatusTooManyRequests, code, "req: %d failed", i)
					require.Contains(t, body, "Too many requests.")
					require.Equal(t, "close", header.Get("Connection"), "req: %d connection closed", i)
					assertSourceIPLog(t, hook)
				}
			}
		})
	}
}

func TestMiddlewareDenyRequestsAfterBurstWithFFCloseConnectionEnabled(t *testing.T) {
	hook := testlog.NewGlobal()
	t.Setenv(feature.RateLimiterCloseConnection.EnvVariable, "true")
	blocked, cachedEntries, cacheReqs := newTestMetrics(t)

	tcs := map[string]struct {
		expectedStatus           int
		expectedConnectionHeader string
	}{
		"enabled_rate_limit_http_blocks": {
			expectedStatus:           http.StatusTooManyRequests,
			expectedConnectionHeader: "close",
		},
	}

	for tn, tc := range tcs {
		t.Run(tn, func(t *testing.T) {
			rl := New(
				"rate_limiter",
				WithCachedEntriesMetric(cachedEntries),
				WithCachedRequestsMetric(cacheReqs),
				WithBlockedCountMetric(blocked),
				WithNow(mockNow),
				WithLimitPerSecond(1),
				WithBurstSize(1),
				WithCloseConnection(true),
			)

			// middleware is evaluated in reverse order
			handler := rl.Middleware(next)

			for i := 0; i < 5; i++ {
				r := requestFor(remoteAddr, "http://gitlab.com")
				code, _, header := testhelpers.PerformRequest(t, handler, r)

				if i == 0 {
					require.Equal(t, http.StatusNoContent, code)
					continue
				}

				// burst is 1 and limit is 1 per second, all subsequent requests should fail
				require.Equal(t, tc.expectedStatus, code)
				require.Equal(t, tc.expectedConnectionHeader, header.Get("Connection"))
				assertSourceIPLog(t, hook)
			}

			blockedCount := testutil.ToFloat64(blocked.WithLabelValues("rate_limiter"))
			require.Equal(t, float64(4), blockedCount, "blocked count")
			blocked.Reset()

			cachedCount := testutil.ToFloat64(cachedEntries.WithLabelValues("rate_limiter"))
			require.Equal(t, float64(1), cachedCount, "cached count")
			cachedEntries.Reset()

			cacheReqMiss := testutil.ToFloat64(cacheReqs.WithLabelValues("rate_limiter", "miss"))
			require.Equal(t, float64(1), cacheReqMiss, "miss count")
			cacheReqHit := testutil.ToFloat64(cacheReqs.WithLabelValues("rate_limiter", "hit"))
			require.Equal(t, float64(4), cacheReqHit, "hit count")
			cacheReqs.Reset()
		})
	}
}

func TestKeyFunc(t *testing.T) {
	tt := map[string]struct {
		keyFunc            KeyFunc
		firstRemoteAddr    string
		firstTarget        string
		secondRemoteAddr   string
		secondTarget       string
		expectedSecondCode int
	}{
		"rejected_by_ip": {
			keyFunc:            request.GetIPV4orIPV6PrefixWithoutPort,
			firstRemoteAddr:    "10.0.0.1",
			firstTarget:        "https://domain.gitlab.io",
			secondRemoteAddr:   "10.0.0.1",
			secondTarget:       "https://different.gitlab.io",
			expectedSecondCode: http.StatusTooManyRequests,
		},
		"rejected_by_ip_with_different_port": {
			keyFunc:            request.GetIPV4orIPV6PrefixWithoutPort,
			firstRemoteAddr:    "10.0.0.1:41000",
			firstTarget:        "https://domain.gitlab.io",
			secondRemoteAddr:   "10.0.0.1:41001",
			secondTarget:       "https://different.gitlab.io",
			expectedSecondCode: http.StatusTooManyRequests,
		},
		"rejected_by_domain": {
			keyFunc:            request.GetHostWithoutPort,
			firstRemoteAddr:    "10.0.0.1",
			firstTarget:        "https://domain.gitlab.io",
			secondRemoteAddr:   "10.0.0.2",
			secondTarget:       "https://domain.gitlab.io",
			expectedSecondCode: http.StatusTooManyRequests,
		},
		"rejected_by_domain_with_different_protocol": {
			keyFunc:            request.GetHostWithoutPort,
			firstRemoteAddr:    "10.0.0.1",
			firstTarget:        "https://domain.gitlab.io",
			secondRemoteAddr:   "10.0.0.2",
			secondTarget:       "http://domain.gitlab.io",
			expectedSecondCode: http.StatusTooManyRequests,
		},
		"domain_limiter_allows_same_ip": {
			keyFunc:            request.GetHostWithoutPort,
			firstRemoteAddr:    "10.0.0.1",
			firstTarget:        "https://domain.gitlab.io",
			secondRemoteAddr:   "10.0.0.1",
			secondTarget:       "https://different.gitlab.io",
			expectedSecondCode: http.StatusNoContent,
		},
		"ip_limiter_allows_same_domain": {
			keyFunc:            request.GetIPV4orIPV6PrefixWithoutPort,
			firstRemoteAddr:    "10.0.0.1",
			firstTarget:        "https://domain.gitlab.io",
			secondRemoteAddr:   "10.0.0.2",
			secondTarget:       "https://domain.gitlab.io",
			expectedSecondCode: http.StatusNoContent,
		},
	}

	for name, tc := range tt {
		t.Run(name, func(t *testing.T) {
			handler := New(
				"rate_limiter",
				WithNow(mockNow),
				WithLimitPerSecond(1),
				WithBurstSize(1),
				WithKeyFunc(tc.keyFunc),
			).Middleware(next)

			r1 := httptest.NewRequest(http.MethodGet, tc.firstTarget, nil)
			r1.RemoteAddr = tc.firstRemoteAddr

			firstCode, _, _ := testhelpers.PerformRequest(t, handler, r1)
			require.Equal(t, http.StatusNoContent, firstCode)

			r2 := httptest.NewRequest(http.MethodGet, tc.secondTarget, nil)
			r2.RemoteAddr = tc.secondRemoteAddr
			secondCode, _, _ := testhelpers.PerformRequest(t, handler, r2)
			require.Equal(t, tc.expectedSecondCode, secondCode)
		})
	}
}

func assertSourceIPLog(t *testing.T, hook *testlog.Hook) {
	t.Helper()

	require.NotNil(t, hook.LastEntry())

	// source_ip that was rate limited
	require.Equal(t, remoteAddr, hook.LastEntry().Data["source_ip"])

	hook.Reset()
}

func newTestMetrics(t *testing.T) (*prometheus.GaugeVec, *prometheus.GaugeVec, *prometheus.CounterVec) {
	t.Helper()

	blockedGauge := prometheus.NewGaugeVec(
		prometheus.GaugeOpts{
			Name: t.Name(),
		},
		[]string{"limit_name"},
	)

	cachedEntries := prometheus.NewGaugeVec(prometheus.GaugeOpts{
		Name: t.Name(),
	}, []string{"op"})

	cacheReqs := prometheus.NewCounterVec(prometheus.CounterOpts{
		Name: t.Name(),
	}, []string{"op", "cache"})

	return blockedGauge, cachedEntries, cacheReqs
}