/
testutil.go
1049 lines (907 loc) · 27.7 KB
/
testutil.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
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gateway
import (
"archive/zip"
"bytes"
"compress/gzip"
"crypto/tls"
"crypto/x509"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/go-redis/redis"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
uuid "github.com/satori/go.uuid"
"golang.org/x/net/context"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/cli"
"github.com/TykTechnologies/tyk/config"
"github.com/TykTechnologies/tyk/storage"
"github.com/TykTechnologies/tyk/test"
"github.com/TykTechnologies/tyk/user"
)
var (
// to register to, but never used
discardMuxer = mux.NewRouter()
// to simulate time ticks for tests that do reloads
ReloadTick = make(chan time.Time)
// Used to store the test bundles:
testMiddlewarePath, _ = ioutil.TempDir("", "tyk-middleware-path")
mockHandle *test.DnsMockHandle
testServerRouter *mux.Router
defaultTestConfig config.Config
EnableTestDNSMock = true
)
func InitTestMain(ctx context.Context, m *testing.M, genConf ...func(globalConf *config.Config)) int {
setTestMode(true)
testServerRouter = testHttpHandler()
testServer := &http.Server{
Addr: testHttpListen,
Handler: testServerRouter,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
MaxHeaderBytes: 1 << 20,
}
globalConf := config.Global()
if err := config.WriteDefault("", &globalConf); err != nil {
panic(err)
}
globalConf.Storage.Database = rand.Intn(15)
var err error
globalConf.AppPath, err = ioutil.TempDir("", "tyk-test-")
if err != nil {
panic(err)
}
globalConf.EnableAnalytics = true
globalConf.AnalyticsConfig.EnableGeoIP = true
_, b, _, _ := runtime.Caller(0)
gatewayPath := filepath.Dir(b)
rootPath := filepath.Dir(gatewayPath)
globalConf.AnalyticsConfig.GeoIPDBLocation = filepath.Join(rootPath, "testdata", "MaxMind-DB-test-ipv4-24.mmdb")
globalConf.EnableJSVM = true
globalConf.HashKeyFunction = storage.HashMurmur64
globalConf.Monitor.EnableTriggerMonitors = true
globalConf.AnalyticsConfig.NormaliseUrls.Enabled = true
globalConf.AllowInsecureConfigs = true
// Enable coprocess and bundle downloader:
globalConf.CoProcessOptions.EnableCoProcess = true
globalConf.EnableBundleDownloader = true
globalConf.BundleBaseURL = testHttpBundles
globalConf.MiddlewarePath = testMiddlewarePath
purgeTicker = make(chan time.Time)
rpcPurgeTicker = make(chan time.Time)
// force ipv4 for now, to work around the docker bug affecting
// Go 1.8 and ealier
globalConf.ListenAddress = "127.0.0.1"
if len(genConf) > 0 {
genConf[0](&globalConf)
}
if EnableTestDNSMock {
mockHandle, err = test.InitDNSMock(test.DomainsToAddresses, nil)
if err != nil {
panic(err)
}
defer mockHandle.ShutdownDnsMock()
}
go func() {
err := testServer.ListenAndServe()
if err != nil {
log.Warn("testServer.ListenAndServe() err: ", err.Error())
}
}()
defer testServer.Shutdown(context.Background())
CoProcessInit()
afterConfSetup(&globalConf)
defaultTestConfig = globalConf
config.SetGlobal(globalConf)
if err := emptyRedis(); err != nil {
panic(err)
}
cli.Init(VERSION, confPaths)
initialiseSystem(ctx)
// Small part of start()
loadAPIEndpoints(mainRouter())
if analytics.GeoIPDB == nil {
panic("GeoIPDB was not initialized")
}
go startPubSubLoop()
go reloadLoop(ReloadTick)
go reloadQueueLoop()
go reloadSimulation()
exitCode := m.Run()
os.RemoveAll(config.Global().AppPath)
return exitCode
}
func ResetTestConfig() {
config.SetGlobal(defaultTestConfig)
}
func emptyRedis() error {
addr := config.Global().Storage.Host + ":" + strconv.Itoa(config.Global().Storage.Port)
c := redis.NewClient(&redis.Options{Addr: addr})
defer c.Close()
dbName := strconv.Itoa(config.Global().Storage.Database)
if err := c.Do("SELECT", dbName).Err(); err != nil {
return err
}
err := c.FlushDB().Err()
return err
}
// simulate reloads in the background, i.e. writes to
// global variables that should not be accessed in a
// racy way like the policies and api specs maps.
func reloadSimulation() {
for {
policiesMu.Lock()
policiesByID["_"] = user.Policy{}
delete(policiesByID, "_")
policiesMu.Unlock()
apisMu.Lock()
old := apiSpecs
apiSpecs = append(apiSpecs, nil)
apiSpecs = old
apisByID["_"] = nil
delete(apisByID, "_")
apisMu.Unlock()
time.Sleep(5 * time.Millisecond)
}
}
// map[bundleName]map[fileName]fileContent
var testBundles = map[string]map[string]string{}
var testBundleMu sync.Mutex
func RegisterBundle(name string, files map[string]string) string {
testBundleMu.Lock()
defer testBundleMu.Unlock()
bundleID := name + "-" + uuid.NewV4().String() + ".zip"
testBundles[bundleID] = files
return bundleID
}
func bundleHandleFunc(w http.ResponseWriter, r *http.Request) {
testBundleMu.Lock()
defer testBundleMu.Unlock()
bundleName := strings.Replace(r.URL.Path, "/bundles/", "", -1)
bundle, exists := testBundles[bundleName]
if !exists {
log.Warning(testBundles)
http.Error(w, "Bundle not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/zip")
z := zip.NewWriter(w)
for name, content := range bundle {
f, _ := z.Create(name)
f.Write([]byte(content))
}
z.Close()
}
func mainRouter() *mux.Router {
return getMainRouter(defaultProxyMux)
}
func mainProxy() *proxy {
return defaultProxyMux.getProxy(config.Global().ListenPort)
}
func controlProxy() *proxy {
p := defaultProxyMux.getProxy(config.Global().ControlAPIPort)
if p != nil {
return p
}
return mainProxy()
}
func EnablePort(port int, protocol string) {
c := config.Global()
if c.PortWhiteList == nil {
c.PortWhiteList = map[string]config.PortWhiteList{
protocol: {
Ports: []int{port},
},
}
} else {
m, ok := c.PortWhiteList[protocol]
if !ok {
m = config.PortWhiteList{
Ports: []int{port},
}
} else {
m.Ports = append(m.Ports, port)
}
c.PortWhiteList[protocol] = m
}
config.SetGlobal(c)
}
func getMainRouter(m *proxyMux) *mux.Router {
var protocol string
if config.Global().HttpServerOptions.UseSSL {
protocol = "https"
} else {
protocol = "http"
}
return m.router(config.Global().ListenPort, protocol)
}
type TestHttpResponse struct {
Method string
URI string
Url string
Body string
Headers map[string]string
Form map[string]string
}
// ProxyHandler Proxies requests through to their final destination, if they make it through the middleware chain.
func ProxyHandler(p *ReverseProxy, apiSpec *APISpec) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
baseMid := BaseMiddleware{Spec: apiSpec, Proxy: p}
handler := SuccessHandler{baseMid}
// Skip all other execution
handler.ServeHTTP(w, r)
})
}
const (
// We need a static port so that the urls can be used in static
// test data, and to prevent the requests from being randomized
// for checksums. Port 16500 should be obscure and unused.
testHttpListen = "127.0.0.1:16500"
// Accepts any http requests on /, only allows GET on /get, etc.
// All return a JSON with request info.
TestHttpAny = "http://" + testHttpListen
TestHttpGet = TestHttpAny + "/get"
testHttpPost = TestHttpAny + "/post"
testHttpJWK = TestHttpAny + "/jwk.json"
testHttpJWKDER = TestHttpAny + "/jwk-der.json"
testHttpBundles = TestHttpAny + "/bundles/"
// Nothing should be listening on port 16501 - useful for
// testing TCP and HTTP failures.
testHttpFailure = "127.0.0.1:16501"
testHttpFailureAny = "http://" + testHttpFailure
MockOrgID = "507f1f77bcf86cd799439011"
)
func testHttpHandler() *mux.Router {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
wsHandler := func(w http.ResponseWriter, req *http.Request) {
conn, err := upgrader.Upgrade(w, req, nil)
if err != nil {
http.Error(w, fmt.Sprintf("cannot upgrade: %v", err), http.StatusInternalServerError)
}
// start simple reader/writer per connection
go func() {
for {
mt, p, err := conn.ReadMessage()
if err != nil {
return
}
conn.WriteMessage(mt, []byte("reply to message: "+string(p)))
}
}()
}
httpError := func(w http.ResponseWriter, status int) {
http.Error(w, http.StatusText(status), status)
}
writeDetails := func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
httpError(w, http.StatusInternalServerError)
return
}
r.URL.Opaque = r.URL.RawPath
w.Header().Set("X-Tyk-Test", "1")
body, _ := ioutil.ReadAll(r.Body)
err := json.NewEncoder(w).Encode(TestHttpResponse{
Method: r.Method,
URI: r.RequestURI,
Url: r.URL.String(),
Headers: firstVals(r.Header),
Form: firstVals(r.Form),
Body: string(body),
})
if err != nil {
httpError(w, http.StatusInternalServerError)
}
}
handleMethod := func(method string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if method != "" && r.Method != method {
httpError(w, http.StatusMethodNotAllowed)
} else {
writeDetails(w, r)
}
}
}
// use gorilla's mux as it allows to cancel URI cleaning
// (it is not configurable in standard http mux)
r := mux.NewRouter()
r.HandleFunc("/get", handleMethod("GET"))
r.HandleFunc("/post", handleMethod("POST"))
r.HandleFunc("/ws", wsHandler)
r.HandleFunc("/jwk.json", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, jwkTestJson)
})
r.HandleFunc("/jwk-der.json", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, jwkTestDERJson)
})
r.HandleFunc("/compressed", func(w http.ResponseWriter, r *http.Request) {
response := "This is a compressed response"
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
json.NewEncoder(gz).Encode(response)
gz.Close()
})
r.HandleFunc("/bundles/{rest:.*}", bundleHandleFunc)
r.HandleFunc("/errors/{status}", func(w http.ResponseWriter, r *http.Request) {
statusCode, _ := strconv.Atoi(mux.Vars(r)["status"])
httpError(w, statusCode)
})
r.HandleFunc("/{rest:.*}", handleMethod(""))
return r
}
const jwkTestJson = `{
"keys": [{
"alg": "RS256",
"kty": "RSA",
"use": "sig",
"x5c": ["Ci0tLS0tQkVHSU4gUFVCTElDIEtFWS0tLS0tCk1JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBTUlJQkNnS0NBUUVBeXFaNHJ3S0Y4cUNFeFM3a3BZNGMKbkphLzM3Rk1rSk5rYWxaM091c2xMQjBvUkw4VDRjOTRrZEY0YWVOelNGa1NlMm45OUlCSTZTc2w3OXZiZk1aYgordDA2TDBROTRrKy9QMzd4NysvUkpaaWZmNHkxVkdqcm5ybk1JMml1OWw0aUJCUll6Tm1HNmVibHJvRU1NV2xnCms1dHlzSGd4QjU5Q1NOSWNEOWdxazFoeDRuL0ZnT212S3NmUWdXSE5sUFNEVFJjV0dXR2hCMi9YZ05WWUcycE8KbFF4QVBxTGhCSGVxR1RYQmJQZkdGOWNIeml4cHNQcjZHdGJ6UHdoc1EvOGJQeG9KN2hkZm4rcnp6dGtzM2Q2KwpIV1VSY3lOVExSZTBtalhqamVlOVo2K2daK0grZlM0cG5QOXRxVDdJZ1U2ZVBVV1Rwam9pUHRMZXhnc0FhL2N0CmpRSURBUUFCCi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQo="],
"n": "xofiG8gsnv9-I_g-5OWTLhaZtgAGq1QEsBCPK9lmLqhuonHe8lT-nK1DM49f6J9QgaOjZ3DB50QkhBysnIFNcXFyzaYIPMoccvuHLPgdBawX4WYKm5gficD0WB0XnTt4sqTI5usFpuop9vvW44BwVGhRqMT7c11gA8TSWMBxDI4A5ARc4MuQtfm64oN-JQodSztArwb9wcmH8WrBvSUkR4pyi9MT8W27gqJ2e2Xn8jgGnswNQWOyCTN84PawOYaN-2ORHeIea1g-URln1bofcHN73vZCIrVbE6iA2D7Ybh22AVrCfunekEDEe2GZfLZLejiZiBWG7enJhcrQIzAQGw",
"e": "AQAB",
"kid": "12345",
"x5t": "12345"
}]
}`
// This has public key encoded as PKIX, ASN.1 DER form.
const jwkTestDERJson = `{
"keys": [{
"alg": "RS256",
"kty": "RSA",
"use": "sig",
"x5c": ["MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyqZ4rwKF8qCExS7kpY4cnJa/37FMkJNkalZ3OuslLB0oRL8T4c94kdF4aeNzSFkSe2n99IBI6Ssl79vbfMZb+t06L0Q94k+/P37x7+/RJZiff4y1VGjrnrnMI2iu9l4iBBRYzNmG6eblroEMMWlgk5tysHgxB59CSNIcD9gqk1hx4n/FgOmvKsfQgWHNlPSDTRcWGWGhB2/XgNVYG2pOlQxAPqLhBHeqGTXBbPfGF9cHzixpsPr6GtbzPwhsQ/8bPxoJ7hdfn+rzztks3d6+HWURcyNTLRe0mjXjjee9Z6+gZ+H+fS4pnP9tqT7IgU6ePUWTpjoiPtLexgsAa/ctjQIDAQAB"],
"n": "xofiG8gsnv9-I_g-5OWTLhaZtgAGq1QEsBCPK9lmLqhuonHe8lT-nK1DM49f6J9QgaOjZ3DB50QkhBysnIFNcXFyzaYIPMoccvuHLPgdBawX4WYKm5gficD0WB0XnTt4sqTI5usFpuop9vvW44BwVGhRqMT7c11gA8TSWMBxDI4A5ARc4MuQtfm64oN-JQodSztArwb9wcmH8WrBvSUkR4pyi9MT8W27gqJ2e2Xn8jgGnswNQWOyCTN84PawOYaN-2ORHeIea1g-URln1bofcHN73vZCIrVbE6iA2D7Ybh22AVrCfunekEDEe2GZfLZLejiZiBWG7enJhcrQIzAQGw",
"e": "AQAB",
"kid": "12345",
"x5t": "12345"
}]
}`
func withAuth(r *http.Request) *http.Request {
// This is the default config secret
r.Header.Set("x-tyk-authorization", config.Global().Secret)
return r
}
// Deprecated: Use Test.CreateSession instead.
func CreateSession(sGen ...func(s *user.SessionState)) string {
key := generateToken("default", "")
session := CreateStandardSession()
if len(sGen) > 0 {
sGen[0](session)
}
if session.Certificate != "" {
key = generateToken("default", session.Certificate)
}
FallbackKeySesionManager.UpdateSession(storage.HashKey(key), session, 60, config.Global().HashKeys)
return key
}
func CreateStandardSession() *user.SessionState {
session := new(user.SessionState)
session.Rate = 10000
session.Allowance = session.Rate
session.LastCheck = time.Now().Unix()
session.Per = 60
session.Expires = -1
session.QuotaRenewalRate = 300 // 5 minutes
session.QuotaRenews = time.Now().Unix() + 20
session.QuotaRemaining = 10
session.QuotaMax = -1
session.Tags = []string{}
session.MetaData = make(map[string]interface{})
session.OrgID = "default"
return session
}
func CreateStandardPolicy() *user.Policy {
return &user.Policy{
OrgID: "default",
Rate: 1000.0,
Per: 1.0,
QuotaMax: -1,
QuotaRenewalRate: -1,
AccessRights: map[string]user.AccessDefinition{},
Active: true,
KeyExpiresIn: 60,
}
}
func CreatePolicy(pGen ...func(p *user.Policy)) string {
pID := keyGen.GenerateAuthKey("")
pol := CreateStandardPolicy()
pol.ID = pID
if len(pGen) > 0 {
pGen[0](pol)
}
policiesMu.Lock()
policiesByID[pol.ID] = *pol
policiesMu.Unlock()
return pol.ID
}
func CreateJWKToken(jGen ...func(*jwt.Token)) string {
// Create the token
token := jwt.New(jwt.GetSigningMethod("RS512"))
// Set the token ID
if len(jGen) > 0 {
jGen[0](token)
}
// Sign and get the complete encoded token as a string
signKey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(jwtRSAPrivKey))
if err != nil {
panic("Couldn't extract private key: " + err.Error())
}
tokenString, err := token.SignedString(signKey)
if err != nil {
panic("Couldn't create JWT token: " + err.Error())
}
return tokenString
}
func CreateJWKTokenECDSA(jGen ...func(*jwt.Token)) string {
// Create the token
token := jwt.New(jwt.GetSigningMethod("ES256"))
// Set the token ID
if len(jGen) > 0 {
jGen[0](token)
}
// Sign and get the complete encoded token as a string
signKey, err := jwt.ParseECPrivateKeyFromPEM([]byte(jwtECDSAPrivateKey))
if err != nil {
panic("Couldn't extract private key: " + err.Error())
}
tokenString, err := token.SignedString(signKey)
if err != nil {
panic("Couldn't create JWT token: " + err.Error())
}
return tokenString
}
func createJWKTokenHMAC(jGen ...func(*jwt.Token)) string {
// Create the token
token := jwt.New(jwt.SigningMethodHS256)
// Set the token ID
if len(jGen) > 0 {
jGen[0](token)
}
tokenString, err := token.SignedString([]byte(jwtSecret))
if err != nil {
panic("Couldn't create JWT token: " + err.Error())
}
return tokenString
}
func TestReqBody(t testing.TB, body interface{}) io.Reader {
switch x := body.(type) {
case []byte:
return bytes.NewReader(x)
case string:
return strings.NewReader(x)
case io.Reader:
return x
case nil:
return nil
default: // JSON objects (structs)
bs, err := json.Marshal(x)
if err != nil {
t.Fatal(err)
}
return bytes.NewReader(bs)
}
}
func TestReq(t testing.TB, method, urlStr string, body interface{}) *http.Request {
return httptest.NewRequest(method, urlStr, TestReqBody(t, body))
}
func CreateDefinitionFromString(defStr string) *APISpec {
loader := APIDefinitionLoader{}
def := loader.ParseDefinition(strings.NewReader(defStr))
spec := loader.MakeSpec(def, nil)
return spec
}
func LoadSampleAPI(def string) (spec *APISpec) {
spec = CreateDefinitionFromString(def)
loadApps([]*APISpec{spec})
return
}
func firstVals(vals map[string][]string) map[string]string {
m := make(map[string]string, len(vals))
for k, vs := range vals {
m[k] = vs[0]
}
return m
}
type TestConfig struct {
sepatateControlAPI bool
Delay time.Duration
HotReload bool
overrideDefaults bool
CoprocessConfig config.CoProcessConfig
}
type Test struct {
URL string
testRunner *test.HTTPTestRunner
GlobalConfig config.Config
config TestConfig
cacnel func()
}
func (s *Test) Start() {
l, _ := net.Listen("tcp", "127.0.0.1:0")
_, port, _ := net.SplitHostPort(l.Addr().String())
l.Close()
globalConf := config.Global()
globalConf.ListenPort, _ = strconv.Atoi(port)
if s.config.sepatateControlAPI {
l, _ := net.Listen("tcp", "127.0.0.1:0")
_, port, _ = net.SplitHostPort(l.Addr().String())
l.Close()
globalConf.ControlAPIPort, _ = strconv.Atoi(port)
}
globalConf.CoProcessOptions = s.config.CoprocessConfig
config.SetGlobal(globalConf)
setupPortsWhitelist()
startServer()
ctx, cancel := context.WithCancel(context.Background())
s.cacnel = cancel
setupGlobals(ctx)
// Set up a default org manager so we can traverse non-live paths
if !config.Global().SupressDefaultOrgStore {
DefaultOrgStore.Init(getGlobalStorageHandler("orgkey.", false))
DefaultQuotaStore.Init(getGlobalStorageHandler("orgkey.", false))
}
s.GlobalConfig = globalConf
scheme := "http://"
if s.GlobalConfig.HttpServerOptions.UseSSL {
scheme = "https://"
}
s.URL = scheme + mainProxy().listener.Addr().String()
s.testRunner = &test.HTTPTestRunner{
RequestBuilder: func(tc *test.TestCase) (*http.Request, error) {
tc.BaseURL = s.URL
if tc.ControlRequest {
if s.config.sepatateControlAPI {
tc.BaseURL = scheme + controlProxy().listener.Addr().String()
} else if s.GlobalConfig.ControlAPIHostname != "" {
tc.Domain = s.GlobalConfig.ControlAPIHostname
}
}
r, err := test.NewRequest(tc)
if tc.AdminAuth {
r = withAuth(r)
}
if s.config.Delay > 0 {
tc.Delay = s.config.Delay
}
return r, err
},
Do: test.HttpServerRunner(),
}
}
func (s *Test) Do(tc test.TestCase) (*http.Response, error) {
req, _ := s.testRunner.RequestBuilder(&tc)
return s.testRunner.Do(req, &tc)
}
func (s *Test) Close() {
if s.cacnel != nil {
s.cacnel()
}
defaultProxyMux.swap(&proxyMux{})
if s.config.sepatateControlAPI {
globalConf := config.Global()
globalConf.ControlAPIPort = 0
config.SetGlobal(globalConf)
}
}
func (s *Test) Run(t testing.TB, testCases ...test.TestCase) (*http.Response, error) {
return s.testRunner.Run(t, testCases...)
}
//TODO:(gernest) when hot reload is suppored enable this.
func (s *Test) RunExt(t testing.TB, testCases ...test.TestCase) {
s.Run(t, testCases...)
var testMatrix = []struct {
goagain bool
overrideDefaults bool
}{
{false, false},
{false, true},
{true, true},
{true, false},
}
for i, m := range testMatrix {
s.config.HotReload = m.goagain
s.config.overrideDefaults = m.overrideDefaults
if i > 0 {
s.Close()
s.Start()
}
title := fmt.Sprintf("hotReload: %v, overrideDefaults: %v", m.goagain, m.overrideDefaults)
t.(*testing.T).Run(title, func(t *testing.T) {
s.Run(t, testCases...)
})
}
}
func GetTLSClient(cert *tls.Certificate, caCert []byte) *http.Client {
// Setup HTTPS client
tlsConfig := &tls.Config{}
if cert != nil {
tlsConfig.Certificates = []tls.Certificate{*cert}
}
if len(caCert) > 0 {
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig.RootCAs = caCertPool
tlsConfig.BuildNameToCertificate()
} else {
tlsConfig.InsecureSkipVerify = true
}
transport := &http.Transport{TLSClientConfig: tlsConfig}
return &http.Client{Transport: transport}
}
func (s *Test) CreateSession(sGen ...func(s *user.SessionState)) (*user.SessionState, string) {
session := CreateStandardSession()
if len(sGen) > 0 {
sGen[0](session)
}
client := GetTLSClient(nil, nil)
resp, err := s.Do(test.TestCase{
Method: http.MethodPost,
Path: "/tyk/keys/create",
Data: session,
Client: client,
AdminAuth: true,
})
if err != nil {
log.Fatal("Error while creating session:", err)
return nil, ""
}
keySuccess := apiModifyKeySuccess{}
err = json.NewDecoder(resp.Body).Decode(&keySuccess)
if err != nil {
log.Fatal("Error while decoding session response:", err)
return nil, ""
}
return session, keySuccess.Key
}
func StartTest(config ...TestConfig) *Test {
t := &Test{}
if len(config) > 0 {
t.config = config[0]
}
t.Start()
return t
}
const sampleAPI = `{
"api_id": "test",
"org_id": "default",
"use_keyless": true,
"definition": {
"location": "header",
"key": "version"
},
"auth": {
"auth_header_name": "authorization"
},
"version_data": {
"default_version": "Default",
"not_versioned": true,
"versions": {
"v1": {
"name": "v1",
"use_extended_paths": true
}
}
},
"proxy": {
"listen_path": "/sample",
"target_url": "` + TestHttpAny + `"
}
}`
func UpdateAPIVersion(spec *APISpec, name string, verGen func(version *apidef.VersionInfo)) {
version := spec.VersionData.Versions[name]
verGen(&version)
spec.VersionData.Versions[name] = version
}
func jsonMarshalString(i interface{}) (out string) {
b, _ := json.Marshal(i)
return string(b)
}
func BuildAPI(apiGens ...func(spec *APISpec)) (specs []*APISpec) {
if len(apiGens) == 0 {
apiGens = append(apiGens, func(spec *APISpec) {})
}
for _, gen := range apiGens {
spec := &APISpec{APIDefinition: &apidef.APIDefinition{}}
if err := json.Unmarshal([]byte(sampleAPI), spec.APIDefinition); err != nil {
panic(err)
}
gen(spec)
specs = append(specs, spec)
}
return specs
}
func LoadAPI(specs ...*APISpec) (out []*APISpec) {
globalConf := config.Global()
oldPath := globalConf.AppPath
globalConf.AppPath, _ = ioutil.TempDir("", "apps")
config.SetGlobal(globalConf)
defer func() {
globalConf := config.Global()
os.RemoveAll(globalConf.AppPath)
globalConf.AppPath = oldPath
config.SetGlobal(globalConf)
}()
for i, spec := range specs {
specBytes, err := json.Marshal(spec)
if err != nil {
panic(err)
}
specFilePath := filepath.Join(config.Global().AppPath, spec.APIID+strconv.Itoa(i)+".json")
if err := ioutil.WriteFile(specFilePath, specBytes, 0644); err != nil {
panic(err)
}
}
DoReload()
for _, spec := range specs {
out = append(out, getApiSpec(spec.APIID))
}
return out
}
func BuildAndLoadAPI(apiGens ...func(spec *APISpec)) (specs []*APISpec) {
return LoadAPI(BuildAPI(apiGens...)...)
}
func CloneAPI(a *APISpec) *APISpec {
new := &APISpec{}
new.APIDefinition = &apidef.APIDefinition{}
*new.APIDefinition = *a.APIDefinition
return new
}
// Taken from https://medium.com/@mlowicki/http-s-proxy-in-golang-in-less-than-100-lines-of-code-6a51c2f2c38c
type httpProxyHandler struct {
proto string
URL string
server *http.Server
listener net.Listener
}
func (p *httpProxyHandler) handleTunneling(w http.ResponseWriter, r *http.Request) {
dest_conn, err := net.DialTimeout("tcp", r.Host, 10*time.Second)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
hijacker, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
return
}
client_conn, _, err := hijacker.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
go p.transfer(dest_conn, client_conn)
go p.transfer(client_conn, dest_conn)
}
func (p *httpProxyHandler) transfer(destination io.WriteCloser, source io.ReadCloser) {
defer destination.Close()
defer source.Close()
io.Copy(destination, source)
}
func (p *httpProxyHandler) handleHTTP(w http.ResponseWriter, req *http.Request) {
resp, err := http.DefaultTransport.RoundTrip(req)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
defer resp.Body.Close()
p.copyHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}
func (p *httpProxyHandler) Stop() error {
ResetTestConfig()
return p.server.Close()
}
func (p *httpProxyHandler) copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func initProxy(proto string, tlsConfig *tls.Config) *httpProxyHandler {
proxy := &httpProxyHandler{proto: proto}
proxy.server = &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodConnect {
proxy.handleTunneling(w, r)
} else {
proxy.handleHTTP(w, r)
}
}),
// Disable HTTP/2.
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
}
var err error
switch proto {
case "http":
proxy.listener, err = net.Listen("tcp", ":0")
case "https":
proxy.listener, err = tls.Listen("tcp", ":0", tlsConfig)
default:
log.Fatal("Unsupported proto scheme", proto)
}
if err != nil {
log.Fatal(err)
}
proxy.URL = proto + "://" + proxy.listener.Addr().String()
go proxy.server.Serve(proxy.listener)
return proxy
}
func GenerateTestBinaryData() (buf *bytes.Buffer) {
buf = new(bytes.Buffer)
type testData struct {
a float32
b float64
c uint32
}
for i := 0; i < 10; i++ {
s := &testData{rand.Float32(), rand.Float64(), rand.Uint32()}
binary.Write(buf, binary.BigEndian, s)
}
return buf
}
// openssl genrsa -out app.rsa
const jwtRSAPrivKey = `
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAyqZ4rwKF8qCExS7kpY4cnJa/37FMkJNkalZ3OuslLB0oRL8T
4c94kdF4aeNzSFkSe2n99IBI6Ssl79vbfMZb+t06L0Q94k+/P37x7+/RJZiff4y1