forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_manager.go
318 lines (262 loc) · 8.44 KB
/
auth_manager.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
311
312
313
314
315
316
317
318
package main
import (
"encoding/base64"
"encoding/json"
"strings"
"sync"
"time"
uuid "github.com/satori/go.uuid"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/storage"
"github.com/TykTechnologies/tyk/user"
"github.com/Sirupsen/logrus"
)
// AuthorisationHandler is used to validate a session key,
// implementing KeyAuthorised() to validate if a key exists or
// is valid in any way (e.g. cryptographic signing etc.). Returns
// a user.SessionState object (deserialised JSON)
type AuthorisationHandler interface {
Init(storage.Handler)
KeyAuthorised(string) (user.SessionState, bool)
KeyExpired(*user.SessionState) bool
}
// SessionHandler handles all update/create/access session functions and deals exclusively with
// user.SessionState objects, not identity
type SessionHandler interface {
Init(store storage.Handler)
UpdateSession(keyName string, session *user.SessionState, resetTTLTo int64, hashed bool) error
RemoveSession(keyName string, hashed bool) bool
SessionDetail(keyName string, hashed bool) (user.SessionState, bool)
Sessions(filter string) []string
Store() storage.Handler
ResetQuota(string, *user.SessionState, bool)
Stop()
}
const sessionPoolDefaultSize = 50
const sessionBufferDefaultSize = 1000
type sessionUpdater struct {
store storage.Handler
once sync.Once
updateChan chan *SessionUpdate
poolSize int
bufferSize int
keyPrefix string
}
var defaultSessionUpdater *sessionUpdater
func init() {
defaultSessionUpdater = &sessionUpdater{}
}
func (s *sessionUpdater) Init(store storage.Handler) {
s.once.Do(func() {
s.store = store
// check pool size in config and set to 50 if unset
s.poolSize = config.Global().SessionUpdatePoolSize
if s.poolSize <= 0 {
s.poolSize = sessionPoolDefaultSize
}
//check size for channel buffer and set to 1000 if unset
s.bufferSize = config.Global().SessionUpdateBufferSize
if s.bufferSize <= 0 {
s.bufferSize = sessionBufferDefaultSize
}
log.WithField("pool_size", s.poolSize).Debug("Session update async pool size")
s.updateChan = make(chan *SessionUpdate, s.bufferSize)
s.keyPrefix = s.store.GetKeyPrefix()
for i := 0; i < s.poolSize; i++ {
go s.updateWorker()
}
})
}
func (s *sessionUpdater) updateWorker() {
for u := range s.updateChan {
v, err := json.Marshal(u.session)
if err != nil {
log.WithError(err).Error("Error marshalling session for async session update")
continue
}
if u.isHashed {
u.keyVal = s.keyPrefix + u.keyVal
err := s.store.SetRawKey(u.keyVal, string(v), u.ttl)
if err != nil {
log.WithError(err).Error("Error updating hashed key")
}
continue
}
err = s.store.SetKey(u.keyVal, string(v), u.ttl)
if err != nil {
log.WithError(err).Error("Error updating key")
}
}
}
// DefaultAuthorisationManager implements AuthorisationHandler,
// requires a storage.Handler to interact with key store
type DefaultAuthorisationManager struct {
store storage.Handler
}
type DefaultSessionManager struct {
store storage.Handler
asyncWrites bool
disableCacheSessionState bool
}
type SessionUpdate struct {
isHashed bool
keyVal string
session *user.SessionState
ttl int64
}
func (b *DefaultAuthorisationManager) Init(store storage.Handler) {
b.store = store
b.store.Connect()
}
// KeyAuthorised checks if key exists and can be read into a user.SessionState object
func (b *DefaultAuthorisationManager) KeyAuthorised(keyName string) (user.SessionState, bool) {
jsonKeyVal, err := b.store.GetKey(keyName)
var newSession user.SessionState
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "auth-mgr",
"inbound-key": obfuscateKey(keyName),
"err": err,
}).Warning("Key not found in storage engine")
return newSession, false
}
if err := json.Unmarshal([]byte(jsonKeyVal), &newSession); err != nil {
log.Error("Couldn't unmarshal session object: ", err)
return newSession, false
}
return newSession, true
}
// KeyExpired checks if a key has expired, if the value of user.SessionState.Expires is 0, it will be ignored
func (b *DefaultAuthorisationManager) KeyExpired(newSession *user.SessionState) bool {
if newSession.Expires >= 1 {
return time.Now().After(time.Unix(newSession.Expires, 0))
}
return false
}
func (b *DefaultSessionManager) Init(store storage.Handler) {
b.asyncWrites = config.Global().UseAsyncSessionWrite
b.store = store
b.store.Connect()
// for RPC we don't need to setup async session writes
switch store.(type) {
case *RPCStorageHandler:
return
}
if b.asyncWrites {
defaultSessionUpdater.Init(store)
}
}
func (b *DefaultSessionManager) Store() storage.Handler {
return b.store
}
func (b *DefaultSessionManager) ResetQuota(keyName string, session *user.SessionState, isHashed bool) {
origKeyName := keyName
if !isHashed {
keyName = storage.HashKey(keyName)
}
rawKey := QuotaKeyPrefix + keyName
log.WithFields(logrus.Fields{
"prefix": "auth-mgr",
"inbound-key": obfuscateKey(origKeyName),
"key": rawKey,
}).Info("Reset quota for key.")
rateLimiterSentinelKey := RateLimitKeyPrefix + keyName + ".BLOCKED"
// Clear the rate limiter
go b.store.DeleteRawKey(rateLimiterSentinelKey)
// Fix the raw key
go b.store.DeleteRawKey(rawKey)
//go b.store.SetKey(rawKey, "0", session.QuotaRenewalRate)
for apiID := range session.AccessRights {
rawKey = QuotaKeyPrefix + apiID + "-" + keyName
go b.store.DeleteRawKey(rawKey)
}
}
// UpdateSession updates the session state in the storage engine
func (b *DefaultSessionManager) UpdateSession(keyName string, session *user.SessionState,
resetTTLTo int64, hashed bool) error {
// async update and return if needed
if b.asyncWrites {
sessionUpdate := &SessionUpdate{
isHashed: hashed,
keyVal: keyName,
session: session,
ttl: resetTTLTo,
}
// send sessionupdate object through channel to pool
defaultSessionUpdater.updateChan <- sessionUpdate
return nil
}
v, err := json.Marshal(session)
if err != nil {
log.Error("Error marshalling session for sync update")
return err
}
// sync update
if hashed {
keyName = b.store.GetKeyPrefix() + keyName
err = b.store.SetRawKey(keyName, string(v), resetTTLTo)
} else {
err = b.store.SetKey(keyName, string(v), resetTTLTo)
}
return err
}
// RemoveSession removes session from storage
func (b *DefaultSessionManager) RemoveSession(keyName string, hashed bool) bool {
if hashed {
return b.store.DeleteRawKey(b.store.GetKeyPrefix() + keyName)
} else {
return b.store.DeleteKey(keyName)
}
}
// SessionDetail returns the session detail using the storage engine (either in memory or Redis)
func (b *DefaultSessionManager) SessionDetail(keyName string, hashed bool) (user.SessionState, bool) {
var jsonKeyVal string
var err error
var session user.SessionState
// get session by key
if hashed {
jsonKeyVal, err = b.store.GetRawKey(b.store.GetKeyPrefix() + keyName)
} else {
jsonKeyVal, err = b.store.GetKey(keyName)
}
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "auth-mgr",
"inbound-key": obfuscateKey(keyName),
"err": err,
}).Debug("Could not get session detail, key not found")
return session, false
}
if err := json.Unmarshal([]byte(jsonKeyVal), &session); err != nil {
log.Error("Couldn't unmarshal session object (may be cache miss): ", err)
return session, false
}
return session, true
}
func (b *DefaultSessionManager) Stop() {}
// Sessions returns all sessions in the key store that match a filter key (a prefix)
func (b *DefaultSessionManager) Sessions(filter string) []string {
return b.store.GetKeys(filter)
}
type DefaultKeyGenerator struct{}
func generateToken(orgID, keyID string) string {
keyID = strings.TrimPrefix(keyID, orgID)
token, err := storage.GenerateToken(orgID, keyID, config.Global().HashKeyFunction)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "auth-mgr",
"orgID": orgID,
}).WithError(err).Warning("Issue during token generation")
}
return token
}
// GenerateAuthKey is a utility function for generating new auth keys. Returns the storage key name and the actual key
func (DefaultKeyGenerator) GenerateAuthKey(orgID string) string {
return generateToken(orgID, "")
}
// GenerateHMACSecret is a utility function for generating new auth keys. Returns the storage key name and the actual key
func (DefaultKeyGenerator) GenerateHMACSecret() string {
u5 := uuid.NewV4()
cleanSting := strings.Replace(u5.String(), "-", "", -1)
return base64.StdEncoding.EncodeToString([]byte(cleanSting))
}