forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_loader.go
677 lines (560 loc) · 24.3 KB
/
api_loader.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
package main
import (
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"sync"
"time"
"github.com/TykTechnologies/logrus"
"github.com/TykTechnologies/tyk/coprocess"
"github.com/TykTechnologies/tykcommon"
"github.com/gorilla/mux"
"github.com/justinas/alice"
"github.com/streamrail/concurrent-map"
)
type ChainObject struct {
ListenOn string
ThisHandler http.Handler
RateLimitChain http.Handler
RateLimitPath string
Open bool
Index int
Skip bool
Subrouter *mux.Router
}
var ListenPathMap cmap.ConcurrentMap
func prepareStorage() (*RedisClusterStorageManager, *RedisClusterStorageManager, *RedisClusterStorageManager, *RPCStorageHandler, *RPCStorageHandler) {
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}
FallbackKeySesionManager.Init(&redisStore)
return &redisStore, &redisOrgStore, healthStore, &rpcAuthStore, &rpcOrgStore
}
func prepareSortOrder(APISpecs *[]*APISpec) {
sort.Sort(SortableAPISpecListByHost(*APISpecs))
sort.Sort(SortableAPISpecListByListen(*APISpecs))
}
func skipSpecBecauseInvalid(referenceSpec *APISpec) bool {
if referenceSpec.Proxy.ListenPath == "" {
log.WithFields(logrus.Fields{
"prefix": "main",
"org_id": referenceSpec.APIDefinition.OrgID,
"api_id": referenceSpec.APIDefinition.APIID,
}).Error("Listen path is empty, skipping API ID: ", referenceSpec.APIID)
return true
}
if strings.Contains(referenceSpec.Proxy.ListenPath, " ") {
log.WithFields(logrus.Fields{
"prefix": "main",
"org_id": referenceSpec.APIDefinition.OrgID,
"api_id": referenceSpec.APIDefinition.APIID,
}).Error("Listen path contains spaces, is invalid, skipping API ID: ", referenceSpec.APIID)
return true
}
_, err := url.Parse(referenceSpec.APIDefinition.Proxy.TargetURL)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
"org_id": referenceSpec.APIDefinition.OrgID,
"api_id": referenceSpec.APIDefinition.APIID,
}).Error("Couldn't parse target URL: ", err)
return true
}
domainHash := generateDomainPath(referenceSpec.Domain, referenceSpec.Proxy.ListenPath)
val, listenPathExists := ListenPathMap.Get(domainHash)
if listenPathExists {
if val.(int) > 1 {
log.WithFields(logrus.Fields{
"prefix": "main",
"org_id": referenceSpec.APIDefinition.OrgID,
"api_id": referenceSpec.APIDefinition.APIID,
}).Error("Listen path is a duplicate: ", domainHash)
return true
}
}
return false
}
func generateDomainPath(hostname string, listenPath string) string {
return hostname + listenPath
}
func generateListenPathMap(APISpecs *[]*APISpec) {
// We must track the hostname no matter what
for _, referenceSpec := range *APISpecs {
domainHash := generateDomainPath(referenceSpec.Domain, referenceSpec.Proxy.ListenPath)
val, ok := ListenPathMap.Get(domainHash)
if ok {
thisVal := val.(int)
thisVal++
ListenPathMap.Set(domainHash, thisVal)
} else {
ListenPathMap.Set(domainHash, 1)
dN := referenceSpec.Domain
if dN == "" {
dN = "(no host)"
}
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
"domain": dN,
}).Info("Tracking hostname")
}
}
}
func processSpec(referenceSpec *APISpec,
Muxer *mux.Router,
index int,
redisStore *RedisClusterStorageManager,
redisOrgStore *RedisClusterStorageManager,
healthStore *RedisClusterStorageManager,
rpcAuthStore *RPCStorageHandler,
rpcOrgStore *RPCStorageHandler,
subrouter *mux.Router) *ChainObject {
var thisChainDefinition = ChainObject{}
thisChainDefinition.Subrouter = subrouter
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Info("Loading API")
if skipSpecBecauseInvalid(referenceSpec) {
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Warning("Skipped!")
thisChainDefinition.Skip = true
return &thisChainDefinition
}
// Set up LB targets:
if referenceSpec.Proxy.EnableLoadBalancing {
thisSL := tykcommon.NewHostListFromList(referenceSpec.Proxy.Targets)
referenceSpec.Proxy.StructuredTargetList = *thisSL
}
// 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
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{}
var mwAuthCheckFunc tykcommon.MiddlewareDefinition
mwPreFuncs := []tykcommon.MiddlewareDefinition{}
mwPostFuncs := []tykcommon.MiddlewareDefinition{}
mwPostAuthCheckFuncs := []tykcommon.MiddlewareDefinition{}
var mwDriver tykcommon.MiddlewareDriver
if EnableCoProcess {
loadBundle(referenceSpec)
}
// TODO: use config.EnableCoProcess
if config.EnableJSVM || EnableCoProcess {
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Debug("Loading Middleware")
mwPaths, mwAuthCheckFunc, mwPreFuncs, mwPostFuncs, mwPostAuthCheckFuncs, mwDriver = loadCustomMiddleware(referenceSpec)
if config.EnableJSVM && mwDriver == tykcommon.OttoDriver {
var pathPrefix string
if referenceSpec.CustomMiddlewareBundle != "" {
pathPrefix = strings.Join([]string{referenceSpec.APIID, referenceSpec.CustomMiddlewareBundle}, "-")
}
referenceSpec.JSVM.LoadJSPaths(mwPaths, pathPrefix)
}
}
if referenceSpec.EnableBatchRequestSupport {
addBatchEndpoint(referenceSpec, subrouter)
}
if referenceSpec.UseOauth2 {
log.Debug("Loading OAuth Manager")
if !RPC_EmergencyMode {
thisOauthManager := addOAuthHandlers(referenceSpec, subrouter, false)
log.Debug("-- Added OAuth Handlers")
referenceSpec.OAuthManager = thisOauthManager
log.Debug("Done loading OAuth Manager")
} else {
log.Warning("RPC Emergency mode detected! OAuth APIs will not function!")
}
}
enableVersionOverrides := false
for _, versionData := range referenceSpec.VersionData.Versions {
if versionData.OverrideTarget != "" {
enableVersionOverrides = true
break
}
}
// Already vetted
remote, _ := url.Parse(referenceSpec.APIDefinition.Proxy.TargetURL)
referenceSpec.target = remote
var proxy ReturningHttpHandler
if enableVersionOverrides {
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).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}
CheckCBEnabled(tykMiddleware)
CheckETEnabled(tykMiddleware)
keyPrefix := "cache-" + referenceSpec.APIDefinition.APIID
CacheStore := &RedisClusterStorageManager{KeyPrefix: keyPrefix, IsCache: true}
CacheStore.Connect()
var chain http.Handler
if referenceSpec.APIDefinition.UseKeylessAccess {
thisChainDefinition.Open = true
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Info("Checking security policy: Open")
// Add pre-process MW
var chainArray = []alice.Constructor{}
handleCORS(&chainArray, referenceSpec)
var baseChainArray = []alice.Constructor{}
AppendMiddleware(&baseChainArray, &RateCheckMW{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray, &IPWhiteListMiddleware{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray, &OrganizationMonitor{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray, &MiddlewareContextVars{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray, &VersionCheck{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray, &RequestSizeLimitMiddleware{tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray, &TrackEndpointMiddleware{tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray, &TransformMiddleware{tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray, &TransformHeaders{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray, &RedisCacheMiddleware{TykMiddleware: tykMiddleware, CacheStore: CacheStore}, tykMiddleware)
AppendMiddleware(&baseChainArray, &VirtualEndpoint{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray, &URLRewriteMiddleware{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray, &TransformMethod{TykMiddleware: tykMiddleware}, tykMiddleware)
log.Debug(referenceSpec.APIDefinition.Name, " - CHAIN SIZE: ", len(baseChainArray))
for _, obj := range mwPreFuncs {
if mwDriver != tykcommon.OttoDriver {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
"api_name": referenceSpec.APIDefinition.Name,
}).Debug("Registering coprocess middleware, hook name: ", obj.Name, "hook type: Pre", ", driver: ", mwDriver)
AppendMiddleware(&chainArray, &CoProcessMiddleware{tykMiddleware, coprocess.HookType_Pre, obj.Name, mwDriver}, tykMiddleware)
} else {
chainArray = append(chainArray, CreateDynamicMiddleware(obj.Name, true, obj.RequireSession, tykMiddleware))
}
}
for _, baseMw := range baseChainArray {
chainArray = append(chainArray, baseMw)
}
for _, obj := range mwPostFuncs {
if mwDriver != tykcommon.OttoDriver {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
"api_name": referenceSpec.APIDefinition.Name,
}).Debug("Registering coprocess middleware, hook name: ", obj.Name, "hook type: Post", ", driver: ", mwDriver)
AppendMiddleware(&chainArray, &CoProcessMiddleware{tykMiddleware, coprocess.HookType_Post, obj.Name, mwDriver}, tykMiddleware)
} else {
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}})
} else {
var chainArray = []alice.Constructor{}
handleCORS(&chainArray, referenceSpec)
var baseChainArray_PreAuth = []alice.Constructor{}
AppendMiddleware(&baseChainArray_PreAuth, &RateCheckMW{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PreAuth, &IPWhiteListMiddleware{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PreAuth, &OrganizationMonitor{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PreAuth, &VersionCheck{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PreAuth, &RequestSizeLimitMiddleware{tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PreAuth, &MiddlewareContextVars{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PreAuth, &TrackEndpointMiddleware{tykMiddleware}, tykMiddleware)
// Add pre-process MW
for _, obj := range mwPreFuncs {
if mwDriver != tykcommon.OttoDriver {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
"api_name": referenceSpec.APIDefinition.Name,
}).Debug("Registering coprocess middleware, hook name: ", obj.Name, "hook type: Pre", ", driver: ", mwDriver)
AppendMiddleware(&chainArray, &CoProcessMiddleware{tykMiddleware, coprocess.HookType_Pre, obj.Name, mwDriver}, tykMiddleware)
} else {
chainArray = append(chainArray, CreateDynamicMiddleware(obj.Name, true, obj.RequireSession, tykMiddleware))
}
}
for _, baseMw := range baseChainArray_PreAuth {
chainArray = append(chainArray, baseMw)
}
// Select the keying method to use for setting session states
var authArray = []alice.Constructor{}
if referenceSpec.APIDefinition.UseOauth2 {
// Oauth2
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Info("Checking security policy: OAuth")
authArray = append(authArray, CreateMiddleware(&Oauth2KeyExists{tykMiddleware}, tykMiddleware))
}
useCoProcessAuth := EnableCoProcess && mwDriver != tykcommon.OttoDriver && referenceSpec.EnableCoProcessAuth
var useOttoAuth bool = false
if !useCoProcessAuth {
useOttoAuth = mwDriver == tykcommon.OttoDriver && referenceSpec.EnableCoProcessAuth
}
if referenceSpec.APIDefinition.UseBasicAuth {
// Basic Auth
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Info("Checking security policy: Basic")
authArray = append(authArray, CreateMiddleware(&BasicAuthKeyIsValid{tykMiddleware}, tykMiddleware))
}
if referenceSpec.EnableSignatureChecking {
// HMAC Auth
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Info("Checking security policy: HMAC")
authArray = append(authArray, CreateMiddleware(&HMACMiddleware{TykMiddleware: tykMiddleware}, tykMiddleware))
}
if referenceSpec.EnableJWT {
// JWT Auth
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Info("Checking security policy: JWT")
authArray = append(authArray, CreateMiddleware(&JWTMiddleware{tykMiddleware}, tykMiddleware))
}
if referenceSpec.UseOpenID {
// JWT Auth
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Info("Checking security policy: OpenID")
// initialise the OID configuration on this reference Spec
authArray = append(authArray, CreateMiddleware(&OpenIDMW{TykMiddleware: tykMiddleware}, tykMiddleware))
}
if useCoProcessAuth {
// TODO: check if mwAuthCheckFunc is available/valid
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Info("Checking security policy: CoProcess Plugin")
log.WithFields(logrus.Fields{
"prefix": "coprocess",
"api_name": referenceSpec.APIDefinition.Name,
}).Debug("Registering coprocess middleware, hook name: ", mwAuthCheckFunc.Name, "hook type: CustomKeyCheck", ", driver: ", mwDriver)
if useCoProcessAuth {
newExtractor(referenceSpec, tykMiddleware)
AppendMiddleware(&authArray, &CoProcessMiddleware{tykMiddleware, coprocess.HookType_CustomKeyCheck, mwAuthCheckFunc.Name, mwDriver}, tykMiddleware)
}
}
if useOttoAuth {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Checking security policy: JS Plugin")
authArray = append(authArray, CreateDynamicAuthMiddleware(mwAuthCheckFunc.Name, tykMiddleware))
}
if referenceSpec.UseStandardAuth || (!referenceSpec.UseOpenID && !referenceSpec.EnableJWT && !referenceSpec.EnableSignatureChecking && !referenceSpec.APIDefinition.UseBasicAuth && !referenceSpec.APIDefinition.UseOauth2 && !useCoProcessAuth && !useOttoAuth) {
// Auth key
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Info("Checking security policy: Token")
authArray = append(authArray, CreateMiddleware(&AuthKey{tykMiddleware}, tykMiddleware))
}
for _, authMw := range authArray {
chainArray = append(chainArray, authMw)
}
for _, obj := range mwPostAuthCheckFuncs {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
"api_name": referenceSpec.APIDefinition.Name,
}).Debug("Registering coprocess middleware, hook name: ", obj.Name, "hook type: Pre", ", driver: ", mwDriver)
AppendMiddleware(&chainArray, &CoProcessMiddleware{tykMiddleware, coprocess.HookType_PostKeyAuth, obj.Name, mwDriver}, tykMiddleware)
}
var baseChainArray_PostAuth = []alice.Constructor{}
AppendMiddleware(&baseChainArray_PostAuth, &KeyExpired{tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PostAuth, &AccessRightsCheck{tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PostAuth, &RateLimitAndQuotaCheck{tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PostAuth, &GranularAccessMiddleware{tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PostAuth, &TransformMiddleware{tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PostAuth, &TransformHeaders{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PostAuth, &URLRewriteMiddleware{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PostAuth, &RedisCacheMiddleware{TykMiddleware: tykMiddleware, CacheStore: CacheStore}, tykMiddleware)
AppendMiddleware(&baseChainArray_PostAuth, &TransformMethod{TykMiddleware: tykMiddleware}, tykMiddleware)
AppendMiddleware(&baseChainArray_PostAuth, &VirtualEndpoint{TykMiddleware: tykMiddleware}, tykMiddleware)
for _, baseMw := range baseChainArray_PostAuth {
chainArray = append(chainArray, baseMw)
}
for _, obj := range mwPostFuncs {
if mwDriver != tykcommon.OttoDriver {
log.WithFields(logrus.Fields{
"prefix": "coprocess",
"api_name": referenceSpec.APIDefinition.Name,
}).Debug("Registering coprocess middleware, hook name: ", obj.Name, "hook type: Post", ", driver: ", mwDriver)
AppendMiddleware(&chainArray, &CoProcessMiddleware{tykMiddleware, coprocess.HookType_Post, obj.Name, mwDriver}, tykMiddleware)
} else {
chainArray = append(chainArray, CreateDynamicMiddleware(obj.Name, false, obj.RequireSession, tykMiddleware))
}
}
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Debug("Custom middleware completed processing")
// Use CreateMiddleware(&ModifiedMiddleware{tykMiddleware}, tykMiddleware) to run custom middleware
chain = alice.New(chainArray...).Then(DummyProxyHandler{SH: SuccessHandler{tykMiddleware}})
log.Debug("Chain completed")
userCheckHandler := http.HandlerFunc(UserRatesCheck())
simpleChain_PreAuth := []alice.Constructor{
CreateMiddleware(&IPWhiteListMiddleware{tykMiddleware}, tykMiddleware),
CreateMiddleware(&OrganizationMonitor{TykMiddleware: tykMiddleware}, tykMiddleware),
CreateMiddleware(&VersionCheck{TykMiddleware: tykMiddleware}, tykMiddleware)}
simpleChain_PostAuth := []alice.Constructor{
CreateMiddleware(&KeyExpired{tykMiddleware}, tykMiddleware),
CreateMiddleware(&AccessRightsCheck{tykMiddleware}, tykMiddleware)}
var fullSimpleChain = []alice.Constructor{}
for _, mw := range simpleChain_PreAuth {
fullSimpleChain = append(fullSimpleChain, mw)
}
for _, authMw := range authArray {
fullSimpleChain = append(fullSimpleChain, authMw)
}
for _, mw := range simpleChain_PostAuth {
fullSimpleChain = append(fullSimpleChain, mw)
}
simpleChain := alice.New(fullSimpleChain...).Then(userCheckHandler)
rateLimitPath := fmt.Sprintf("%s%s", referenceSpec.Proxy.ListenPath, "tyk/rate-limits/")
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Debug("Rate limit endpoint is: ", rateLimitPath)
//subrouter.Handle(rateLimitPath, simpleChain)
thisChainDefinition.RateLimitPath = rateLimitPath
thisChainDefinition.RateLimitChain = simpleChain
}
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
}).Debug("Setting Listen Path: ", referenceSpec.Proxy.ListenPath)
//subrouter.Handle(referenceSpec.Proxy.ListenPath+"{rest:.*}", chain)
thisChainDefinition.ThisHandler = chain
thisChainDefinition.ListenOn = referenceSpec.Proxy.ListenPath + "{rest:.*}"
notifyAPILoaded(referenceSpec)
return &thisChainDefinition
}
// Create the individual API (app) specs based on live configurations and assign middleware
func loadApps(APISpecs *[]*APISpec, Muxer *mux.Router) {
ListenPathMap = cmap.New()
// load the APi defs
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("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, redisOrgStore, healthStore, rpcAuthStore, rpcOrgStore := prepareStorage()
prepareSortOrder(APISpecs)
chainChannel := make(chan *ChainObject)
var wg sync.WaitGroup
wg.Add(len(*APISpecs))
// Create a new handler for each API spec
loadList := make([]*ChainObject, len(*APISpecs))
generateListenPathMap(APISpecs)
for i, referenceSpec := range *APISpecs {
var subrouter *mux.Router
go func(chChan chan *ChainObject, referenceSpec *APISpec, i int, subrouter *mux.Router) {
defer wg.Done()
// Handle custom domains
if config.EnableCustomDomains {
if referenceSpec.Domain != "" {
log.WithFields(logrus.Fields{
"prefix": "main",
"api_name": referenceSpec.APIDefinition.Name,
"domain": referenceSpec.Domain,
}).Info("Custom Domain set.")
subrouter = mainRouter.Host(referenceSpec.Domain).Subrouter()
} else {
subrouter = Muxer
}
} else {
subrouter = Muxer
}
thisChainObject := processSpec(referenceSpec, Muxer, i, redisStore, redisOrgStore, healthStore, rpcAuthStore, rpcOrgStore, subrouter)
thisChainObject.Index = i
chChan <- thisChainObject
}(chainChannel, referenceSpec, i, subrouter)
// TODO: This will not deal with skipped APis well
tempSpecRegister[referenceSpec.APIDefinition.APIID] = referenceSpec
}
go func() {
for thisCHObj := range chainChannel {
loadList[thisCHObj.Index] = thisCHObj
}
}()
wg.Wait()
time.Sleep(1 * time.Second)
for _, thisChainObject := range loadList {
if !thisChainObject.Skip {
if !thisChainObject.Open {
thisChainObject.Subrouter.Handle(thisChainObject.RateLimitPath, thisChainObject.RateLimitChain)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Processed and listening on: ", thisChainObject.ListenOn)
thisChainObject.Subrouter.Handle(thisChainObject.ListenOn, thisChainObject.ThisHandler)
}
}
// All APIs processed, now we can healthcheck
// Add a root message to check all is OK
Muxer.HandleFunc("/hello", pingTest)
// Swap in the new register
ApiSpecRegister = &tempSpecRegister
log.Debug("Checker host list")
// Kick off our host checkers
if config.UptimeTests.Disable == false {
SetCheckerHostList()
}
log.Debug("Checker host Done")
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Initialised API Definitions")
if config.SlaveOptions.UseRPC {
//log.Warning("TODO: PUT THE KEEPALIVE WATCHER BACK")
StartRPCKeepaliveWatcher(rpcAuthStore)
StartRPCKeepaliveWatcher(rpcOrgStore)
}
}