forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mw_rate_limiting.go
111 lines (91 loc) · 3.28 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
package main
import (
"errors"
"net/http"
"github.com/Sirupsen/logrus"
)
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) GetName() string {
return "RateLimitAndQuotaCheck"
}
func (k *RateLimitAndQuotaCheck) IsEnabledForSpec() bool {
return !k.Spec.DisableRateLimit || !k.Spec.DisableQuota
}
func (k *RateLimitAndQuotaCheck) handleRateLimitFailure(r *http.Request, token string) (error, int) {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": GetIPFromRequest(r),
"key": token,
}).Info("Key rate limit exceeded.")
// Fire a rate limit exceeded event
k.FireEvent(EventRateLimitExceeded, EventRateLimitExceededMeta{
EventMetaDefault: EventMetaDefault{Message: "Key Rate Limit Exceeded", OriginatingRequest: EncodeRequestToEvent(r)},
Path: r.URL.Path,
Origin: GetIPFromRequest(r),
Key: token,
})
// Report in health check
ReportHealthCheckValue(k.Spec.Health, Throttle, "-1")
return errors.New("Rate limit exceeded"), 429
}
func (k *RateLimitAndQuotaCheck) handleQuotaFailure(r *http.Request, token string) (error, int) {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": GetIPFromRequest(r),
"key": token,
}).Info("Key quota limit exceeded.")
// Fire a quota exceeded event
k.FireEvent(EventQuotaExceeded, EventQuotaExceededMeta{
EventMetaDefault: EventMetaDefault{Message: "Key Quota Limit Exceeded", OriginatingRequest: EncodeRequestToEvent(r)},
Path: r.URL.Path,
Origin: GetIPFromRequest(r),
Key: token,
})
// Report in health check
ReportHealthCheckValue(k.Spec.Health, QuotaViolation, "-1")
return errors.New("Quota exceeded"), 403
}
// 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) {
session := ctxGetSession(r)
token := ctxGetAuthToken(r)
storeRef := k.Spec.SessionManager.GetStore()
reason := sessionLimiter.ForwardMessage(session,
token,
storeRef,
!k.Spec.DisableRateLimit,
!k.Spec.DisableQuota)
// If either are disabled, save the write roundtrip
if !k.Spec.DisableRateLimit || !k.Spec.DisableQuota {
// Ensure quota and rate data for this session are recorded
if globalConf.UseAsyncSessionWrite {
go k.Spec.SessionManager.UpdateSession(token, session, getLifetime(k.Spec, session))
} else {
k.Spec.SessionManager.UpdateSession(token, session, getLifetime(k.Spec, session))
}
ctxSetSession(r, session)
}
log.Debug("SessionState: ", session)
switch reason {
case sessionFailNone:
case sessionFailRateLimit:
return k.handleRateLimitFailure(r, token)
case sessionFailQuota:
return k.handleQuotaFailure(r, token)
default:
// Other reason? Still not allowed
return errors.New("Access denied"), 403
}
// Run the trigger monitor
if globalConf.Monitor.MonitorUserKeys {
sessionMonitor.Check(session, token)
}
// Request is valid, carry on
return nil, 200
}