forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coprocess_id_extractor.go
326 lines (255 loc) · 9.82 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
316
317
318
319
320
321
322
323
324
325
326
// +build coprocess
package main
import (
"bytes"
"crypto/md5"
"errors"
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/mitchellh/mapstructure"
"gopkg.in/xmlpath.v2"
"github.com/TykTechnologies/tyk/apidef"
)
// IdExtractor is the base interface for an ID extractor.
type IdExtractor interface {
ExtractAndCheck(*http.Request) (string, ReturnOverrides)
PostProcess(*http.Request, *SessionState, string)
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{403, "Key not authorised"}
}
// PostProcess sets context variables and updates the storage.
func (e *BaseExtractor) PostProcess(r *http.Request, session *SessionState, sessionID string) {
sessionLifetime := getLifetime(e.Spec, session)
e.Spec.SessionManager.UpdateSession(sessionID, session, sessionLifetime)
ctxSetSession(r, session)
ctxSetAuthToken(r, sessionID)
}
// 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
}
func (e *BaseExtractor) ExtractBody(r *http.Request) (bodyValue string, err error) {
return bodyValue, 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) {
log.WithFields(logrus.Fields{
"path": r.URL.Path,
"origin": GetIPFromRequest(r),
}).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 = mw.Spec.OrgID + tokenID
return sessionID
}
type ValueExtractor struct {
BaseExtractor
}
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) {
var extractorOutput string
var config ValueExtractorConfig
err := mapstructure.Decode(e.Config.ExtractorConfig, &config)
if err != nil {
returnOverrides = e.Error(r, err, "Couldn't decode ValueExtractor configuration")
return sessionID, returnOverrides
}
switch e.Config.ExtractFrom {
case apidef.HeaderSource:
extractorOutput, err = e.ExtractHeader(r)
case apidef.FormSource:
extractorOutput, err = e.ExtractForm(r, config.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)
if keyExists {
lastUpdated, _ := strconv.Atoi(previousSession.LastUpdated)
deadlineTs := int64(lastUpdated) + previousSession.IdExtractorDeadline
if deadlineTs > time.Now().Unix() {
e.PostProcess(r, &previousSession, sessionID)
returnOverrides = ReturnOverrides{
ResponseCode: 200,
}
}
}
return sessionID, returnOverrides
}
type RegexExtractor struct {
BaseExtractor
}
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) {
var extractorOutput string
var config RegexExtractorConfig
err := mapstructure.Decode(e.Config.ExtractorConfig, &config)
if err != nil {
returnOverrides = e.Error(r, err, "Can't decode RegexExtractor configuration")
return SessionID, returnOverrides
}
if e.Config.ExtractorConfig["regex_expression"] == nil {
returnOverrides = e.Error(r, nil, "RegexExtractor expects an expression")
return SessionID, returnOverrides
}
expression, err := regexp.Compile(config.RegexExpression)
if err != nil {
returnOverrides = e.Error(r, nil, "RegexExtractor found an invalid expression")
return SessionID, returnOverrides
}
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, config.FormParamName)
}
if err != nil {
returnOverrides = e.Error(r, err, "RegexExtractor error")
return SessionID, returnOverrides
}
regexOutput := expression.FindAllString(extractorOutput, -1)
SessionID = e.GenerateSessionID(regexOutput[config.RegexMatchIndex], e.BaseMid)
previousSession, keyExists := e.BaseMid.CheckSessionAndIdentityForValidKey(SessionID)
if keyExists {
lastUpdated, _ := strconv.Atoi(previousSession.LastUpdated)
deadlineTs := int64(lastUpdated) + previousSession.IdExtractorDeadline
if deadlineTs > time.Now().Unix() {
e.PostProcess(r, &previousSession, SessionID)
returnOverrides = ReturnOverrides{
ResponseCode: 200,
}
}
}
return SessionID, returnOverrides
}
type XPathExtractor struct {
BaseExtractor
}
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 extractorOutput string
var config XPathExtractorConfig
err := mapstructure.Decode(e.Config.ExtractorConfig, &config)
if e.Config.ExtractorConfig["xpath_expression"] == nil {
returnOverrides = e.Error(r, err, "XPathExtractor: no expression set")
return SessionID, returnOverrides
}
expressionString := e.Config.ExtractorConfig["xpath_expression"].(string)
expression, err := xmlpath.Compile(expressionString)
if err != nil {
returnOverrides = e.Error(r, err, "XPathExtractor: bad expression")
return SessionID, returnOverrides
}
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, config.FormParamName)
}
if err != nil {
returnOverrides = e.Error(r, err, "XPathExtractor error")
return SessionID, returnOverrides
}
extractedXml, err := xmlpath.Parse(bytes.NewBufferString(extractorOutput))
if err != nil {
returnOverrides = e.Error(r, err, "XPathExtractor: couldn't parse input")
return SessionID, returnOverrides
}
output, ok := expression.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)
if keyExists {
lastUpdated, _ := strconv.Atoi(previousSession.LastUpdated)
deadlineTs := int64(lastUpdated) + previousSession.IdExtractorDeadline
if deadlineTs > time.Now().Unix() {
e.PostProcess(r, &previousSession, SessionID)
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}
case apidef.RegexExtractor:
extractor = &RegexExtractor{baseExtractor}
case apidef.XPathExtractor:
extractor = &XPathExtractor{baseExtractor}
}
referenceSpec.CustomMiddleware.IdExtractor.Extractor = extractor
}