-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcoprocess_id_extractor.go
315 lines (267 loc) · 9.98 KB
/
coprocess_id_extractor.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
package main
import (
"crypto/md5"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/mitchellh/mapstructure"
xmlpath "gopkg.in/xmlpath.v2"
"github.com/TykTechnologies/tyk/apidef"
"github.com/TykTechnologies/tyk/regexp"
)
// IdExtractor is the base interface for an ID extractor.
type IdExtractor interface {
ExtractAndCheck(*http.Request) (string, ReturnOverrides)
GenerateSessionID(string, BaseMiddleware) string
}
// BaseExtractor is the base structure for an ID extractor, it implements the IdExtractor interface. Other extractors may override some of its methods.
type BaseExtractor struct {
Config *apidef.MiddlewareIdExtractor
BaseMid BaseMiddleware
Spec *APISpec
}
// ExtractAndCheck is called from the CP middleware, if ID extractor is enabled for the current API.
func (e *BaseExtractor) ExtractAndCheck(r *http.Request) (sessionID string, returnOverrides ReturnOverrides) {
log.WithFields(logrus.Fields{
"prefix": "idextractor",
}).Error("This extractor doesn't implement an extraction method, rejecting.")
return "", ReturnOverrides{ResponseCode: 403, ResponseError: "Key not authorised"}
}
// ExtractHeader is used when a HeaderSource is specified.
func (e *BaseExtractor) ExtractHeader(r *http.Request) (headerValue string, err error) {
headerName := e.Config.ExtractorConfig["header_name"].(string)
headerValue = r.Header.Get(headerName)
if headerValue == "" {
err = errors.New("Bad header value.")
}
return headerValue, err
}
// ExtractForm is used when a FormSource is specified.
func (e *BaseExtractor) ExtractForm(r *http.Request, paramName string) (formValue string, err error) {
r.ParseForm()
if paramName == "" {
return "", errors.New("no form param name set")
}
values := r.Form[paramName]
if len(values) == 0 {
return "", errors.New("no form value")
}
return strings.Join(values, ""), nil
}
// ExtractBody is used when BodySource is specified.
func (e *BaseExtractor) ExtractBody(r *http.Request) (string, error) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return "", err
}
return string(body), err
}
// Error is a helper for logging the extractor errors. It always returns HTTP 400 (so we don't expose any details).
func (e *BaseExtractor) Error(r *http.Request, err error, message string) (returnOverrides ReturnOverrides) {
logEntry := getLogEntryForRequest(e.BaseMid.Logger(), r, "", nil)
logEntry.Info("Extractor error: ", message, ", ", err)
return ReturnOverrides{
ResponseCode: 400,
ResponseError: "Authorization field missing",
}
}
// GenerateSessionID is a helper for generating session IDs, it takes an input (usually the extractor output) and a middleware pointer.
func (e *BaseExtractor) GenerateSessionID(input string, mw BaseMiddleware) (sessionID string) {
data := []byte(input)
tokenID := fmt.Sprintf("%x", md5.Sum(data))
sessionID = generateToken(mw.Spec.OrgID, tokenID)
return sessionID
}
type ValueExtractor struct {
BaseExtractor
cfg *ValueExtractorConfig
}
type ValueExtractorConfig struct {
HeaderName string `mapstructure:"header_name" bson:"header_name" json:"header_name"`
FormParamName string `mapstructure:"param_name" bson:"param_name" json:"param_name"`
}
func (e *ValueExtractor) Extract(input interface{}) string {
headerValue := input.(string)
return headerValue
}
func (e *ValueExtractor) ExtractAndCheck(r *http.Request) (sessionID string, returnOverrides ReturnOverrides) {
if e.cfg == nil {
config := &ValueExtractorConfig{}
if err := mapstructure.Decode(e.Config.ExtractorConfig, config); err != nil {
returnOverrides = e.Error(r, err, "Couldn't decode ValueExtractor configuration")
return sessionID, returnOverrides
}
e.cfg = config
}
var extractorOutput string
var err error
switch e.Config.ExtractFrom {
case apidef.HeaderSource:
extractorOutput, err = e.ExtractHeader(r)
case apidef.FormSource:
extractorOutput, err = e.ExtractForm(r, e.cfg.FormParamName)
}
if err != nil {
returnOverrides = e.Error(r, err, "ValueExtractor error")
return sessionID, returnOverrides
}
sessionID = e.GenerateSessionID(extractorOutput, e.BaseMid)
previousSession, keyExists := e.BaseMid.CheckSessionAndIdentityForValidKey(sessionID, r)
if keyExists {
if previousSession.IdExtractorDeadline > time.Now().Unix() {
ctxSetSession(r, &previousSession, sessionID, true)
returnOverrides = ReturnOverrides{
ResponseCode: 200,
}
}
}
return sessionID, returnOverrides
}
type RegexExtractor struct {
BaseExtractor
compiledExpr *regexp.Regexp
cfg *RegexExtractorConfig
}
type RegexExtractorConfig struct {
HeaderName string `mapstructure:"header_name" bson:"header_name" json:"header_name"`
RegexExpression string `mapstructure:"regex_expression" bson:"regex_expression" json:"regex_expression"`
RegexMatchIndex int `mapstructure:"regex_match_index" bson:"regex_match_index" json:"regex_match_index"`
FormParamName string `mapstructure:"param_name" bson:"param_name" json:"param_name"`
}
func (e *RegexExtractor) ExtractAndCheck(r *http.Request) (SessionID string, returnOverrides ReturnOverrides) {
// Parse specific configuration settings:
if e.cfg == nil {
config := &RegexExtractorConfig{}
if err := mapstructure.Decode(e.Config.ExtractorConfig, config); err != nil {
returnOverrides = e.Error(r, err, "Can't decode RegexExtractor configuration")
return SessionID, returnOverrides
}
e.cfg = config
}
if e.Config.ExtractorConfig["regex_expression"] == nil {
returnOverrides = e.Error(r, nil, "RegexExtractor expects an expression")
return SessionID, returnOverrides
}
var err error
if e.compiledExpr == nil {
e.compiledExpr, err = regexp.Compile(e.cfg.RegexExpression)
if err != nil {
returnOverrides = e.Error(r, nil, "RegexExtractor found an invalid expression")
return SessionID, returnOverrides
}
}
var extractorOutput string
switch e.Config.ExtractFrom {
case apidef.HeaderSource:
extractorOutput, err = e.ExtractHeader(r)
case apidef.BodySource:
extractorOutput, err = e.ExtractBody(r)
case apidef.FormSource:
extractorOutput, err = e.ExtractForm(r, e.cfg.FormParamName)
}
if err != nil {
returnOverrides = e.Error(r, err, "RegexExtractor error")
return SessionID, returnOverrides
}
regexOutput := e.compiledExpr.FindAllString(extractorOutput, -1)
if e.cfg.RegexMatchIndex > len(regexOutput)-1 {
returnOverrides = e.Error(r, fmt.Errorf("Can't find regexp match group"), "RegexExtractor error")
return SessionID, returnOverrides
}
SessionID = e.GenerateSessionID(regexOutput[e.cfg.RegexMatchIndex], e.BaseMid)
previousSession, keyExists := e.BaseMid.CheckSessionAndIdentityForValidKey(SessionID, r)
if keyExists {
if previousSession.IdExtractorDeadline > time.Now().Unix() {
ctxSetSession(r, &previousSession, SessionID, true)
returnOverrides = ReturnOverrides{
ResponseCode: 200,
}
}
}
return SessionID, returnOverrides
}
type XPathExtractor struct {
BaseExtractor
cfg *XPathExtractorConfig
path *xmlpath.Path
}
type XPathExtractorConfig struct {
HeaderName string `mapstructure:"header_name" bson:"header_name" json:"header_name"`
RegexExpression string `mapstructure:"regex_expression" bson:"regex_expression" json:"regex_expression"`
RegexMatchIndex int `mapstructure:"regex_match_index" bson:"regex_match_index" json:"regex_match_index"`
FormParamName string `mapstructure:"param_name" bson:"param_name" json:"param_name"`
}
func (e *XPathExtractor) ExtractAndCheck(r *http.Request) (SessionID string, returnOverrides ReturnOverrides) {
var err error
config := &XPathExtractorConfig{}
if err = mapstructure.Decode(e.Config.ExtractorConfig, config); err != nil {
returnOverrides = e.Error(r, err, "Can't decode XPathExtractor configuration")
return SessionID, returnOverrides
}
e.cfg = config
if e.Config.ExtractorConfig["xpath_expression"] == nil {
returnOverrides = e.Error(r, err, "XPathExtractor: no expression set")
return SessionID, returnOverrides
}
if e.path == nil {
expressionString := e.Config.ExtractorConfig["xpath_expression"].(string)
e.path, err = xmlpath.Compile(expressionString)
if err != nil {
returnOverrides = e.Error(r, err, "XPathExtractor: bad expression")
return SessionID, returnOverrides
}
}
var extractorOutput string
switch e.Config.ExtractFrom {
case apidef.HeaderSource:
extractorOutput, err = e.ExtractHeader(r)
case apidef.BodySource:
extractorOutput, err = e.ExtractBody(r)
case apidef.FormSource:
extractorOutput, err = e.ExtractForm(r, e.cfg.FormParamName)
}
if err != nil {
returnOverrides = e.Error(r, err, "XPathExtractor error")
return SessionID, returnOverrides
}
extractedXml, err := xmlpath.Parse(strings.NewReader(extractorOutput))
if err != nil {
returnOverrides = e.Error(r, err, "XPathExtractor: couldn't parse input")
return SessionID, returnOverrides
}
output, ok := e.path.String(extractedXml)
if !ok {
returnOverrides = e.Error(r, err, "XPathExtractor: no input")
return SessionID, returnOverrides
}
SessionID = e.GenerateSessionID(output, e.BaseMid)
previousSession, keyExists := e.BaseMid.CheckSessionAndIdentityForValidKey(SessionID, r)
if keyExists {
if previousSession.IdExtractorDeadline > time.Now().Unix() {
ctxSetSession(r, &previousSession, SessionID, true)
returnOverrides = ReturnOverrides{
ResponseCode: 200,
}
}
}
return SessionID, returnOverrides
}
// newExtractor is called from the CP middleware for every API that specifies extractor settings.
func newExtractor(referenceSpec *APISpec, mw BaseMiddleware) {
var extractor IdExtractor
baseExtractor := BaseExtractor{&referenceSpec.CustomMiddleware.IdExtractor, mw, referenceSpec}
// Initialize a extractor based on the API spec.
switch referenceSpec.CustomMiddleware.IdExtractor.ExtractWith {
case apidef.ValueExtractor:
extractor = &ValueExtractor{baseExtractor, nil}
case apidef.RegexExtractor:
extractor = &RegexExtractor{baseExtractor, nil, nil}
case apidef.XPathExtractor:
extractor = &XPathExtractor{baseExtractor, nil, nil}
}
referenceSpec.CustomMiddleware.IdExtractor.Extractor = extractor
}