-
-
Notifications
You must be signed in to change notification settings - Fork 384
/
utils.go
426 lines (406 loc) · 10.8 KB
/
utils.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
package pkg
import (
"encoding/json"
"fmt"
"html"
"net/http"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/araddon/dateparse"
proto "go.keploy.io/server/grpc/regression"
"go.keploy.io/server/grpc/utils"
"go.keploy.io/server/pkg/models"
"go.uber.org/zap"
)
func IsTime(stringDate string) bool {
s := strings.TrimSpace(stringDate)
_, err := dateparse.ParseAny(s)
return err == nil
}
func AddHttpBodyToMap(body string, m map[string][]string) error {
// add body
if json.Valid([]byte(body)) {
var result interface{}
err := json.Unmarshal([]byte(body), &result)
if err != nil {
return err
}
j := Flatten(result)
for k, v := range j {
nk := "body"
if k != "" {
nk = nk + "." + k
}
m[nk] = v
}
} else {
// add it as raw text
m["body"] = []string{body}
}
return nil
}
func FlattenHttpResponse(h http.Header, body string) (map[string][]string, error) {
m := map[string][]string{}
for k, v := range h {
m["header."+k] = []string{strings.Join(v, "")}
}
err := AddHttpBodyToMap(body, m)
if err != nil {
return m, err
}
return m, nil
}
func FindNoisyFields(m map[string][]string, comparator func(string, []string) bool) []string {
var noise []string
for k, v := range m {
if comparator(k, v) {
noise = append(noise, k)
}
}
return noise
}
// Flatten takes a map and returns a new one where nested maps are replaced
// by dot-delimited keys.
// examples of valid jsons - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#examples
func Flatten(j interface{}) map[string][]string {
if j == nil {
return map[string][]string{"": {""}}
}
o := make(map[string][]string)
x := reflect.ValueOf(j)
switch x.Kind() {
case reflect.Map:
m, ok := j.(map[string]interface{})
if !ok {
return map[string][]string{}
}
for k, v := range m {
nm := Flatten(v)
for nk, nv := range nm {
fk := k
if nk != "" {
fk = fk + "." + nk
}
o[fk] = nv
}
}
case reflect.Bool:
o[""] = []string{strconv.FormatBool(x.Bool())}
case reflect.Float64:
o[""] = []string{strconv.FormatFloat(x.Float(), 'E', -1, 64)}
case reflect.String:
o[""] = []string{x.String()}
case reflect.Slice:
child, ok := j.([]interface{})
if !ok {
return map[string][]string{}
}
for _, av := range child {
nm := Flatten(av)
for nk, nv := range nm {
if ov, exists := o[nk]; exists {
o[nk] = append(ov, nv...)
} else {
o[nk] = nv
}
}
}
default:
fmt.Println("found invalid value in json", j, x.Kind())
}
return o
}
func IsValidPath(s string) bool {
return !strings.HasPrefix(s, "/etc/passwd") && !strings.Contains(s, "../")
}
// sanitiseInput sanitises user input strings before logging them for safety, removing newlines
// and escaping HTML tags. This is to prevent log injection, including forgery of log records.
// Reference: https://www.owasp.org/index.php/Log_Injection
func SanitiseInput(s string) string {
re := regexp.MustCompile(`(\n|\n\r|\r\n|\r)`)
return html.EscapeString(string(re.ReplaceAll([]byte(s), []byte(""))))
}
func CompareHeaders(h1 http.Header, h2 http.Header, res *[]models.HeaderResult, noise map[string]string) bool {
if res == nil {
return false
}
match := true
_, isHeaderNoisy := noise["header"]
for k, v := range h1 {
// Ignore go http router default headers
// if k == "Date" || k == "Content-Length" || k == "date" || k == "connection" {
// continue
// }
_, isNoisy := noise[k]
isNoisy = isNoisy || isHeaderNoisy
val, ok := h2[k]
if !isNoisy {
if !ok {
if checkKey(res, k) {
*res = append(*res, models.HeaderResult{
Normal: false,
Expected: models.Header{
Key: k,
Value: v,
},
Actual: models.Header{
Key: k,
Value: nil,
},
})
}
match = false
continue
}
if len(v) != len(val) {
if checkKey(res, k) {
*res = append(*res, models.HeaderResult{
Normal: false,
Expected: models.Header{
Key: k,
Value: v,
},
Actual: models.Header{
Key: k,
Value: val,
},
})
}
match = false
continue
}
for i, e := range v {
if val[i] != e {
if checkKey(res, k) {
*res = append(*res, models.HeaderResult{
Normal: false,
Expected: models.Header{
Key: k,
Value: v,
},
Actual: models.Header{
Key: k,
Value: val,
},
})
}
match = false
continue
}
}
}
if checkKey(res, k) {
*res = append(*res, models.HeaderResult{
Normal: true,
Expected: models.Header{
Key: k,
Value: v,
},
Actual: models.Header{
Key: k,
Value: val,
},
})
}
}
for k, v := range h2 {
// Ignore go http router default headers
// if k == "Date" || k == "Content-Length" || k == "date" || k == "connection" {
// continue
// }
_, isNoisy := noise[k]
isNoisy = isNoisy || isHeaderNoisy
val, ok := h1[k]
if isNoisy && checkKey(res, k) {
*res = append(*res, models.HeaderResult{
Normal: true,
Expected: models.Header{
Key: k,
Value: val,
},
Actual: models.Header{
Key: k,
Value: v,
},
})
continue
}
if !ok {
if checkKey(res, k) {
*res = append(*res, models.HeaderResult{
Normal: false,
Expected: models.Header{
Key: k,
Value: nil,
},
Actual: models.Header{
Key: k,
Value: v,
},
})
}
match = false
}
}
return match
}
func checkKey(res *[]models.HeaderResult, key string) bool {
for _, v := range *res {
if key == v.Expected.Key {
return false
}
}
return true
}
func Contains(elems []string, v string) bool {
for _, s := range elems {
if v == s {
return true
}
}
return false
}
func FilterFields(r interface{}, filter []string, logger *zap.Logger) interface{} { //This filters the headers that the user does not want to record
for _, v := range filter {
fields := strings.Split(v, ".")
if len(fields) < 3 {
logger.Error(fmt.Sprintf("failed to filter a tcs field `%v` due to invalid format. Format should be `<req_OR_resp_OR_all>.<header_OR_body>.<FIELD_NAME>`", v))
continue
}
fieldType := fields[0] //req, resp, all
fieldValue := fields[1] //header, body
fieldName := fields[2] //name of the header or body
switch i := r.(type) {
case models.TestCase: //This is for the case when the user wants to filter the headers of the testcases
// i := r.(models.TestCase)
if fieldType == "req" || fieldType == "all" {
fieldRegex := regexp.MustCompile(fieldName)
switch fieldValue {
case "header": // pair with matching key is filtered from request headers
for k := range i.HttpReq.Header { //If the regex matches the header name, delete it
if fieldRegex.MatchString(k) {
delete(i.HttpReq.Header, k)
}
}
// TODO: Filter for request body
}
}
if fieldType == "resp" || fieldType == "all" {
fieldRegex := regexp.MustCompile(fieldName)
switch fieldValue {
case "header": // filters pair with matching key from the response headers
for k := range i.HttpResp.Header {
if fieldRegex.MatchString(k) {
delete(i.HttpResp.Header, k)
}
}
// TODO: Filter for response body
}
}
case *proto.Mock_SpecSchema: //This is for the case when the user wants to filter the headers of the mocks
// i := r.(*proto.Mock_SpecSchema)
if fieldType == "req" || fieldType == "all" {
fieldRegex := regexp.MustCompile(fieldName)
switch fieldValue {
case "header": // pair with matching key is filtered from request headers
for k := range i.Req.Header {
if fieldRegex.MatchString(k) {
delete(i.Req.Header, k)
}
}
// TODO: Filter for response body
}
}
if fieldType == "resp" || fieldType == "all" {
fieldRegex := regexp.MustCompile(fieldName)
switch fieldValue {
case "header": // filters pair with matching key from the response headers
for k := range i.Res.Header {
if fieldRegex.MatchString(k) {
delete(i.Res.Header, k)
}
}
}
}
}
}
return r
}
// replaceUrlDomain changes the Domain of the full urlStr to domain
func replaceUrlDomain(urlStr string, domain string, logger *zap.Logger) (*url.URL, error) {
replaceUrl, err := url.Parse(urlStr)
if err != nil {
logger.Error("failed to replace http.Request domain field due to error while parsing url", zap.Error(err))
return replaceUrl, err
}
replaceUrl.Host = domain // changes the Domain of parsed url
return replaceUrl, nil
}
// ReplaceFields replaces the http test-case Request fields to values from the "replace" map.
func ReplaceFields(r interface{}, replace map[string]string, logger *zap.Logger) interface{} {
for k, v := range replace {
fields := strings.Split(k, ".")
fieldType := fields[0] //header, domain, method, proto_major, proto_minor
switch fieldType {
case "header": // FORMAT should be "header.key":"val1 | val2 | val3"
newHeader := strings.Split(v, " | ") //The value of the header is a string of the form "value1 | value2"
if len(fields) > 1 {
switch i := r.(type) {
case models.TestCase:
i.HttpReq.Header[fields[1]] = newHeader
case *proto.Mock_SpecSchema:
i.Req.Header[fields[1]] = utils.ToStrArr(newHeader)
}
} else {
logger.Error("failed to replace http.Request header field due to no header key provided. The format should be `map[string]string{'header.Accept': 'val1 | val2 | val3'}`")
}
case "domain":
switch i := r.(type) {
case models.TestCase:
if replacedUrl, err := replaceUrlDomain(i.HttpReq.URL, v, logger); err == nil {
i.HttpReq.URL = replacedUrl.String()
}
case *proto.Mock_SpecSchema:
if replacedUrl, err := replaceUrlDomain(i.Req.URL, v, logger); err == nil {
i.Req.URL = replacedUrl.String()
}
}
case "method":
switch i := r.(type) {
case models.TestCase:
i.HttpReq.Method = models.Method(v)
case *proto.Mock_SpecSchema:
i.Req.Method = v
i.Metadata["operation"] = v
}
case "proto_major":
protomajor, err := strconv.Atoi(v)
if err != nil {
logger.Error("failed to replace http.Request proto_major field", zap.Error(err))
}
switch i := r.(type) {
case models.TestCase:
i.HttpReq.ProtoMajor = protomajor
case *proto.Mock_SpecSchema:
i.Req.ProtoMajor = int64(protomajor)
}
case "proto_minor":
protominor, err := strconv.Atoi(v)
if err != nil {
logger.Error("failed to replace http.Request proto_minor field", zap.Error(err))
}
switch i := r.(type) {
case models.TestCase:
i.HttpReq.ProtoMinor = protominor
case *proto.Mock_SpecSchema:
i.Req.ProtoMinor = int64(protominor)
}
default:
logger.Error("Invlaid format for replace map keys. Possible values for keys are `header, domain, method, proto_major, proto_minor`")
}
}
return r
}