forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_organisation_activity.go
229 lines (183 loc) · 6.43 KB
/
middleware_organisation_activity.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
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
package main
import (
"github.com/gorilla/context"
"net/http"
"sync"
)
import (
"errors"
"github.com/Sirupsen/logrus"
)
var orgChanMap = make(map[string]chan bool)
type orgActiveMapMu struct {
sync.RWMutex
OrgMap map[string]bool
}
var orgActiveMap = orgActiveMapMu{
OrgMap: make(map[string]bool),
}
// 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 OrganizationMonitor struct {
*TykMiddleware
sessionlimiter SessionLimiter
mon Monitor
}
// New lets you do any initialisations for the object can be done here
func (k *OrganizationMonitor) New() {
k.sessionlimiter = SessionLimiter{}
k.mon = Monitor{}
}
// GetConfig retrieves the configuration from the API config - we user mapstructure for this for simplicity
func (k *OrganizationMonitor) GetConfig() (interface{}, error) {
return nil, nil
}
func (k *OrganizationMonitor) ProcessRequest(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) {
if config.ExperimentalProcessOrgOffThread {
return k.ProcessRequestOffThread(w, r, configuration)
} else {
return k.ProcessRequestLive(w, r, configuration)
}
}
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
func (k *OrganizationMonitor) ProcessRequestLive(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) {
if !config.EnforceOrgQuotas {
// We aren;t enforcing quotas, so skip this altogether
return nil, 200
}
thisSessionState, found := k.GetOrgSession(k.Spec.OrgID)
if !found {
// No organisation session has been created, should not be a pre-requisite in site setups, so we pass the request on
return nil, 200
}
// Is it active?
if thisSessionState.IsInactive {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": GetIPFromRequest(r),
"key": k.Spec.OrgID,
}).Warning("Organisation access is disabled.")
return errors.New("This organisation access has been disabled, please contact your API administrator."), 403
}
// We found a session, apply the quota limiter
forwardMessage, reason := k.sessionlimiter.ForwardMessage(&thisSessionState, k.Spec.OrgID, k.Spec.OrgSessionManager.GetStore())
k.Spec.OrgSessionManager.UpdateSession(k.Spec.OrgID, thisSessionState, 0)
if !forwardMessage {
if reason == 2 {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": GetIPFromRequest(r),
"key": k.Spec.OrgID,
}).Warning("Organisation quota has been exceeded.")
// Fire a quota exceeded event
go k.TykMiddleware.FireEvent(EVENT_OrgQuotaExceeded,
EVENT_QuotaExceededMeta{
EventMetaDefault: EventMetaDefault{Message: "Organisation quota has been exceeded", OriginatingRequest: EncodeRequestToEvent(r)},
Path: r.URL.Path,
Origin: GetIPFromRequest(r),
Key: k.Spec.OrgID,
})
return errors.New("This organisation quota has been exceeded, please contact your API administrator"), 403
}
}
if config.Monitor.MonitorOrgKeys {
// Run the trigger monitor
k.mon.Check(&thisSessionState, "")
}
// Lets keep a reference of the org
context.Set(r, OrgSessionContext, thisSessionState)
// Request is valid, carry on
return nil, 200
}
func (k *OrganizationMonitor) SetOrgSentinel(orgChan chan bool, orgId string) {
var isActive bool
for {
isActive = <-orgChan
log.Debug("Chan got:", isActive)
if isActive {
orgActiveMap.Lock()
orgActiveMap.OrgMap[orgId] = true
orgActiveMap.Unlock()
} else {
orgActiveMap.Lock()
orgActiveMap.OrgMap[orgId] = false
orgActiveMap.Unlock()
}
}
}
func (k *OrganizationMonitor) ProcessRequestOffThread(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) {
if !config.EnforceOrgQuotas {
// We aren't enforcing quotas, so skip this altogether
return nil, 200
}
orgChan, ok := orgChanMap[k.Spec.OrgID]
if !ok {
orgChanMap[k.Spec.OrgID] = make(chan bool)
orgChan = orgChanMap[k.Spec.OrgID]
go k.SetOrgSentinel(orgChan, k.Spec.OrgID)
}
go k.AllowAccessNext(orgChan, r)
orgActiveMap.RLock()
active, found := orgActiveMap.OrgMap[k.Spec.OrgID]
orgActiveMap.RUnlock()
if found {
log.Debug("Is not active")
if !active {
return errors.New("This organisation access has been disabled or quota is exceeded, please contact your API administrator."), 403
}
}
log.Debug("Key not found")
// Request is valid, carry on
return nil, 200
}
func (k *OrganizationMonitor) AllowAccessNext(orgChan chan bool, r *http.Request) {
thisSessionState, found := k.GetOrgSession(k.Spec.OrgID)
if !found {
// No organisation session has been created, should not be a pre-requisite in site setups, so we pass the request on
log.Debug("No session for org, skipping")
return
}
// Is it active?
if thisSessionState.IsInactive {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": GetIPFromRequest(r),
"key": k.Spec.OrgID,
}).Warning("Organisation access is disabled.")
//return errors.New("This organisation access has been disabled, please contact your API administrator."), 403
orgChan <- false
return
}
// We found a session, apply the quota limiter
isQuotaExceeded := k.sessionlimiter.IsRedisQuotaExceeded(&thisSessionState, k.Spec.OrgID, k.Spec.OrgSessionManager.GetStore())
k.Spec.OrgSessionManager.UpdateSession(k.Spec.OrgID, thisSessionState, 0)
if isQuotaExceeded {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": GetIPFromRequest(r),
"key": k.Spec.OrgID,
}).Warning("Organisation quota has been exceeded.")
// Fire a quota exceeded event
go k.TykMiddleware.FireEvent(EVENT_OrgQuotaExceeded,
EVENT_QuotaExceededMeta{
EventMetaDefault: EventMetaDefault{Message: "Organisation quota has been exceeded", OriginatingRequest: EncodeRequestToEvent(r)},
Path: r.URL.Path,
Origin: GetIPFromRequest(r),
Key: k.Spec.OrgID,
})
//return errors.New("This organisation quota has been exceeded, please contact your API administrator"), 403
orgChan <- false
if config.Monitor.MonitorOrgKeys {
// Run the trigger monitor
k.mon.Check(&thisSessionState, "")
}
return
}
if config.Monitor.MonitorOrgKeys {
// Run the trigger monitor
k.mon.Check(&thisSessionState, "")
}
// Lets keep a reference of the org
context.Set(r, OrgSessionContext, thisSessionState)
orgChan <- true
}