-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathauth_manager_test.go
More file actions
580 lines (454 loc) · 15.5 KB
/
Copy pathauth_manager_test.go
File metadata and controls
580 lines (454 loc) · 15.5 KB
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
package gateway
import (
"crypto/x509"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/TykTechnologies/tyk/certs"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/header"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/storage"
"github.com/TykTechnologies/tyk/test"
"github.com/TykTechnologies/tyk/user"
)
func TestAuthenticationAfterDeleteKey(t *testing.T) {
ts := StartTest(nil)
defer ts.Close()
assert := func(t *testing.T, ts *Test, hashKeys bool) {
t.Helper()
globalConf := ts.Gw.GetConfig()
globalConf.HashKeys = hashKeys
ts.Gw.SetConfig(globalConf)
api := ts.Gw.BuildAndLoadAPI(func(spec *APISpec) {
spec.UseKeylessAccess = false
spec.Proxy.ListenPath = "/"
})[0]
key := CreateSession(ts.Gw, func(s *user.SessionState) {
s.AccessRights = map[string]user.AccessDefinition{api.APIID: {
APIID: api.APIID,
}}
})
deletePath := "/tyk/keys/" + key
authHeader := map[string]string{
"authorization": key,
}
ts.Run(t, []test.TestCase{
{Path: "/get", Headers: authHeader, Code: http.StatusOK},
{Method: http.MethodDelete, Path: deletePath, AdminAuth: true, Code: http.StatusOK, BodyMatch: `"action":"deleted"`},
{Path: "/get", Headers: authHeader, Code: http.StatusForbidden},
}...)
}
t.Run("HashKeys=false", func(t *testing.T) {
assert(t, ts, false)
})
t.Run("HashKeys=true", func(t *testing.T) {
assert(t, ts, true)
})
}
func TestAuthenticationAfterUpdateKey(t *testing.T) {
ts := StartTest(nil)
defer ts.Close()
assert := func(t *testing.T, ts *Test, hashKeys bool) {
t.Helper()
globalConf := ts.Gw.GetConfig()
globalConf.HashKeys = hashKeys
ts.Gw.SetConfig(globalConf)
api := ts.Gw.BuildAndLoadAPI(func(spec *APISpec) {
spec.UseKeylessAccess = false
spec.Proxy.ListenPath = "/"
})[0]
key := ts.Gw.generateToken("", "")
session := CreateStandardSession()
session.AccessRights = map[string]user.AccessDefinition{api.APIID: {
APIID: api.APIID,
}}
err := ts.Gw.GlobalSessionManager.UpdateSession(storage.HashKey(key, ts.Gw.GetConfig().HashKeys), session, 0, ts.Gw.GetConfig().HashKeys)
if err != nil {
t.Error("could not update session in Session Manager. " + err.Error())
}
authHeader := map[string]string{
"authorization": key,
}
ts.Run(t, []test.TestCase{
{Path: "/get", Headers: authHeader, Code: http.StatusOK},
}...)
session.AccessRights = map[string]user.AccessDefinition{"dummy": {
APIID: "dummy",
}}
err = ts.Gw.GlobalSessionManager.UpdateSession(storage.HashKey(key, ts.Gw.GetConfig().HashKeys), session, 0, ts.Gw.GetConfig().HashKeys)
if err != nil {
t.Error("could not update session in Session Manager. " + err.Error())
}
ts.Run(t, []test.TestCase{
{Path: "/get", Headers: authHeader, Code: http.StatusForbidden},
}...)
}
t.Run("HashKeys=false", func(t *testing.T) {
assert(t, ts, false)
})
t.Run("HashKeys=true", func(t *testing.T) {
assert(t, ts, true)
})
}
func TestHashKeyFunctionChanged(t *testing.T) {
orgId := "default"
//We generate the combinedPEM and get its serverCertID
_, _, combinedPEM, _ := certs.GenServerCertificate()
serverCertID, _, _ := certs.GetCertIDAndChainPEM(combinedPEM, "")
client := GetTLSClient(nil, nil)
conf := func(globalConf *config.Config) {
globalConf.HttpServerOptions.UseSSL = true
globalConf.HttpServerOptions.SSLCertificates = []string{serverCertID}
globalConf.HashKeys = true
globalConf.HashKeyFunction = "murmur64"
globalConf.LocalSessionCache.DisableCacheSessionState = true
}
ts := StartTest(conf)
defer ts.Close()
//add the server certificate to the gateway CertificateManager
ts.Gw.CertificateManager.Add(combinedPEM, "")
//We reload the gw proxy so it uses the added server certificate
ts.ReloadGatewayProxy()
clientPEM, _, _, clientCert := certs.GenCertificate(&x509.Certificate{}, false)
clientCertID, err := ts.Gw.CertificateManager.Add(clientPEM, orgId)
if err != nil {
t.Fatal("certificate should be added to cert manager")
}
api := ts.Gw.BuildAndLoadAPI(func(spec *APISpec) {
spec.Proxy.ListenPath = "/"
spec.UseKeylessAccess = false
spec.AuthConfigs = map[string]apidef.AuthConfig{
apidef.AuthTokenType: {UseCertificate: false},
}
})[0]
globalConf := ts.Gw.GetConfig()
testChangeHashFunc := func(t *testing.T, authHeader map[string]string, client *http.Client, failCode int) {
t.Helper()
_, _ = ts.Run(t, test.TestCase{Headers: authHeader, Client: client, Code: http.StatusOK})
globalConf.HashKeyFunction = "sha256"
ts.Gw.SetConfig(globalConf)
_, _ = ts.Run(t, test.TestCase{Headers: authHeader, Client: client, Code: failCode})
globalConf.HashKeyFunctionFallback = []string{"murmur64"}
ts.Gw.SetConfig(globalConf)
_, _ = ts.Run(t, test.TestCase{Headers: authHeader, Client: client, Code: http.StatusOK})
// Reset
globalConf.HashKeyFunction = "murmur64"
globalConf.HashKeyFunctionFallback = nil
ts.Gw.SetConfig(globalConf)
}
t.Run("custom key", func(t *testing.T) {
const customKey = "custom-key"
session := CreateStandardSession()
session.AccessRights = map[string]user.AccessDefinition{"test": {
APIID: "test", Versions: []string{"v1"},
}}
_, _ = ts.Run(t, test.TestCase{AdminAuth: true, Method: http.MethodPost, Path: "/tyk/keys/" + customKey,
Data: session, Client: client, Code: http.StatusOK})
testChangeHashFunc(t, map[string]string{header.Authorization: customKey}, client, http.StatusForbidden)
})
t.Run("basic auth key", func(t *testing.T) {
api.UseBasicAuth = true
api.AuthConfigs = map[string]apidef.AuthConfig{
apidef.AuthTokenType: {UseCertificate: true},
}
ts.Gw.LoadAPI(api)
globalConf = ts.Gw.GetConfig()
session := CreateStandardSession()
session.BasicAuthData.Password = "password"
session.AccessRights = map[string]user.AccessDefinition{"test": {
APIID: "test", Versions: []string{"v1"},
}}
_, _ = ts.Run(t, test.TestCase{
AdminAuth: true,
Method: http.MethodPost,
Path: "/tyk/keys/user",
Data: session,
Client: client,
Code: http.StatusOK,
})
authHeader := map[string]string{"Authorization": genAuthHeader("user", "password")}
testChangeHashFunc(t, authHeader, client, http.StatusUnauthorized)
api.UseBasicAuth = false
ts.Gw.LoadAPI(api)
globalConf = ts.Gw.GetConfig()
})
t.Run("client certificate", func(t *testing.T) {
api.UseBasicAuth = false
api.AuthConfigs = map[string]apidef.AuthConfig{
apidef.AuthTokenType: {UseCertificate: true},
}
ts.Gw.LoadAPI(api)
session := CreateStandardSession()
session.Certificate = clientCertID
session.BasicAuthData.Password = "password"
session.AccessRights = map[string]user.AccessDefinition{"test": {
APIID: "test", Versions: []string{"v1"},
}}
_, _ = ts.Run(t, test.TestCase{AdminAuth: true, Method: http.MethodPost, Path: "/tyk/keys/create",
Data: session, Client: client, Code: http.StatusOK})
client = GetTLSClient(&clientCert, nil)
testChangeHashFunc(t, nil, client, http.StatusUnauthorized)
})
}
func TestResetQuotaObfuscate(t *testing.T) {
t.Run("Obfuscate key", func(t *testing.T) {
conf := func(globalConf *config.Config) {
globalConf.HashKeys = false
globalConf.EnableKeyLogging = false
}
ts := StartTest(conf)
sessionManager := DefaultSessionManager{Gw: ts.Gw}
t.Cleanup(func() {
ts.Close()
})
actual := sessionManager.ResetQuotaObfuscateKey("481408ygjkbs")
assert.Equal(t, "****jkbs", actual)
})
t.Run("Does not Obfuscate key", func(t *testing.T) {
conf := func(globalConf *config.Config) {
globalConf.HashKeys = true
globalConf.EnableKeyLogging = true
}
ts := StartTest(conf)
sessionManager := DefaultSessionManager{Gw: ts.Gw}
t.Cleanup(func() {
ts.Close()
})
actual := sessionManager.ResetQuotaObfuscateKey("481408ygjkbs")
assert.Equal(t, "481408ygjkbs", actual)
})
}
// TestCustomKeysEdgeGw check that custom keys are processed
// by edge gw when a keySpace signal is received
func TestCustomKeysEdgeGw(t *testing.T) {
const customKey = "my-custom-key"
orgId := "default"
testCases := []struct {
name string
useCustomKey bool
}{
{
name: "sending event with custom key",
useCustomKey: true,
},
{
name: "sending event with base64 representation",
useCustomKey: false,
},
}
hashKeys := []bool{true, false}
for _, hashed := range hashKeys {
t.Run(fmt.Sprintf("HashKeys: %v", hashed), func(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// 1- execute an edge gw
ts := StartTest(func(globalConf *config.Config) {
globalConf.SlaveOptions.GroupID = "group"
globalConf.LivenessCheck.CheckDuration = 1000000000
globalConf.SlaveOptions.APIKey = "apikey-test"
globalConf.HashKeys = hashed
globalConf.SlaveOptions.SynchroniserEnabled = hashed
})
defer ts.Close()
rpcListener := RPCStorageHandler{
KeyPrefix: "rpc.listener.",
SuppressRegister: true,
HashKeys: hashed,
Gw: ts.Gw,
}
key := customKey
if !tc.useCustomKey {
key = ts.Gw.generateToken(orgId, key)
}
// 2- creates a custom key
session := CreateStandardSession()
session.AccessRights = map[string]user.AccessDefinition{"test": {
APIID: "test", Versions: []string{"v1"},
}}
client := GetTLSClient(nil, nil)
resp, err := ts.Run(t, test.TestCase{AdminAuth: true, Method: http.MethodPost, Path: "/tyk/keys/" + customKey,
Data: session, Client: client, Code: http.StatusOK})
assert.Nil(t, err)
defer func() {
err = resp.Body.Close()
assert.Nil(t, err)
}()
body, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
keyResp := apiModifyKeySuccess{}
err = json.Unmarshal(body, &keyResp)
assert.NoError(t, err)
if hashed {
key = keyResp.KeyHash
}
// 3- double check that key exists
_, found := ts.Gw.GlobalSessionManager.SessionDetail(orgId, key, hashed)
assert.True(t, found)
keyEvent := key
if hashed {
keyEvent += ":hashed"
}
// 4- emit events so edge process it
rpcListener.ProcessKeySpaceChanges([]string{keyEvent}, orgId)
// 5- key should not exist in edge as it was removed
_, found = ts.Gw.GlobalSessionManager.SessionDetail(orgId, key, hashed)
assert.False(t, found)
})
}
})
}
}
func TestDeleteRawKeysWithAllowanceScope(t *testing.T) {
sessionManager := DefaultSessionManager{}
t.Run("should not panic if storage.Handler is nil", func(t *testing.T) {
session := &user.SessionState{
AccessRights: map[string]user.AccessDefinition{
"ar1": {AllowanceScope: "scope1"},
},
}
sessionManager.deleteRawKeysWithAllowanceScope(nil, session, "keyName")
})
t.Run("should not panic if session is nil", func(t *testing.T) {
handler := newCountingStorageHandler()
sessionManager.deleteRawKeysWithAllowanceScope(handler, nil, "keyName")
assert.Equal(t, 0, handler.deleteRawKeyCount)
})
t.Run("should not call DeleteRawKey of the storage handler if no allowance scope is defined in any AccessDefinition", func(t *testing.T) {
// Lets create 10,000 elements, see TT-11721
const elementsCount = 10_000
accessRights := make(map[string]user.AccessDefinition, elementsCount)
for i := 0; i < elementsCount; i++ {
key := fmt.Sprintf("ar-%d", i)
accessRights[key] = user.AccessDefinition{AllowanceScope: ""}
}
session := &user.SessionState{
AccessRights: accessRights,
}
handler := newCountingStorageHandler()
sessionManager.deleteRawKeysWithAllowanceScope(handler, session, "keyName")
assert.Equal(t, 0, handler.deleteRawKeyCount)
})
t.Run("should only call DeleteRawKey of the storage handler as many times as allowance scopes are defined", func(t *testing.T) {
session := &user.SessionState{
AccessRights: map[string]user.AccessDefinition{
"ar1": {AllowanceScope: ""},
"ar2": {AllowanceScope: "scope2"},
"ar3": {AllowanceScope: "scope3"},
"ar4": {AllowanceScope: ""},
},
}
handler := newCountingStorageHandler()
sessionManager.deleteRawKeysWithAllowanceScope(handler, session, "keyName")
assert.Equal(t, 2, handler.deleteRawKeyCount)
})
}
type countingStorageHandler struct {
deleteRawKeyMutex *sync.Mutex
deleteRawKeyCount int
}
func newCountingStorageHandler() *countingStorageHandler {
return &countingStorageHandler{
deleteRawKeyMutex: &sync.Mutex{},
deleteRawKeyCount: 0,
}
}
func (c *countingStorageHandler) GetKey(s string) (string, error) {
return "", nil
}
func (c *countingStorageHandler) GetMultiKey(strings []string) ([]string, error) {
return nil, nil
}
func (c *countingStorageHandler) GetRawKey(s string) (string, error) {
return "", nil
}
func (c *countingStorageHandler) SetKey(s string, s2 string, i int64) error {
return nil
}
func (c *countingStorageHandler) SetRawKey(s string, s2 string, i int64) error {
return nil
}
func (c *countingStorageHandler) SetExp(s string, i int64) error {
return nil
}
func (c *countingStorageHandler) GetExp(s string) (int64, error) {
return 0, nil
}
func (c *countingStorageHandler) GetKeys(s string) []string {
return nil
}
func (c *countingStorageHandler) DeleteKey(s string) bool {
return false
}
func (c *countingStorageHandler) DeleteAllKeys() bool {
return false
}
func (c *countingStorageHandler) DeleteRawKey(s string) bool {
c.deleteRawKeyMutex.Lock()
defer c.deleteRawKeyMutex.Unlock()
c.deleteRawKeyCount++
return true
}
func (c *countingStorageHandler) DeleteRawKeys(keys []string) bool {
c.deleteRawKeyMutex.Lock()
defer c.deleteRawKeyMutex.Unlock()
c.deleteRawKeyCount += len(keys)
return true
}
func (c *countingStorageHandler) Connect() bool {
return false
}
func (c *countingStorageHandler) GetKeysAndValues() map[string]string {
return nil
}
func (c *countingStorageHandler) GetKeysAndValuesWithFilter(s string) map[string]string {
return nil
}
func (c *countingStorageHandler) DeleteKeys(_ []string) bool {
return false
}
func (c *countingStorageHandler) Decrement(s string) {}
func (c *countingStorageHandler) IncrememntWithExpire(s string, i int64) int64 {
return 0
}
func (c *countingStorageHandler) SetRollingWindow(key string, per int64, val string, pipeline bool) (int, []interface{}) {
return 0, nil
}
func (c *countingStorageHandler) GetRollingWindow(key string, per int64, pipeline bool) (int, []interface{}) {
return 0, nil
}
func (c *countingStorageHandler) GetSet(s string) (map[string]string, error) {
return nil, nil
}
func (c *countingStorageHandler) AddToSet(s string, s2 string) {}
func (c *countingStorageHandler) GetAndDeleteSet(s string) []interface{} {
return nil
}
func (c *countingStorageHandler) RemoveFromSet(s string, s2 string) {}
func (c *countingStorageHandler) DeleteScanMatch(s string) bool {
return false
}
func (c *countingStorageHandler) GetKeyPrefix() string {
return ""
}
func (c *countingStorageHandler) AddToSortedSet(s string, s2 string, f float64) {}
func (c *countingStorageHandler) GetSortedSetRange(s string, s2 string, s3 string) ([]string, []float64, error) {
return nil, nil, nil
}
func (c *countingStorageHandler) RemoveSortedSetRange(s string, s2 string, s3 string) error {
return nil
}
func (c *countingStorageHandler) GetListRange(s string, i int64, i2 int64) ([]string, error) {
return nil, nil
}
func (c *countingStorageHandler) RemoveFromList(s string, s2 string) error {
return nil
}
func (c *countingStorageHandler) AppendToSet(s string, s2 string) {}
func (c *countingStorageHandler) Exists(s string) (bool, error) {
return false, nil
}