forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1347 lines (1137 loc) · 41.3 KB
/
main.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 main
import (
"crypto/tls"
"fmt"
"github.com/Sirupsen/logrus"
logger "github.com/TykTechnologies/tykcommon-logger"
"github.com/docopt/docopt.go"
"github.com/evalphobia/logrus_sentry"
"github.com/gorilla/mux"
"github.com/justinas/alice"
osin "github.com/lonelycode/osin"
"github.com/lonelycode/tykcommon"
"github.com/rcrowley/goagain"
"github.com/rs/cors"
"html/template"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"runtime/pprof"
"strconv"
"strings"
"time"
)
var log = logger.GetLogger()
var config = Config{}
var templates = &template.Template{}
var analytics = RedisAnalyticsHandler{}
var profileFile = &os.File{}
var GlobalEventsJSVM = &JSVM{}
var doMemoryProfile bool
var doCpuProfile bool
var Policies = make(map[string]Policy)
var MainNotifier = RedisNotifier{}
var DefaultOrgStore = DefaultSessionManager{}
var DefaultQuotaStore = DefaultSessionManager{}
var FallbackKeySesionManager SessionHandler = &DefaultSessionManager{}
var MonitoringHandler TykEventHandler
var RPCListener = RPCStorageHandler{}
var ApiSpecRegister *map[string]*APISpec //make(map[string]*APISpec)
var keyGen = DefaultKeyGenerator{}
var mainRouter *mux.Router
var defaultRouter *mux.Router
var NodeID string
// Generic system error
const (
E_SYSTEM_ERROR string = "{\"status\": \"system error, please contact administrator\"}"
OAUTH_AUTH_CODE_TIMEOUT int = 60 * 60
OAUTH_PREFIX string = "oauth-data."
)
// Display configuration options
func displayConfig() {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("--> Listening on port: ", config.ListenPort)
}
func getHostName() string {
hName := config.HostName
if config.HostName == "" {
hName = ""
}
return hName
}
func pingTest(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello Tiki")
}
// Create all globals and init connection handlers
func setupGlobals() {
mainRouter = mux.NewRouter()
if getHostName() != "" {
defaultRouter = mainRouter.Host(getHostName()).Subrouter()
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Hostname set: ", getHostName())
} else {
defaultRouter = mainRouter
}
if (config.EnableAnalytics == true) && (config.Storage.Type != "redis") {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Panic("Analytics requires Redis Storage backend, please enable Redis in the tyk.conf file.")
}
// Initialise our Host Checker
HealthCheckStore := &RedisClusterStorageManager{KeyPrefix: "host-checker:"}
InitHostCheckManager(HealthCheckStore)
if config.EnableAnalytics {
config.loadIgnoredIPs()
AnalyticsStore := RedisClusterStorageManager{KeyPrefix: "analytics-"}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Setting up analytics DB connection")
analytics = RedisAnalyticsHandler{
Store: &AnalyticsStore,
}
analytics.Init()
if config.AnalyticsConfig.Type == "rpc" {
log.Debug("Using RPC cache purge")
thisPurger := RPCPurger{Store: &AnalyticsStore, Address: config.SlaveOptions.ConnectionString}
thisPurger.Connect()
analytics.Clean = &thisPurger
go analytics.Clean.StartPurgeLoop(10)
} else {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warn("Cache purging is no longer part of Tyk Gateway, please use Tyk-Pump.")
}
}
//genericOsinStorage = MakeNewOsinServer()
templateFile := fmt.Sprintf("%s/error.json", config.TemplatePath)
templates = template.Must(template.ParseFiles(templateFile))
// Set up global JSVM
if config.EnableJSVM {
GlobalEventsJSVM.Init(config.TykJSPath)
}
// Get the notifier ready
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Notifier will not work in hybrid mode")
MainNotifierStore := RedisClusterStorageManager{}
MainNotifierStore.Connect()
MainNotifier = RedisNotifier{&MainNotifierStore, RedisPubSubChannel}
if config.Monitor.EnableTriggerMonitors {
var monitorErr error
MonitoringHandler, monitorErr = WebHookHandler{}.New(config.Monitor.Config)
if monitorErr != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Failed to initialise monitor! ", monitorErr)
}
}
}
// Pull API Specs from configuration
var APILoader APIDefinitionLoader = APIDefinitionLoader{}
func getAPISpecs() *[]*APISpec {
var APISpecs *[]*APISpec
if config.UseDBAppConfigs {
if config.DBAppConfOptions.ConnectionString != "" {
connStr := config.DBAppConfOptions.ConnectionString
connStr = connStr + "/system/apis"
APISpecs = APILoader.LoadDefinitionsFromDashboardService(connStr, config.NodeSecret)
} else {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Fatal("No connection string or node ID present. Failing.")
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Using App Configuration from Dashboard Service")
} else if config.SlaveOptions.UseRPC {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Using RPC Configuration")
APISpecs = APILoader.LoadDefinitionsFromRPC(config.SlaveOptions.RPCKey)
} else {
APISpecs = APILoader.LoadDefinitions(config.AppPath)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Printf("Detected %v APIs", len(*APISpecs))
if config.AuthOverride.ForceAuthProvider {
for i, _ := range *APISpecs {
(*APISpecs)[i].AuthProvider = config.AuthOverride.AuthProvider
}
}
if config.AuthOverride.ForceSessionProvider {
for i, _ := range *APISpecs {
(*APISpecs)[i].SessionProvider = config.AuthOverride.SessionProvider
}
}
return APISpecs
}
func getPolicies() {
thesePolicies := make(map[string]Policy)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading policies")
if config.Policies.PolicyRecordName == "" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("No policy record name defined, skipping...")
return
}
if config.Policies.PolicySource == "service" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Using Policies from Dashboard Service")
if config.Policies.PolicyConnectionString != "" {
connStr := config.Policies.PolicyConnectionString
connStr = connStr + "/system/policies"
thesePolicies = LoadPoliciesFromDashboard(connStr, config.NodeSecret, config.Policies.AllowExplicitPolicyID)
} else {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Fatal("No connection string or node ID present. Failing.")
}
} else if config.Policies.PolicySource == "rpc" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Using Policies from RPC")
thesePolicies = LoadPoliciesFromRPC(config.SlaveOptions.RPCKey)
} else {
thesePolicies = LoadPoliciesFromFile(config.Policies.PolicyRecordName)
}
if len(thesePolicies) > 0 {
Policies = thesePolicies
return
}
}
// Set up default Tyk control API endpoints - these are global, so need to be added first
func loadAPIEndpoints(Muxer *mux.Router) {
var ApiMuxer *mux.Router
ApiMuxer = Muxer
if config.EnableAPISegregation {
if config.ControlAPIHostname != "" {
ApiMuxer = Muxer.Host(config.ControlAPIHostname).Subrouter()
}
}
// Add a root message to check all is OK
ApiMuxer.HandleFunc("/hello", pingTest)
// set up main API handlers
ApiMuxer.HandleFunc("/tyk/reload/group", CheckIsAPIOwner(groupResetHandler))
ApiMuxer.HandleFunc("/tyk/reload/", CheckIsAPIOwner(resetHandler))
if !IsRPCMode() {
ApiMuxer.HandleFunc("/tyk/org/keys/"+"{rest:.*}", CheckIsAPIOwner(orgHandler))
ApiMuxer.HandleFunc("/tyk/keys/policy/"+"{rest:.*}", CheckIsAPIOwner(policyUpdateHandler))
ApiMuxer.HandleFunc("/tyk/keys/create", CheckIsAPIOwner(createKeyHandler))
ApiMuxer.HandleFunc("/tyk/apis/"+"{rest:.*}", CheckIsAPIOwner(apiHandler))
ApiMuxer.HandleFunc("/tyk/health/", CheckIsAPIOwner(healthCheckhandler))
ApiMuxer.HandleFunc("/tyk/oauth/clients/create", CheckIsAPIOwner(createOauthClient))
ApiMuxer.HandleFunc("/tyk/oauth/refresh/"+"{rest:.*}", CheckIsAPIOwner(invalidateOauthRefresh))
} else {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Node is slaved, REST API minimised")
}
ApiMuxer.HandleFunc("/tyk/keys/"+"{rest:.*}", CheckIsAPIOwner(keyHandler))
ApiMuxer.HandleFunc("/tyk/oauth/clients/"+"{rest:.*}", CheckIsAPIOwner(oAuthClientHandler))
}
func generateOAuthPrefix(apiID string) string {
return OAUTH_PREFIX + apiID + "."
}
// Create API-specific OAuth handlers and respective auth servers
func addOAuthHandlers(spec *APISpec, Muxer *mux.Router, test bool) *OAuthManager {
apiAuthorizePath := spec.Proxy.ListenPath + "tyk/oauth/authorize-client/"
clientAuthPath := spec.Proxy.ListenPath + "oauth/authorize/"
clientAccessPath := spec.Proxy.ListenPath + "oauth/token/"
serverConfig := osin.NewServerConfig()
serverConfig.ErrorStatusCode = 403
serverConfig.AllowedAccessTypes = spec.Oauth2Meta.AllowedAccessTypes
serverConfig.AllowedAuthorizeTypes = spec.Oauth2Meta.AllowedAuthorizeTypes
OAuthPrefix := generateOAuthPrefix(spec.APIID)
//storageManager := RedisClusterStorageManager{KeyPrefix: OAuthPrefix}
storageManager := GetGlobalStorageHandler(OAuthPrefix, false)
storageManager.Connect()
osinStorage := RedisOsinStorageInterface{storageManager, spec.SessionManager} //TODO: Needs storage manager from APISpec
if test {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("Adding test clients")
testPolicy := Policy{}
testPolicy.Rate = 100
testPolicy.Per = 1
testPolicy.QuotaMax = -1
testPolicy.QuotaRenewalRate = 1000000000
Policies["TEST-4321"] = testPolicy
testClient := OAuthClient{
ClientID: "1234",
ClientSecret: "aabbccdd",
ClientRedirectURI: "http://client.oauth.com",
PolicyID: "TEST-4321",
}
osinStorage.SetClient(testClient.ClientID, &testClient, false)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("Test client added")
}
osinServer := TykOsinNewServer(serverConfig, osinStorage)
// osinServer.AccessTokenGen = &AccessTokenGenTyk{}
oauthManager := OAuthManager{spec, osinServer}
oauthHandlers := OAuthHandlers{oauthManager}
Muxer.HandleFunc(apiAuthorizePath, CheckIsAPIOwner(oauthHandlers.HandleGenerateAuthCodeData))
Muxer.HandleFunc(clientAuthPath, oauthHandlers.HandleAuthorizePassthrough)
Muxer.HandleFunc(clientAccessPath, oauthHandlers.HandleAccessRequest)
return &oauthManager
}
func addBatchEndpoint(spec *APISpec, Muxer *mux.Router) {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Batch requests enabled for API")
apiBatchPath := spec.Proxy.ListenPath + "tyk/batch/"
thisBatchHandler := BatchRequestHandler{API: spec}
Muxer.HandleFunc(apiBatchPath, thisBatchHandler.HandleBatchRequest)
}
func loadCustomMiddleware(referenceSpec *APISpec) ([]string, []tykcommon.MiddlewareDefinition, []tykcommon.MiddlewareDefinition) {
mwPaths := []string{}
mwPreFuncs := []tykcommon.MiddlewareDefinition{}
mwPostFuncs := []tykcommon.MiddlewareDefinition{}
// Load form the configuration
for _, mwObj := range referenceSpec.APIDefinition.CustomMiddleware.Pre {
mwPaths = append(mwPaths, mwObj.Path)
mwPreFuncs = append(mwPreFuncs, mwObj)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading custom PRE-PROCESSOR middleware: ", mwObj.Name)
}
for _, mwObj := range referenceSpec.APIDefinition.CustomMiddleware.Post {
mwPaths = append(mwPaths, mwObj.Path)
mwPostFuncs = append(mwPostFuncs, mwObj)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading custom POST-PROCESSOR middleware: ", mwObj.Name)
}
// Load from folder
// Get PRE folder path
middlwareFolderPath := path.Join(config.MiddlewarePath, referenceSpec.APIDefinition.APIID, "pre")
files, _ := ioutil.ReadDir(middlwareFolderPath)
for _, f := range files {
if strings.Contains(f.Name(), ".js") {
filePath := filepath.Join(middlwareFolderPath, f.Name())
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading PRE-PROCESSOR file middleware from ", filePath)
middlewareObjectName := strings.Split(f.Name(), ".")[0]
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware name ", middlewareObjectName)
requiresSession := strings.Contains(middlewareObjectName, "_with_session")
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware requires session: ", requiresSession)
thisMWDef := tykcommon.MiddlewareDefinition{}
thisMWDef.Name = middlewareObjectName
thisMWDef.Path = filePath
thisMWDef.RequireSession = requiresSession
mwPaths = append(mwPaths, filePath)
mwPreFuncs = append(mwPreFuncs, thisMWDef)
}
}
// Get POST folder path
middlewarePostFolderPath := path.Join(config.MiddlewarePath, referenceSpec.APIDefinition.APIID, "post")
mwPostFiles, _ := ioutil.ReadDir(middlewarePostFolderPath)
for _, f := range mwPostFiles {
if strings.Contains(f.Name(), ".js") {
filePath := filepath.Join(middlewarePostFolderPath, f.Name())
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading POST-PROCESSOR file middleware from ", filePath)
middlewareObjectName := strings.Split(f.Name(), ".")[0]
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware name ", middlewareObjectName)
requiresSession := strings.Contains(middlewareObjectName, "_with_session")
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("-- Middleware requires session: ", requiresSession)
thisMWDef := tykcommon.MiddlewareDefinition{}
thisMWDef.Name = middlewareObjectName
thisMWDef.Path = filePath
thisMWDef.RequireSession = requiresSession
mwPaths = append(mwPaths, filePath)
mwPostFuncs = append(mwPostFuncs, thisMWDef)
}
}
return mwPaths, mwPreFuncs, mwPostFuncs
}
func creeateResponseMiddlewareChain(referenceSpec *APISpec) {
// Create the response processors
responseChain := make([]TykResponseHandler, len(referenceSpec.APIDefinition.ResponseProcessors))
for i, processorDetail := range referenceSpec.APIDefinition.ResponseProcessors {
processorType, err := GetResponseProcessorByName(processorDetail.Name)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Failed to load processor! ", err)
return
}
thisProcessor, _ := processorType.New(processorDetail.Options, referenceSpec)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading Response processor: ", processorDetail.Name)
responseChain[i] = thisProcessor
}
referenceSpec.ResponseChain = &responseChain
}
func handleCORS(chain *[]alice.Constructor, spec *APISpec) {
if spec.CORS.Enable {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("CORS ENABLED")
c := cors.New(cors.Options{
AllowedOrigins: spec.CORS.AllowedOrigins,
AllowedMethods: spec.CORS.AllowedMethods,
AllowedHeaders: spec.CORS.AllowedHeaders,
ExposedHeaders: spec.CORS.ExposedHeaders,
AllowCredentials: spec.CORS.AllowCredentials,
MaxAge: spec.CORS.MaxAge,
OptionsPassthrough: spec.CORS.OptionsPassthrough,
Debug: spec.CORS.Debug,
})
*chain = append(*chain, c.Handler)
}
}
func IsRPCMode() bool {
if config.AuthOverride.ForceAuthProvider {
if config.AuthOverride.AuthProvider.StorageEngine == RPCStorageEngine {
return true
}
}
return false
}
func doCopy(from *APISpec, to *APISpec) {
*to = *from
}
// Create the individual API (app) specs based on live configurations and assign middleware
func loadApps(APISpecs *[]*APISpec, Muxer *mux.Router) {
// load the APi defs
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("Loading API configurations.")
var tempSpecRegister = make(map[string]*APISpec)
// Only create this once, add other types here as needed, seems wasteful but we can let the GC handle it
redisStore := RedisClusterStorageManager{KeyPrefix: "apikey-", HashKeys: config.HashKeys}
redisOrgStore := RedisClusterStorageManager{KeyPrefix: "orgkey."}
healthStore := &RedisClusterStorageManager{KeyPrefix: "apihealth."}
rpcAuthStore := RPCStorageHandler{KeyPrefix: "apikey-", HashKeys: config.HashKeys, UserKey: config.SlaveOptions.APIKey, Address: config.SlaveOptions.ConnectionString}
rpcOrgStore := RPCStorageHandler{KeyPrefix: "orgkey.", UserKey: config.SlaveOptions.APIKey, Address: config.SlaveOptions.ConnectionString}
if config.SlaveOptions.UseRPC {
StartRPCKeepaliveWatcher(&rpcAuthStore)
StartRPCKeepaliveWatcher(&rpcOrgStore)
}
listenPaths := make(map[string][]string)
FallbackKeySesionManager.Init(&redisStore)
// Create a new handler for each API spec
for _, referenceSpec := range *APISpecs {
var skip bool
// We need a reference to this as we change it on the go and re-use it in a global index
//referenceSpec := (*APISpecs)[apiIndex]
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("--> Loading API: ", referenceSpec.APIDefinition.Name)
// Handle custom domains
var subrouter *mux.Router
if config.EnableCustomDomains {
if referenceSpec.Domain != "" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Custom Domain: ", referenceSpec.Domain)
subrouter = mainRouter.Host(referenceSpec.Domain).Subrouter()
} else {
subrouter = Muxer
}
} else {
subrouter = Muxer
}
onDomains, listenPathExists := listenPaths[referenceSpec.Proxy.ListenPath]
if listenPathExists {
if config.EnableCustomDomains == false {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Duplicate listen path found, skipping. API ID: ", referenceSpec.APIID)
skip = true
} else {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Domain check...")
for _, onDomain := range onDomains {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Checking Domain: ", onDomain)
if onDomain == referenceSpec.Domain {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Duplicate listen path found on domain, skipping. API ID: ", referenceSpec.APIID)
skip = true
break
}
}
}
}
if referenceSpec.Proxy.ListenPath == "" {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Listen path is empty, skipping API ID: ", referenceSpec.APIID)
skip = true
}
if strings.Contains(referenceSpec.Proxy.ListenPath, " ") {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Listen path contains spaces, is invalid, skipping API ID: ", referenceSpec.APIID)
skip = true
}
remote, err := url.Parse(referenceSpec.APIDefinition.Proxy.TargetURL)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Error("Culdn't parse target URL: ", err)
}
if !skip {
listenPaths[referenceSpec.Proxy.ListenPath] = append(listenPaths[referenceSpec.Proxy.ListenPath], referenceSpec.Domain)
dN := referenceSpec.Domain
if dN == "" {
dN = "(no host)"
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Tracking: ", dN)
// Initialise the auth and session managers (use Redis for now)
var authStore StorageHandler
var sessionStore StorageHandler
var orgStore StorageHandler
authStorageEngineToUse := referenceSpec.AuthProvider.StorageEngine
// if config.SlaveOptions.OverrideDefinitionStorageSettings {
// authStorageEngineToUse = RPCStorageEngine
// }
switch authStorageEngineToUse {
case DefaultStorageEngine:
authStore = &redisStore
orgStore = &redisOrgStore
case LDAPStorageEngine:
thisStorageEngine := LDAPStorageHandler{}
thisStorageEngine.LoadConfFromMeta(referenceSpec.AuthProvider.Meta)
authStore = &thisStorageEngine
orgStore = &redisOrgStore
case RPCStorageEngine:
thisStorageEngine := &rpcAuthStore // &RPCStorageHandler{KeyPrefix: "apikey-", HashKeys: config.HashKeys, UserKey: config.SlaveOptions.APIKey, Address: config.SlaveOptions.ConnectionString}
authStore = thisStorageEngine
orgStore = &rpcOrgStore // &RPCStorageHandler{KeyPrefix: "orgkey.", UserKey: config.SlaveOptions.APIKey, Address: config.SlaveOptions.ConnectionString}
config.EnforceOrgDataAge = true
config.EnforceOrgQuotas = true
default:
authStore = &redisStore
orgStore = &redisOrgStore
}
SessionStorageEngineToUse := referenceSpec.SessionProvider.StorageEngine
// if config.SlaveOptions.OverrideDefinitionStorageSettings {
// SessionStorageEngineToUse = RPCStorageEngine
// }
switch SessionStorageEngineToUse {
case DefaultStorageEngine:
sessionStore = &redisStore
case RPCStorageEngine:
sessionStore = &RPCStorageHandler{KeyPrefix: "apikey-", HashKeys: config.HashKeys, UserKey: config.SlaveOptions.APIKey, Address: config.SlaveOptions.ConnectionString}
default:
sessionStore = &redisStore
}
// Health checkers are initialised per spec so that each API handler has it's own connection and redis sotorage pool
referenceSpec.Init(authStore, sessionStore, healthStore, orgStore)
//Set up all the JSVM middleware
mwPaths := []string{}
mwPreFuncs := []tykcommon.MiddlewareDefinition{}
mwPostFuncs := []tykcommon.MiddlewareDefinition{}
if config.EnableJSVM {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("----> Loading Middleware")
mwPaths, mwPreFuncs, mwPostFuncs = loadCustomMiddleware(referenceSpec)
referenceSpec.JSVM.LoadJSPaths(mwPaths)
}
if referenceSpec.EnableBatchRequestSupport {
addBatchEndpoint(referenceSpec, subrouter)
}
if referenceSpec.UseOauth2 {
thisOauthManager := addOAuthHandlers(referenceSpec, subrouter, false)
referenceSpec.OAuthManager = thisOauthManager
}
enableVersionOverrides := false
for _, versionData := range referenceSpec.VersionData.Versions {
if versionData.OverrideTarget != "" {
enableVersionOverrides = true
break
}
}
referenceSpec.target = remote
var proxy ReturningHttpHandler
if enableVersionOverrides {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Multi target enabled")
proxy = &MultiTargetProxy{}
} else {
proxy = TykNewSingleHostReverseProxy(remote, referenceSpec)
}
// initialise the proxy
proxy.New(nil, referenceSpec)
// Create the response processors
creeateResponseMiddlewareChain(referenceSpec)
//proxyHandler := http.HandlerFunc(ProxyHandler(proxy, referenceSpec))
tykMiddleware := &TykMiddleware{referenceSpec, proxy}
keyPrefix := "cache-" + referenceSpec.APIDefinition.APIID
CacheStore := &RedisClusterStorageManager{KeyPrefix: keyPrefix}
CacheStore.Connect()
if referenceSpec.APIDefinition.UseKeylessAccess {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Checking security policy: Open")
// Add pre-process MW
var chainArray = []alice.Constructor{}
handleCORS(&chainArray, referenceSpec)
var baseChainArray = []alice.Constructor{
CreateMiddleware(&IPWhiteListMiddleware{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&OrganizationMonitor{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&VersionCheck{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&RequestSizeLimitMiddleware{tykMiddleware}, tykMiddleware),
CreateMiddleware(&TransformMiddleware{tykMiddleware}, tykMiddleware),
CreateMiddleware(&TransformHeaders{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&RedisCacheMiddleware{TykMiddleware: tykMiddleware, CacheStore: CacheStore}, tykMiddleware),
CreateMiddleware(&VirtualEndpoint{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&URLRewriteMiddleware{TykMiddleware: tykMiddleware}, tykMiddleware),
}
for _, obj := range mwPreFuncs {
chainArray = append(chainArray, CreateDynamicMiddleware(obj.Name, true, obj.RequireSession, tykMiddleware))
}
for _, baseMw := range baseChainArray {
chainArray = append(chainArray, baseMw)
}
for _, obj := range mwPostFuncs {
chainArray = append(chainArray, CreateDynamicMiddleware(obj.Name, false, obj.RequireSession, tykMiddleware))
}
// for KeyLessAccess we can't support rate limiting, versioning or access rules
chain := alice.New(chainArray...).Then(DummyProxyHandler{SH: SuccessHandler{tykMiddleware}})
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("----> Setting Listen Path: ", referenceSpec.Proxy.ListenPath)
subrouter.Handle(referenceSpec.Proxy.ListenPath+"{rest:.*}", chain)
} else {
// Select the keying method to use for setting session states
var keyCheck func(http.Handler) http.Handler
if referenceSpec.APIDefinition.UseOauth2 {
// Oauth2
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Checking security policy: OAuth")
keyCheck = CreateMiddleware(&Oauth2KeyExists{tykMiddleware}, tykMiddleware)
} else if referenceSpec.APIDefinition.UseBasicAuth {
// Basic Auth
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Checking security policy: Basic")
keyCheck = CreateMiddleware(&BasicAuthKeyIsValid{tykMiddleware}, tykMiddleware)
} else if referenceSpec.EnableSignatureChecking {
// HMAC Auth
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Checking security policy: HMAC")
keyCheck = CreateMiddleware(&HMACMiddleware{tykMiddleware}, tykMiddleware)
} else if referenceSpec.EnableJWT {
// JWT Auth
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Checking security policy: JWT")
keyCheck = CreateMiddleware(&JWTMiddleware{tykMiddleware}, tykMiddleware)
} else if referenceSpec.UseOpenID {
// JWT Auth
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Checking security policy: OpenID")
// initialise the OID configuration on this reference Spec
keyCheck = CreateMiddleware(&OpenIDMW{TykMiddleware: tykMiddleware}, tykMiddleware)
} else {
// Auth key
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Checking security policy: Token")
keyCheck = CreateMiddleware(&AuthKey{tykMiddleware}, tykMiddleware)
}
var chainArray = []alice.Constructor{}
handleCORS(&chainArray, referenceSpec)
var baseChainArray = []alice.Constructor{
CreateMiddleware(&IPWhiteListMiddleware{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&OrganizationMonitor{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&VersionCheck{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&RequestSizeLimitMiddleware{tykMiddleware}, tykMiddleware),
keyCheck,
CreateMiddleware(&KeyExpired{tykMiddleware}, tykMiddleware),
CreateMiddleware(&AccessRightsCheck{tykMiddleware}, tykMiddleware),
CreateMiddleware(&RateLimitAndQuotaCheck{tykMiddleware}, tykMiddleware),
CreateMiddleware(&GranularAccessMiddleware{tykMiddleware}, tykMiddleware),
CreateMiddleware(&TransformMiddleware{tykMiddleware}, tykMiddleware),
CreateMiddleware(&TransformHeaders{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&URLRewriteMiddleware{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&RedisCacheMiddleware{TykMiddleware: tykMiddleware, CacheStore: CacheStore}, tykMiddleware),
CreateMiddleware(&VirtualEndpoint{TykMiddleware: tykMiddleware}, tykMiddleware),
}
// Add pre-process MW
for _, obj := range mwPreFuncs {
chainArray = append(chainArray, CreateDynamicMiddleware(obj.Name, true, obj.RequireSession, tykMiddleware))
}
for _, baseMw := range baseChainArray {
chainArray = append(chainArray, baseMw)
}
for _, obj := range mwPostFuncs {
chainArray = append(chainArray, CreateDynamicMiddleware(obj.Name, false, obj.RequireSession, tykMiddleware))
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("----> Custom middleware processed")
// Use CreateMiddleware(&ModifiedMiddleware{tykMiddleware}, tykMiddleware) to run custom middleware
chain := alice.New(chainArray...).Then(DummyProxyHandler{SH: SuccessHandler{tykMiddleware}})
userCheckHandler := http.HandlerFunc(UserRatesCheck())
simpleChain := alice.New(
CreateMiddleware(&IPWhiteListMiddleware{tykMiddleware}, tykMiddleware),
CreateMiddleware(&OrganizationMonitor{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&VersionCheck{TykMiddleware: tykMiddleware}, tykMiddleware),
keyCheck,
CreateMiddleware(&KeyExpired{tykMiddleware}, tykMiddleware),
CreateMiddleware(&AccessRightsCheck{tykMiddleware}, tykMiddleware)).Then(userCheckHandler)
rateLimitPath := fmt.Sprintf("%s%s", referenceSpec.Proxy.ListenPath, "tyk/rate-limits/")
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("----> Rate limits available at: ", rateLimitPath)
subrouter.Handle(rateLimitPath, simpleChain)
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("----> Setting Listen Path: ", referenceSpec.Proxy.ListenPath)
subrouter.Handle(referenceSpec.Proxy.ListenPath+"{rest:.*}", chain)
}
tempSpecRegister[referenceSpec.APIDefinition.APIID] = referenceSpec
} else {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("----> Skipped!")
}
}
// Swap in the new register
ApiSpecRegister = &tempSpecRegister
// Kick off our host checkers
if config.UptimeTests.Disable == false {
SetCheckerHostList()
}
}
func RPCReloadLoop(RPCKey string) {
for {
RPCListener.CheckForReload(config.SlaveOptions.RPCKey)
}
}
func doReload() {
time.Sleep(10 * time.Second)
// Load the API Policies
getPolicies()
// load the specs
specs := getAPISpecs()
if len(*specs) == 0 {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("No API Definitions found, not reloading")
reloadScheduled = false
return
}
// We have updated specs, lets load those...
// Kill RPC if available
if config.SlaveOptions.UseRPC {
ClearRPCClients()
}
// Reset the JSVM
GlobalEventsJSVM.Init(config.TykJSPath)
newRouter := mux.NewRouter()
mainRouter = newRouter
var newMuxes *mux.Router
if getHostName() != "" {
newMuxes = newRouter.Host(getHostName()).Subrouter()
} else {
newMuxes = newRouter
}
loadAPIEndpoints(newMuxes)
loadApps(specs, newMuxes)
newServeMux := http.NewServeMux()
newServeMux.Handle("/", mainRouter)
http.DefaultServeMux = newServeMux
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("API reload complete")
reloadScheduled = false
}
var reloadScheduled bool
func checkReloadTimeout() {
if reloadScheduled {
time.Sleep(30 * time.Second)
if reloadScheduled {
log.Warning("Reloader timed out! Removing sentinel")
reloadScheduled = false
}
}
}
// ReloadURLStructure will create a new muxer, reload all the app configs for an
// instance and then replace the DefaultServeMux with the new one, this enables a
// reconfiguration to take place without stopping any requests from being handled.
func ReloadURLStructure() {
if !reloadScheduled {
reloadScheduled = true
log.Info("Initiating reload")
go doReload()
go checkReloadTimeout()
}
}
func init() {
usage := `Tyk API Gateway.
Usage:
tyk [options]
Options:
-h --help Show this screen
--conf=FILE Load a named configuration file
--port=PORT Listen on PORT (overrides confg file)
--memprofile Generate a memory profile
--cpuprofile Generate a cpu profile
--debug Enable Debug output
--import-blueprint=<file> Import an API Blueprint file
--import-swagger=<file> Import a Swagger file
--create-api Creates a new API Definition from the blueprint
--org-id=><id> Assign the API Defintition to this org_id (required with create)
--upstream-target=<url> Set the upstream target for the definition
--as-mock Creates the API as a mock based on example fields
--for-api=<path> Adds blueprint to existing API Defintition as version
--as-version=<version> The version number to use when inserting
`
arguments, err := docopt.Parse(usage, nil, true, VERSION, false, false)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("Error while parsing arguments: ", err)
}
// Enable command mode
for k, _ := range CommandModeOptions {
v := arguments[k]
if v == true {
HandleCommandModeArgs(arguments)
os.Exit(0)
}
if v != nil && v != false {
HandleCommandModeArgs(arguments)
os.Exit(0)