forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmw_rate_limiting.go
142 lines (117 loc) · 3.81 KB
/
mw_rate_limiting.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
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
package gateway
import (
"errors"
"net/http"
"time"
"github.com/TykTechnologies/tyk/request"
)
var sessionLimiter = SessionLimiter{}
var sessionMonitor = Monitor{}
// RateLimitAndQuotaCheck will check the incomming request and key whether it is within it's quota and
// within it's rate limit, it makes use of the SessionLimiter object to do this
type RateLimitAndQuotaCheck struct {
BaseMiddleware
}
func (k *RateLimitAndQuotaCheck) Name() string {
return "RateLimitAndQuotaCheck"
}
func (k *RateLimitAndQuotaCheck) EnabledForSpec() bool {
return !k.Spec.DisableRateLimit || !k.Spec.DisableQuota
}
func (k *RateLimitAndQuotaCheck) handleRateLimitFailure(r *http.Request, token string) (error, int) {
k.Logger().WithField("key", obfuscateKey(token)).Info("Key rate limit exceeded.")
// Fire a rate limit exceeded event
k.FireEvent(EventRateLimitExceeded, EventKeyFailureMeta{
EventMetaDefault: EventMetaDefault{Message: "Key Rate Limit Exceeded", OriginatingRequest: EncodeRequestToEvent(r)},
Path: r.URL.Path,
Origin: request.RealIP(r),
Key: token,
})
// Report in health check
reportHealthValue(k.Spec, Throttle, "-1")
return errors.New("Rate limit exceeded"), http.StatusTooManyRequests
}
func (k *RateLimitAndQuotaCheck) handleQuotaFailure(r *http.Request, token string) (error, int) {
k.Logger().WithField("key", obfuscateKey(token)).Info("Key quota limit exceeded.")
// Fire a quota exceeded event
k.FireEvent(EventQuotaExceeded, EventKeyFailureMeta{
EventMetaDefault: EventMetaDefault{Message: "Key Quota Limit Exceeded", OriginatingRequest: EncodeRequestToEvent(r)},
Path: r.URL.Path,
Origin: request.RealIP(r),
Key: token,
})
// Report in health check
reportHealthValue(k.Spec, QuotaViolation, "-1")
return errors.New("Quota exceeded"), http.StatusForbidden
}
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
func (k *RateLimitAndQuotaCheck) ProcessRequest(w http.ResponseWriter, r *http.Request, _ interface{}) (error, int) {
// Skip rate limiting and quotas for looping
if !ctxCheckLimits(r) {
return nil, http.StatusOK
}
session := ctxGetSession(r)
token := ctxGetAuthToken(r)
storeRef := k.Spec.SessionManager.Store()
reason := sessionLimiter.ForwardMessage(
r,
session,
token,
storeRef,
!k.Spec.DisableRateLimit,
!k.Spec.DisableQuota,
&k.Spec.GlobalConfig,
k.Spec.APIID,
false,
)
throttleRetryLimit := session.ThrottleRetryLimit
throttleInterval := session.ThrottleInterval
if len(session.AccessRights) > 0 {
if rights, ok := session.AccessRights[k.Spec.APIID]; ok {
if rights.Limit != nil {
throttleInterval = rights.Limit.ThrottleInterval
throttleRetryLimit = rights.Limit.ThrottleRetryLimit
}
}
}
switch reason {
case sessionFailNone:
case sessionFailRateLimit:
err, errCode := k.handleRateLimitFailure(r, token)
if throttleRetryLimit > 0 {
for true {
ctxIncThrottleLevel(r, throttleRetryLimit)
time.Sleep(time.Duration(throttleInterval * float64(time.Second)))
reason = sessionLimiter.ForwardMessage(
r,
session,
token,
storeRef,
!k.Spec.DisableRateLimit,
!k.Spec.DisableQuota,
&k.Spec.GlobalConfig,
k.Spec.APIID,
true,
)
if reason == sessionFailNone {
return k.ProcessRequest(w, r, nil)
}
if ctxThrottleLevel(r) > throttleRetryLimit {
break
}
}
}
return err, errCode
case sessionFailQuota:
return k.handleQuotaFailure(r, token)
default:
// Other reason? Still not allowed
return errors.New("Access denied"), http.StatusForbidden
}
// Run the trigger monitor
if k.Spec.GlobalConfig.Monitor.MonitorUserKeys {
sessionMonitor.Check(session, token)
}
// Request is valid, carry on
return nil, http.StatusOK
}