/
rpc_storage_handler_test.go
331 lines (281 loc) · 9.21 KB
/
rpc_storage_handler_test.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
319
320
321
322
323
324
325
326
327
328
329
330
331
package gateway
import (
"fmt"
"net/http"
"testing"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/config"
"github.com/lonelycode/osin"
"github.com/stretchr/testify/assert"
"github.com/TykTechnologies/tyk/header"
"github.com/TykTechnologies/tyk/storage"
"github.com/TykTechnologies/tyk/test"
"github.com/TykTechnologies/tyk/user"
)
const (
RevokeOauthHashedToken = "RevokeOauthHashedToken"
RevokeOauthToken = "RevokeOauthToken"
RevokeOauthRefreshToken = "RevokeOauthRefreshToken"
RevokeOauthRefreshHashedToken = "RevokeOauthRefreshHashedToken" // we do not support hashed refresh tokens yet
DefaultOrg = "default-org-id"
)
func buildStringEvent(eventType, token, apiId string) string {
switch eventType {
case RevokeOauthHashedToken:
// string is as= {the-hashed-token}#hashed:{api-id}:oAuthRevokeToken
token = storage.HashStr(token)
return fmt.Sprintf("%s#hashed:%s:oAuthRevokeToken", token, apiId)
case RevokeOauthToken:
// string is as= {the-token}:{api-id}:oAuthRevokeToken
return fmt.Sprintf("%s:%s:oAuthRevokeToken", token, apiId)
case RevokeOauthRefreshToken:
// string is as= {the-token}:{api-id}:oAuthRevokeToken
return fmt.Sprintf("%s:%s:oAuthRevokeRefreshToken", token, apiId)
case RevokeOauthRefreshHashedToken:
// string is as= {the-token}:{api-id}:oAuthRevokeToken
return fmt.Sprintf("%s:%s:oAuthRevokeToken", token, apiId)
}
return ""
}
func getAccessToken(td tokenData) string {
return td.AccessToken
}
func getRefreshToken(td tokenData) string {
return td.RefreshToken
}
func TestProcessKeySpaceChangesForOauth(t *testing.T) {
cases := []struct {
TestName string
Event string
Hashed bool
GetToken func(td tokenData) string
}{
{
TestName: RevokeOauthToken,
Event: RevokeOauthToken,
Hashed: false,
GetToken: getAccessToken,
},
{
TestName: RevokeOauthHashedToken,
Event: RevokeOauthHashedToken,
Hashed: true,
GetToken: getAccessToken,
},
{
TestName: RevokeOauthRefreshToken,
Event: RevokeOauthRefreshToken,
Hashed: false,
GetToken: getRefreshToken,
},
}
for _, tc := range cases {
t.Run(tc.TestName, func(t *testing.T) {
ts := StartTest(nil)
defer ts.Close()
globalConf := ts.Gw.GetConfig()
globalConf.HashKeys = tc.Hashed
ts.Gw.SetConfig(globalConf)
rpcListener := RPCStorageHandler{
KeyPrefix: "rpc.listener.",
SuppressRegister: true,
HashKeys: tc.Hashed,
Gw: ts.Gw,
}
myApi := ts.LoadTestOAuthSpec()
oauthClient := ts.createTestOAuthClient(myApi, authClientID)
tokenData := getToken(t, ts)
token := tc.GetToken(tokenData)
var getKeyFromStore func(string) (string, error)
if tc.Event == RevokeOauthRefreshToken {
//Refresh token are threated in a different way due that they reside in a different level and we cannot access them directly
client := new(OAuthClient)
client.MetaData = oauthClient.MetaData
client.Description = oauthClient.Description
client.ClientSecret = oauthClient.GetSecret()
client.PolicyID = oauthClient.PolicyID
client.ClientRedirectURI = oauthClient.ClientRedirectURI
storage := myApi.OAuthManager.OsinServer.Storage
ret := &osin.AccessData{
AccessToken: tokenData.AccessToken,
RefreshToken: tokenData.RefreshToken,
Client: client,
}
storage.SaveAccess(ret)
getKeyFromStore = func(token string) (string, error) {
accessData, err := storage.LoadRefresh(token)
var refresh string
if accessData != nil {
refresh = accessData.RefreshToken
}
return refresh, err
}
} else {
getKeyFromStore = ts.Gw.GlobalSessionManager.Store().GetKey
ts.Gw.GlobalSessionManager.Store().DeleteAllKeys()
err := ts.Gw.GlobalSessionManager.Store().SetRawKey(token, token, 100)
assert.NoError(t, err)
_, err = ts.Gw.GlobalSessionManager.Store().GetRawKey(token)
assert.NoError(t, err)
}
stringEvent := buildStringEvent(tc.Event, token, myApi.APIID)
rpcListener.ProcessKeySpaceChanges([]string{stringEvent}, myApi.OrgID)
found, err := getKeyFromStore(token)
if err == nil {
t.Error(" key not removed. event:", stringEvent, " found:", found)
} else {
assert.Equal(t, err.Error(), "key not found", "expected error msg is 'key not found'")
}
})
}
}
func TestProcessKeySpaceChanges_ResetQuota(t *testing.T) {
g := StartTest(nil)
defer g.Close()
rpcListener := RPCStorageHandler{
KeyPrefix: "rpc.listener.",
SuppressRegister: true,
HashKeys: false,
Gw: g.Gw,
}
g.Gw.GlobalSessionManager.Store().DeleteAllKeys()
defer g.Gw.GlobalSessionManager.Store().DeleteAllKeys()
api := g.Gw.BuildAndLoadAPI(func(spec *APISpec) {
spec.UseKeylessAccess = false
spec.Proxy.ListenPath = "/api"
})[0]
session, key := g.CreateSession(func(s *user.SessionState) {
s.AccessRights = map[string]user.AccessDefinition{api.APIID: {
APIID: api.APIID,
Limit: user.APILimit{
QuotaMax: 30,
},
}}
})
auth := map[string]string{
header.Authorization: key,
}
// Call 3 times
_, _ = g.Run(t, []test.TestCase{
{Path: "/api", Headers: auth, Code: http.StatusOK},
{Path: "/api", Headers: auth, Code: http.StatusOK},
{Path: "/api", Headers: auth, Code: http.StatusOK},
}...)
// AllowanceScope is api id.
quotaKey := QuotaKeyPrefix + api.APIID + "-" + key
quotaCounter, err := g.Gw.GlobalSessionManager.Store().GetRawKey(quotaKey)
assert.NoError(t, err)
assert.Equal(t, "3", quotaCounter)
rpcListener.ProcessKeySpaceChanges([]string{key + ":resetQuota", key}, api.OrgID)
// mock of key reload in mdcb environment
err = g.Gw.GlobalSessionManager.UpdateSession(key, session, 0, false)
assert.NoError(t, err)
// Call 1 time
_, _ = g.Run(t, test.TestCase{Path: "/api", Headers: auth, Code: http.StatusOK})
// ProcessKeySpaceChanges should reset the quota counter, it should be 1 instead of 4.
quotaCounter, err = g.Gw.GlobalSessionManager.Store().GetRawKey(quotaKey)
assert.NoError(t, err)
assert.Equal(t, "1", quotaCounter)
}
// TestRPCUpdateKey check that on update key event the key still exist in worker redis
func TestRPCUpdateKey(t *testing.T) {
cases := []struct {
TestName string
Hashed bool
EventPostfix string
}{
{
TestName: "TestRPCUpdateKey unhashed",
Hashed: false,
EventPostfix: "",
}, {
TestName: "TestRPCUpdateKey hashed",
Hashed: true,
EventPostfix: ":hashed",
},
}
for _, tc := range cases {
t.Run(tc.TestName, func(t *testing.T) {
g := StartTest(func(globalConf *config.Config) {
globalConf.HashKeys = tc.Hashed
})
defer g.Close()
rpcListener := RPCStorageHandler{
KeyPrefix: "rpc.listener.",
SuppressRegister: true,
HashKeys: tc.Hashed,
Gw: g.Gw,
}
g.Gw.GlobalSessionManager.Store().DeleteAllKeys()
defer g.Gw.GlobalSessionManager.Store().DeleteAllKeys()
api := g.Gw.BuildAndLoadAPI(func(spec *APISpec) {
spec.UseKeylessAccess = false
spec.Proxy.ListenPath = "/api"
})[0]
session, key := g.CreateSession(func(s *user.SessionState) {
s.AccessRights = map[string]user.AccessDefinition{api.APIID: {
APIID: api.APIID,
Limit: user.APILimit{
QuotaMax: 30,
},
}}
})
auth := map[string]string{
header.Authorization: key,
}
_, _ = g.Run(t, []test.TestCase{
{Path: "/api", Headers: auth, Code: http.StatusOK},
}...)
tags := []string{"test"}
session.Tags = tags
err := g.Gw.GlobalSessionManager.UpdateSession(key, session, 0, tc.Hashed)
assert.NoError(t, err)
rpcListener.ProcessKeySpaceChanges([]string{"apikey-" + key + tc.EventPostfix}, api.OrgID)
myUpdatedSession, newSessFound := g.Gw.GlobalSessionManager.SessionDetail(api.OrgID, key, tc.Hashed)
assert.True(t, newSessFound, "key should be found")
assert.Equal(t, tags, myUpdatedSession.Tags)
})
}
}
func TestGetGroupLoginCallback(t *testing.T) {
tcs := []struct {
testName string
syncEnabled bool
givenKey string
givenGroup string
expectedCallbackResponse interface{}
}{
{
testName: "sync disabled",
syncEnabled: false,
givenKey: "key",
givenGroup: "group",
expectedCallbackResponse: apidef.GroupLoginRequest{UserKey: "key", GroupID: "group"},
},
{
testName: "sync enabled",
syncEnabled: true,
givenKey: "key",
givenGroup: "group",
expectedCallbackResponse: apidef.GroupLoginRequest{UserKey: "key", GroupID: "group", ForceSync: true},
},
}
for _, tc := range tcs {
t.Run(tc.testName, func(t *testing.T) {
g := StartTest(func(globalConf *config.Config) {
globalConf.SlaveOptions.SynchroniserEnabled = tc.syncEnabled
})
defer g.Close()
defer g.Gw.GlobalSessionManager.Store().DeleteAllKeys()
rpcListener := RPCStorageHandler{
KeyPrefix: "rpc.listener.",
SuppressRegister: true,
Gw: g.Gw,
}
fn := rpcListener.getGroupLoginCallback(tc.syncEnabled)
groupLogin, ok := fn(tc.givenKey, tc.givenGroup).(apidef.GroupLoginRequest)
assert.True(t, ok)
assert.Equal(t, tc.expectedCallbackResponse, groupLogin)
})
}
}