forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugins.go
368 lines (293 loc) · 8.92 KB
/
plugins.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gorilla/context"
"github.com/mitchellh/mapstructure"
"github.com/robertkrimen/otto"
_ "github.com/robertkrimen/otto/underscore"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
)
// MiniRequestObject is marshalled to JSON string and pased into JSON middleware
type MiniRequestObject struct {
Headers map[string][]string
SetHeaders map[string]string
DeleteHeaders []string
Body string
URL string
AddParams map[string]string
DeleteParams []string
}
type VMReturnObject struct {
Request MiniRequestObject
SessionMeta map[string]string
}
type nopCloser struct {
io.Reader
}
func (nopCloser) Close() error {
return nil
}
// DynamicMiddleware is a generic middleware that will execute JS code before continuing
type DynamicMiddleware struct {
*TykMiddleware
MiddlewareClassName string
Pre bool
UseSession bool
}
type DynamicMiddlewareConfig struct {
ConfigData map[string]string `mapstructure:"config_data" bson:"config_data" json:"config_data"`
}
// New lets you do any initialisations for the object can be done here
func (d *DynamicMiddleware) New() {}
// GetConfig retrieves the configuration from the API config - we user mapstructure for this for simplicity
func (d *DynamicMiddleware) GetConfig() (interface{}, error) {
var thisModuleConfig DynamicMiddlewareConfig
err := mapstructure.Decode(d.TykMiddleware.Spec.APIDefinition.RawData, &thisModuleConfig)
if err != nil {
log.Error(err)
return nil, err
}
return thisModuleConfig, nil
}
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
func (d *DynamicMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) {
t1 := time.Now().UnixNano()
// Createthe proxy object
defer r.Body.Close()
originalBody, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Error("Failed to read request body! ", err)
return nil, 200
}
thisRequestData := MiniRequestObject{
Headers: r.Header,
SetHeaders: make(map[string]string),
DeleteHeaders: make([]string, 0),
Body: string(originalBody),
URL: r.URL.Path,
AddParams: make(map[string]string),
DeleteParams: make([]string, 0),
}
asJsonRequestObj, encErr := json.Marshal(thisRequestData)
if encErr != nil {
log.Error("Failed to encode request object for dynamic middleware: ", encErr)
return nil, 200
}
var thisSessionState = SessionState{}
var authHeaderValue = ""
// Encode the session object (if not a pre-process)
if !d.Pre {
if d.UseSession {
thisSessionState = context.Get(r, SessionData).(SessionState)
authHeaderValue = context.Get(r, AuthHeaderValue).(string)
}
}
sessionAsJsonObj, sessEncErr := json.Marshal(thisSessionState)
if sessEncErr != nil {
log.Error("Failed to encode session for VM: ", sessEncErr)
return nil, 200
}
// Run the middleware
middlewareClassname := d.MiddlewareClassName
thisVM := d.Spec.JSVM.VM.Copy()
returnRaw, _ := thisVM.Run(middlewareClassname + `.DoProcessRequest(` + string(asJsonRequestObj) + `, ` + string(sessionAsJsonObj) + `);`)
returnDataStr, _ := returnRaw.ToString()
// Decode the return object
newRequestData := VMReturnObject{}
decErr := json.Unmarshal([]byte(returnDataStr), &newRequestData)
if decErr != nil {
log.Error("Failed to decode middleware request data on return from VM: ", decErr)
log.Debug(returnDataStr)
return nil, 200
}
// Reconstruct the request parts
r.ContentLength = int64(len(newRequestData.Request.Body))
r.Body = nopCloser{bytes.NewBufferString(newRequestData.Request.Body)}
r.URL.Path = newRequestData.Request.URL
// Delete and set headers
for _, dh := range newRequestData.Request.DeleteHeaders {
r.Header.Del(dh)
}
for h, v := range newRequestData.Request.SetHeaders {
r.Header.Set(h, v)
}
// Delete and set request parameters
values := r.URL.Query()
for _, k := range newRequestData.Request.DeleteParams {
values.Del(k)
}
for p, v := range newRequestData.Request.AddParams {
values.Set(p, v)
}
r.URL.RawQuery = values.Encode()
// Save the sesison data (if modified)
if !d.Pre {
if d.UseSession {
thisSessionState.MetaData = newRequestData.SessionMeta
d.Spec.SessionManager.UpdateSession(authHeaderValue, thisSessionState, 0)
}
}
log.Debug("JSVM middleware execution took: (ns) ", time.Now().UnixNano()-t1)
return nil, 200
}
// --- Utility functions during startup to ensure a sane VM is present for each API Def ----
type JSVM struct {
VM *otto.Otto
}
// Init creates the JSVM with the core library (tyk.js)
func (j *JSVM) Init(coreJS string) {
vm := otto.New()
coreJs, _ := ioutil.ReadFile(config.TykJSPath)
// Init TykJS namespace, constructors etc.
vm.Run(coreJs)
j.VM = vm
// Add environment API
j.LoadTykJSApi()
}
// LoadJSPaths will load JS classes and functionality in to the VM by file
func (j *JSVM) LoadJSPaths(paths []string) {
for _, mwPath := range paths {
js, loadErr := ioutil.ReadFile(mwPath)
if loadErr != nil {
log.Error("Failed to load Middleware JS: ", loadErr)
} else {
// No error, load the JS into the VM
log.Info("Loading JS File: ", mwPath)
j.VM.Run(js)
}
}
}
type TykJSHttpRequest struct {
Method string
Body string
Headers map[string]string
Domain string
Resource string
FormData map[string]string
}
type TykJSHttpResponse struct {
Code int
Body string
Headers map[string][]string
}
func (j *JSVM) LoadTykJSApi() {
// Enable a log
j.VM.Set("log", func(call otto.FunctionCall) otto.Value {
log.Info("[JSVM] [LOG]: ", call.Argument(0).String())
return otto.Value{}
})
// Enable the creation of HTTP Requsts
j.VM.Set("TykMakeHttpRequest", func(call otto.FunctionCall) otto.Value {
jsonHRO := call.Argument(0).String()
HRO := TykJSHttpRequest{}
if jsonHRO != "undefined" {
jsonErr := json.Unmarshal([]byte(jsonHRO), &HRO)
if jsonErr != nil {
log.Error("JSVM: Failed to deserialise HTTP Request object")
return otto.Value{}
}
// Make the request
domain := HRO.Domain
data := url.Values{}
for k, v := range HRO.FormData {
data.Set(k, v)
}
u, _ := url.ParseRequestURI(domain)
u.Path = HRO.Resource
urlStr := fmt.Sprintf("%v", u) // "https://api.com/user/"
client := &http.Client{}
var d *string
if HRO.Body != "" {
d = &HRO.Body
} else {
if len(HRO.FormData) > 0 {
thisD := data.Encode()
d = &thisD
} else {
d = nil
}
}
r, _ := http.NewRequest(HRO.Method, urlStr, nil)
if d != nil {
r, _ = http.NewRequest(HRO.Method, urlStr, bytes.NewBufferString(*d))
}
for k, v := range HRO.Headers {
r.Header.Add(k, v)
}
r.Close = true
resp, respErr := client.Do(r)
if respErr != nil {
log.Error("[JSVM]: Request failed: ", respErr)
return otto.Value{}
}
body, _ := ioutil.ReadAll(resp.Body)
tykResp := TykJSHttpResponse{
Code: resp.StatusCode,
Body: string(body),
Headers: resp.Header,
}
retAsStr, _ := json.Marshal(tykResp)
returnVal, retErr := j.VM.ToValue(string(retAsStr))
if retErr != nil {
log.Error("[JSVM]: Failed to encode return value: ", retErr)
return otto.Value{}
}
return returnVal
}
// Nope, return nothing
return otto.Value{}
})
// Expose Setters and Getters in the REST API for a key:
j.VM.Set("TykGetKeyData", func(call otto.FunctionCall) otto.Value {
apiKey := call.Argument(0).String()
apiId := call.Argument(1).String()
byteArray, _ := handleGetDetail(apiKey, apiId)
returnVal, retErr := j.VM.ToValue(string(byteArray))
if retErr != nil {
log.Error("[JSVM]: Failed to encode return value: ", retErr)
return otto.Value{}
}
return returnVal
})
j.VM.Set("TykSetKeyData", func(call otto.FunctionCall) otto.Value {
apiKey := call.Argument(0).String()
encoddedSession := call.Argument(1).String()
suppress_reset := call.Argument(2).String()
newSession := SessionState{}
decErr := json.Unmarshal([]byte(encoddedSession), &newSession)
if decErr != nil {
log.Error("[JSVM]: Failed to decode the sesison data")
return otto.Value{}
}
var dont_reset bool = false
if suppress_reset == "1" {
dont_reset = true
}
doAddOrUpdate(apiKey, newSession, dont_reset)
return otto.Value{}
})
// Batch request method
unsafeBatchHandler := BatchRequestHandler{}
j.VM.Set("TykBatchRequest", func(call otto.FunctionCall) otto.Value {
requestSet := call.Argument(0).String()
log.Debug("Batch input is: ", requestSet)
byteArray := unsafeBatchHandler.ManualBatchRequest([]byte(requestSet))
returnVal, retErr := j.VM.ToValue(string(byteArray))
if retErr != nil {
log.Error("[JSVM]: Failed to encode return value: ", retErr)
return otto.Value{}
}
return returnVal
})
TykReturnFunc := `
function TykJsResponse(response, session_meta) {
return JSON.stringify({Response: response, SessionMeta: session_meta})
};`
j.VM.Run(TykReturnFunc)
}