forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_definition_test.go
345 lines (289 loc) · 8.46 KB
/
api_definition_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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package main
import (
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/garyburd/redigo/redis"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/test"
"github.com/TykTechnologies/tyk/user"
)
func createDefinitionFromString(defStr string) *APISpec {
loader := APIDefinitionLoader{}
def := loader.ParseDefinition(strings.NewReader(defStr))
spec := loader.MakeSpec(def)
return spec
}
func TestWhitelist(t *testing.T) {
ts := newTykTestServer()
defer ts.Close()
t.Run("Extended Paths", func(t *testing.T) {
buildAndLoadAPI(func(spec *APISpec) {
updateAPIVersion(spec, "v1", func(v *apidef.VersionInfo) {
json.Unmarshal([]byte(`[
{
"path": "/reply/{id}",
"method_actions": {
"GET": {"action": "reply", "code": 200, "data": "flump"}
}
},
{
"path": "/get",
"method_actions": {"GET": {"action": "no_action"}}
}
]`), &v.ExtendedPaths.WhiteList)
})
spec.Proxy.ListenPath = "/"
})
ts.Run(t, []test.TestCase{
// Should mock path
{Path: "/reply/", Code: 200, BodyMatch: "flump"},
{Path: "/reply/123", Code: 200, BodyMatch: "flump"},
// Should get original upstream response
{Path: "/get", Code: 200, BodyMatch: `"Url":"/get"`},
// Reject not whitelisted (but know by upstream) path
{Method: "POST", Path: "/post", Code: 403},
}...)
})
t.Run("Simple Paths", func(t *testing.T) {
buildAndLoadAPI(func(spec *APISpec) {
updateAPIVersion(spec, "v1", func(v *apidef.VersionInfo) {
v.Paths.WhiteList = []string{"/simple", "/regex/{id}/test"}
v.UseExtendedPaths = false
})
spec.Proxy.ListenPath = "/"
})
ts.Run(t, []test.TestCase{
// Should mock path
{Path: "/simple", Code: 200},
{Path: "/regex/123/test", Code: 200},
{Path: "/regex/123/differ", Code: 403},
{Path: "/", Code: 403},
}...)
})
}
func TestBlacklist(t *testing.T) {
ts := newTykTestServer()
defer ts.Close()
t.Run("Extended Paths", func(t *testing.T) {
buildAndLoadAPI(func(spec *APISpec) {
updateAPIVersion(spec, "v1", func(v *apidef.VersionInfo) {
json.Unmarshal([]byte(`[
{
"path": "/blacklist/literal",
"method_actions": {"GET": {"action": "no_action"}}
},
{
"path": "/blacklist/{id}/test",
"method_actions": {"GET": {"action": "no_action"}}
}
]`), &v.ExtendedPaths.BlackList)
})
spec.Proxy.ListenPath = "/"
})
ts.Run(t, []test.TestCase{
{Path: "/blacklist/literal", Code: 403},
{Path: "/blacklist/123/test", Code: 403},
{Path: "/blacklist/123/different", Code: 200},
// POST method not blacklisted
{Method: "POST", Path: "/blacklist/literal", Code: 200},
}...)
})
t.Run("Simple Paths", func(t *testing.T) {
buildAndLoadAPI(func(spec *APISpec) {
updateAPIVersion(spec, "v1", func(v *apidef.VersionInfo) {
v.Paths.BlackList = []string{"/blacklist/literal", "/blacklist/{id}/test"}
v.UseExtendedPaths = false
})
spec.Proxy.ListenPath = "/"
})
ts.Run(t, []test.TestCase{
{Path: "/blacklist/literal", Code: 403},
{Path: "/blacklist/123/test", Code: 403},
{Path: "/blacklist/123/different", Code: 200},
// POST method also blacklisted
{Method: "POST", Path: "/blacklist/literal", Code: 403},
}...)
})
}
func TestIgnored(t *testing.T) {
ts := newTykTestServer()
defer ts.Close()
t.Run("Extended Paths", func(t *testing.T) {
buildAndLoadAPI(func(spec *APISpec) {
updateAPIVersion(spec, "v1", func(v *apidef.VersionInfo) {
json.Unmarshal([]byte(`[
{
"path": "/ignored/literal",
"method_actions": {"GET": {"action": "no_action"}}
},
{
"path": "/ignored/{id}/test",
"method_actions": {"GET": {"action": "no_action"}}
}
]`), &v.ExtendedPaths.Ignored)
})
spec.UseKeylessAccess = false
spec.Proxy.ListenPath = "/"
})
ts.Run(t, []test.TestCase{
// Should ignore auth check
{Path: "/ignored/literal", Code: 200},
{Path: "/ignored/123/test", Code: 200},
// Only GET is ignored
{Method: "POST", Path: "/ext/ignored/literal", Code: 401},
{Path: "/", Code: 401},
}...)
})
t.Run("Simple Paths", func(t *testing.T) {
buildAndLoadAPI(func(spec *APISpec) {
updateAPIVersion(spec, "v1", func(v *apidef.VersionInfo) {
v.Paths.Ignored = []string{"/ignored/literal", "/ignored/{id}/test"}
v.UseExtendedPaths = false
})
spec.UseKeylessAccess = false
spec.Proxy.ListenPath = "/"
})
ts.Run(t, []test.TestCase{
// Should ignore auth check
{Path: "/ignored/literal", Code: 200},
{Path: "/ignored/123/test", Code: 200},
// All methods ignored
{Method: "POST", Path: "/ext/ignored/literal", Code: 200},
{Path: "/", Code: 401},
}...)
})
}
func TestSyncAPISpecsDashboardSuccess(t *testing.T) {
// Mock Dashboard
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/system/apis" {
w.Write([]byte(`{"Status": "OK", "Nonce": "1", "Message": [{"api_definition": {}}]}`))
} else {
t.Fatal("Unknown dashboard API request", r)
}
}))
defer ts.Close()
apisMu.Lock()
apisByID = make(map[string]*APISpec)
apisMu.Unlock()
config.Global.UseDBAppConfigs = true
config.Global.AllowInsecureConfigs = true
config.Global.DBAppConfOptions.ConnectionString = ts.URL
defer func() {
config.Global.UseDBAppConfigs = false
config.Global.AllowInsecureConfigs = false
config.Global.DBAppConfOptions.ConnectionString = ""
}()
var wg sync.WaitGroup
wg.Add(1)
msg := redis.Message{Data: []byte(`{"Command": "ApiUpdated"}`)}
handled := func(got NotificationCommand) {
if want := NoticeApiUpdated; got != want {
t.Fatalf("want %q, got %q", want, got)
}
}
handleRedisEvent(msg, handled, wg.Done)
// Since we already know that reload is queued
reloadTick <- time.Time{}
// Wait for the reload to finish, then check it worked
wg.Wait()
apisMu.RLock()
if len(apisByID) != 1 {
t.Error("Should return array with one spec", apisByID)
}
apisMu.RUnlock()
}
func TestRoundRobin(t *testing.T) {
rr := RoundRobin{}
for _, want := range []int{0, 1, 2, 0} {
if got := rr.WithLen(3); got != want {
t.Errorf("RR Pos wrong: want %d got %d", want, got)
}
}
if got, want := rr.WithLen(0), 0; got != want {
t.Errorf("RR Pos of 0 wrong: want %d got %d", want, got)
}
}
func setupKeepalive(conn net.Conn) error {
tcpConn := conn.(*net.TCPConn)
if err := tcpConn.SetKeepAlive(true); err != nil {
return err
}
if err := tcpConn.SetKeepAlivePeriod(30 * time.Second); err != nil {
return err
}
return nil
}
type customListener struct {
L net.Listener
}
func (ln *customListener) Init(addr string) (err error) {
ln.L, err = net.Listen("tcp", addr)
return
}
func (ln *customListener) Accept() (conn io.ReadWriteCloser, clientAddr string, err error) {
c, err := ln.L.Accept()
if err != nil {
return
}
if err = setupKeepalive(c); err != nil {
c.Close()
return
}
handshake := make([]byte, 6)
if _, err = io.ReadFull(c, handshake); err != nil {
return
}
idLenBuf := make([]byte, 1)
if _, err = io.ReadFull(c, idLenBuf); err != nil {
return
}
idLen := uint8(idLenBuf[0])
id := make([]byte, idLen)
if _, err = io.ReadFull(c, id); err != nil {
return
}
return c, string(id), nil
}
func (ln *customListener) Close() error {
return ln.L.Close()
}
func TestDefaultVersion(t *testing.T) {
ts := newTykTestServer()
defer ts.Close()
buildAndLoadAPI(func(spec *APISpec) {
v1 := apidef.VersionInfo{Name: "v1"}
v1.Name = "v1"
v1.Paths.WhiteList = []string{"/foo"}
v2 := apidef.VersionInfo{Name: "v2"}
v2.Paths.WhiteList = []string{"/bar"}
spec.VersionDefinition.Location = "url-param"
spec.VersionDefinition.Key = "v"
spec.VersionData.NotVersioned = false
spec.VersionData.Versions["v1"] = v1
spec.VersionData.Versions["v2"] = v2
spec.VersionData.DefaultVersion = "v2"
spec.Proxy.ListenPath = "/"
spec.UseKeylessAccess = false
})
key := createSession(func(s *user.SessionState) {
s.AccessRights = map[string]user.AccessDefinition{"test": {
APIID: "test", Versions: []string{"v1", "v2"},
}}
})
authHeaders := map[string]string{"authorization": key}
ts.Run(t, []test.TestCase{
{Path: "/foo", Headers: authHeaders, Code: 403}, // Not whitelisted for default v2
{Path: "/bar", Headers: authHeaders, Code: 200}, // Whitelisted for default v2
{Path: "/foo?v=v1", Headers: authHeaders, Code: 200}, // Allowed for v1
{Path: "/bar?v=v1", Headers: authHeaders, Code: 403}, // Not allowed for v1
}...)
}