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: 25ac08b5110ba4b6297135a1724645f6a2767684 (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
package ratelimiter

import (
	"net/http"
	"net/http/httptest"
	"strconv"
	"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),
				WithEnforce(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, remoteAddr, hook)
				}
			}
		})
	}
}

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

	tcs := map[string]struct {
		enforce        bool
		expectedStatus int
	}{
		"disabled_rate_limit_http": {
			enforce:        false,
			expectedStatus: http.StatusNoContent,
		},
		"enabled_rate_limit_http_blocks": {
			enforce:        true,
			expectedStatus: http.StatusTooManyRequests,
		},
	}

	for tn, tc := range tcs {
		t.Run(tn, func(t *testing.T) {
			testhelpers.StubFeatureFlagValue(t, feature.EnforceIPRateLimits.EnvVariable, tc.enforce)

			rl := New(
				"rate_limiter",
				WithCachedEntriesMetric(cachedEntries),
				WithCachedRequestsMetric(cacheReqs),
				WithBlockedCountMetric(blocked),
				WithNow(mockNow),
				WithLimitPerSecond(1),
				WithBurstSize(1),
				WithEnforce(tc.enforce),
			)

			// 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, remoteAddr, hook)
			}

			blockedCount := testutil.ToFloat64(blocked.WithLabelValues("rate_limiter", strconv.FormatBool(tc.enforce)))
			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.GetRemoteAddrWithoutPort,
			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.GetRemoteAddrWithoutPort,
			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.GetRemoteAddrWithoutPort,
			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),
				WithEnforce(true),
			).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, remoteAddr string, 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", "enforced"},
	)

	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
}