/
limiter.go
102 lines (89 loc) · 2.39 KB
/
limiter.go
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
package server
import (
"fmt"
"net"
"net/http"
"strings"
"sync"
"time"
"github.com/jellydator/ttlcache/v2"
log "github.com/sirupsen/logrus"
"github.com/urfave/negroni"
"github.com/chainflag/eth-faucet/internal/chain"
)
type Limiter struct {
mutex sync.Mutex
cache *ttlcache.Cache
proxyCount int
ttl time.Duration
}
func NewLimiter(proxyCount int, ttl time.Duration) *Limiter {
cache := ttlcache.NewCache()
cache.SkipTTLExtensionOnHit(true)
return &Limiter{
cache: cache,
proxyCount: proxyCount,
ttl: ttl,
}
}
func (l *Limiter) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
address := r.PostFormValue(AddressKey)
if !chain.IsValidAddress(address, true) {
http.Error(w, "invalid address", http.StatusBadRequest)
return
}
if l.ttl <= 0 {
next.ServeHTTP(w, r)
return
}
clintIP := getClientIPFromRequest(l.proxyCount, r)
l.mutex.Lock()
if l.limitByKey(w, address) || l.limitByKey(w, clintIP) {
l.mutex.Unlock()
return
}
l.cache.SetWithTTL(address, true, l.ttl)
l.cache.SetWithTTL(clintIP, true, l.ttl)
l.mutex.Unlock()
next.ServeHTTP(w, r)
if w.(negroni.ResponseWriter).Status() != http.StatusOK {
l.cache.Remove(address)
l.cache.Remove(clintIP)
return
}
log.WithFields(log.Fields{
"address": address,
"clientIP": clintIP,
}).Info("Maximum request limit has been reached")
}
func (l *Limiter) limitByKey(w http.ResponseWriter, key string) bool {
if _, ttl, err := l.cache.GetWithTTL(key); err == nil {
errMsg := fmt.Sprintf("You have exceeded the rate limit. Please wait %s before you try again", ttl.Round(time.Second))
http.Error(w, errMsg, http.StatusTooManyRequests)
return true
}
return false
}
func getClientIPFromRequest(proxyCount int, r *http.Request) string {
if proxyCount > 0 {
xForwardedFor := r.Header.Get("X-Forwarded-For")
xRealIP := r.Header.Get("X-Real-Ip")
if xForwardedFor != "" {
xForwardedForParts := strings.Split(xForwardedFor, ",")
// Avoid reading the user's forged request header by configuring the count of reverse proxies
partIndex := len(xForwardedForParts) - proxyCount
if partIndex < 0 {
partIndex = 0
}
return strings.TrimSpace(xForwardedForParts[partIndex])
}
if xRealIP != "" {
return strings.TrimSpace(xRealIP)
}
}
remoteIP, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
remoteIP = r.RemoteAddr
}
return remoteIP
}