forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmw_organisation_activity.go
310 lines (263 loc) · 8.45 KB
/
mw_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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package gateway
import (
"errors"
"net/http"
"sync"
"time"
"github.com/TykTechnologies/tyk/ctx"
"github.com/TykTechnologies/tyk/request"
"github.com/TykTechnologies/tyk/user"
)
type orgChanMapMu struct {
sync.Mutex
channels map[string](chan bool)
}
var orgChanMap = orgChanMapMu{channels: map[string](chan bool){}}
var orgActiveMap sync.Map
// RateLimitAndQuotaCheck will check the incoming 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 {
BaseMiddleware
sessionlimiter SessionLimiter
mon Monitor
}
func (k *OrganizationMonitor) Name() string {
return "OrganizationMonitor"
}
func (k *OrganizationMonitor) EnabledForSpec() bool {
// If false, we aren't enforcing quotas so skip this mw
// altogether
return k.Spec.GlobalConfig.EnforceOrgQuotas
}
func (k *OrganizationMonitor) getOrgHasNoSession() bool {
k.Spec.RLock()
defer k.Spec.RUnlock()
return k.Spec.OrgHasNoSession
}
func (k *OrganizationMonitor) setOrgHasNoSession(val bool) {
k.Spec.Lock()
defer k.Spec.Unlock()
k.Spec.OrgHasNoSession = val
}
func (k *OrganizationMonitor) ProcessRequest(w http.ResponseWriter, r *http.Request, conf interface{}) (error, int) {
// Skip rate limiting and quotas for looping
if !ctxCheckLimits(r) {
return nil, http.StatusOK
}
// short path for specs which have organization limiter enabled but organization has no session
if k.getOrgHasNoSession() {
return nil, http.StatusOK
}
var orgSession user.SessionState
var found bool
// try to check in in-app cache 1st
if !k.Spec.GlobalConfig.LocalSessionCache.DisableCacheSessionState {
var cachedSession interface{}
if cachedSession, found = SessionCache.Get(k.Spec.OrgID); found {
orgSession = cachedSession.(user.SessionState)
}
}
// try to get from Redis
if !found {
// not found in in-app cache, let's read from Redis
orgSession, found = k.OrgSession(k.Spec.OrgID)
if !found {
// prevent reads from in-app cache and from Redis for next runs
k.setOrgHasNoSession(true)
// No organisation session has not been created, should not be a pre-requisite in site setups, so we pass the request on
return nil, http.StatusOK
}
}
if k.Spec.GlobalConfig.ExperimentalProcessOrgOffThread {
// Make a copy of request before before sending to goroutine
r2 := r.WithContext(r.Context())
return k.ProcessRequestOffThread(r2, orgSession)
}
return k.ProcessRequestLive(r, orgSession)
}
// 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(r *http.Request, orgSession user.SessionState) (error, int) {
logger := k.Logger()
if orgSession.IsInactive {
logger.Warning("Organisation access is disabled.")
return errors.New("this organisation access has been disabled, please contact your API administrator"), http.StatusForbidden
}
// We found a session, apply the quota and rate limiter
reason := k.sessionlimiter.ForwardMessage(
r,
&orgSession,
k.Spec.OrgID,
k.Spec.OrgSessionManager.Store(),
orgSession.Per > 0 && orgSession.Rate > 0,
true,
&k.Spec.GlobalConfig,
k.Spec.APIID,
false,
)
sessionLifeTime := orgSession.Lifetime(k.Spec.SessionLifetime)
if err := k.Spec.OrgSessionManager.UpdateSession(k.Spec.OrgID, &orgSession, sessionLifeTime, false); err == nil {
// update in-app cache if needed
if !k.Spec.GlobalConfig.LocalSessionCache.DisableCacheSessionState {
SessionCache.Set(k.Spec.OrgID, orgSession, time.Second*time.Duration(sessionLifeTime))
}
} else {
logger.WithError(err).Error("Could not update org session")
}
switch reason {
case sessionFailNone:
// all good, keep org active
case sessionFailQuota:
logger.Warning("Organisation quota has been exceeded.", k.Spec.OrgID)
// Fire a quota exceeded event
k.FireEvent(
EventOrgQuotaExceeded,
EventKeyFailureMeta{
EventMetaDefault: EventMetaDefault{
Message: "Organisation quota has been exceeded",
OriginatingRequest: EncodeRequestToEvent(r),
},
Path: r.URL.Path,
Origin: request.RealIP(r),
Key: k.Spec.OrgID,
})
return errors.New("This organisation quota has been exceeded, please contact your API administrator"), http.StatusForbidden
case sessionFailRateLimit:
logger.Warning("Organisation rate limit has been exceeded.", k.Spec.OrgID)
// Fire a rate limit exceeded event
k.FireEvent(
EventOrgRateLimitExceeded,
EventKeyFailureMeta{
EventMetaDefault: EventMetaDefault{
Message: "Organisation rate limit has been exceeded",
OriginatingRequest: EncodeRequestToEvent(r),
},
Path: r.URL.Path,
Origin: request.RealIP(r),
Key: k.Spec.OrgID,
},
)
return errors.New("This organisation rate limit has been exceeded, please contact your API administrator"), http.StatusForbidden
}
if k.Spec.GlobalConfig.Monitor.MonitorOrgKeys {
// Run the trigger monitor
k.mon.Check(&orgSession, "")
}
// Lets keep a reference of the org
setCtxValue(r, ctx.OrgSessionContext, orgSession)
// Request is valid, carry on
return nil, http.StatusOK
}
func (k *OrganizationMonitor) SetOrgSentinel(orgChan chan bool, orgId string) {
for isActive := range orgChan {
k.Logger().Debug("Chan got:", isActive)
orgActiveMap.Store(orgId, isActive)
}
}
func (k *OrganizationMonitor) ProcessRequestOffThread(r *http.Request, orgSession user.SessionState) (error, int) {
orgChanMap.Lock()
orgChan, ok := orgChanMap.channels[k.Spec.OrgID]
if !ok {
orgChan = make(chan bool)
orgChanMap.channels[k.Spec.OrgID] = orgChan
go k.SetOrgSentinel(orgChan, k.Spec.OrgID)
}
orgChanMap.Unlock()
active, found := orgActiveMap.Load(k.Spec.OrgID)
// Lets keep a reference of the org
// session might be updated by go-routine AllowAccessNext and we loose those changes here
// but it is OK as we need it in context for detailed org logging
setCtxValue(r, ctx.OrgSessionContext, orgSession)
orgSessionCopy := orgSession
go k.AllowAccessNext(
orgChan,
r.URL.Path,
request.RealIP(r),
r,
&orgSessionCopy,
)
if found && !active.(bool) {
k.Logger().Debug("Is not active")
return errors.New("This organization access has been disabled or quota/rate limit is exceeded, please contact your API administrator"), http.StatusForbidden
}
// Request is valid, carry on
return nil, http.StatusOK
}
func (k *OrganizationMonitor) AllowAccessNext(
orgChan chan bool,
path string,
IP string,
r *http.Request,
session *user.SessionState) {
// Is it active?
logEntry := getExplicitLogEntryForRequest(k.Logger(), path, IP, k.Spec.OrgID, nil)
if session.IsInactive {
logEntry.Warning("Organisation access is disabled.")
orgChan <- false
return
}
// We found a session, apply the quota and rate limiter
reason := k.sessionlimiter.ForwardMessage(
r,
session,
k.Spec.OrgID,
k.Spec.OrgSessionManager.Store(),
session.Per > 0 && session.Rate > 0,
true,
&k.Spec.GlobalConfig,
k.Spec.APIID,
false,
)
sessionLifeTime := session.Lifetime(k.Spec.SessionLifetime)
if err := k.Spec.OrgSessionManager.UpdateSession(k.Spec.OrgID, session, sessionLifeTime, false); err == nil {
// update in-app cache if needed
if !k.Spec.GlobalConfig.LocalSessionCache.DisableCacheSessionState {
SessionCache.Set(k.Spec.OrgID, *session, time.Second*time.Duration(sessionLifeTime))
}
} else {
logEntry.WithError(err).WithField("orgID", k.Spec.OrgID).Error("Could not update org session")
}
isExceeded := false
switch reason {
case sessionFailNone:
// all good, keep org active
case sessionFailQuota:
isExceeded = true
logEntry.Warning("Organisation quota has been exceeded.")
// Fire a quota exceeded event
k.FireEvent(
EventOrgQuotaExceeded,
EventKeyFailureMeta{
EventMetaDefault: EventMetaDefault{
Message: "Organisation quota has been exceeded",
},
Path: path,
Origin: IP,
Key: k.Spec.OrgID,
},
)
case sessionFailRateLimit:
isExceeded = true
logEntry.Warning("Organisation rate limit has been exceeded.")
// Fire a rate limit exceeded event
k.FireEvent(
EventOrgRateLimitExceeded,
EventKeyFailureMeta{
EventMetaDefault: EventMetaDefault{
Message: "Organisation rate limit has been exceeded",
},
Path: path,
Origin: IP,
Key: k.Spec.OrgID,
},
)
}
if k.Spec.GlobalConfig.Monitor.MonitorOrgKeys {
// Run the trigger monitor
k.mon.Check(session, "")
}
if isExceeded {
orgChan <- false
return
}
orgChan <- true
}