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

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

import (
	"net/http"

	"github.com/sirupsen/logrus"

	"gitlab.com/gitlab-org/gitlab-pages/internal/httperrors"
	"gitlab.com/gitlab-org/gitlab-pages/internal/logging"
	"gitlab.com/gitlab-org/gitlab-pages/internal/request"
)

const (
	headerGitLabRealIP    = "GitLab-Real-IP"
	headerXForwardedFor   = "X-Forwarded-For"
	headerXForwardedProto = "X-Forwarded-Proto"
)

// Middleware returns middleware for rate-limiting clients
func (rl *RateLimiter) Middleware(handler http.Handler) http.Handler {
	if rl.limitPerSecond <= 0.0 {
		return handler
	}

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if rl.requestAllowed(r) {
			handler.ServeHTTP(w, r)
			return
		}

		rl.logRateLimitedRequest(r)

		if rl.blockedCount != nil {
			rl.blockedCount.WithLabelValues(rl.name).Inc()
		}

		httperrors.Serve429(w)
	})
}

func (rl *RateLimiter) logRateLimitedRequest(r *http.Request) {
	logging.LogRequest(r).WithFields(logrus.Fields{
		"rate_limiter_name":             rl.name,
		"scheme":                        r.URL.Scheme,
		"remote_addr":                   r.RemoteAddr,
		"source_ip":                     request.GetRemoteAddrWithoutPort(r),
		"x_forwarded_proto":             r.Header.Get(headerXForwardedProto),
		"x_forwarded_for":               r.Header.Get(headerXForwardedFor),
		"gitlab_real_ip":                r.Header.Get(headerGitLabRealIP),
		"rate_limiter_limit_per_second": rl.limitPerSecond,
		"rate_limiter_burst_size":       rl.burstSize,
	}). // TODO: change to Debug with https://gitlab.com/gitlab-org/gitlab-pages/-/issues/629
		Info("request hit rate limit")
}