-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_scenario_key_data.go
301 lines (273 loc) · 9.25 KB
/
api_scenario_key_data.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
package types
import (
"encoding/json"
"fmt"
"regexp"
"strings"
"github.com/bhatti/api-mock-service/internal/fuzz"
log "github.com/sirupsen/logrus"
)
// APIKeyData defines keys of api scenario for in-memory store
type APIKeyData struct {
// Method for HTTP API
Method MethodType `yaml:"method" json:"method"`
// Name to uniquely identify the scenario
Name string `yaml:"name" json:"name"`
// Path for the API (excluding query params)
Path string `yaml:"path" json:"path"`
// Order of scenario
Order int `yaml:"order" json:"order"`
// Group of scenario
Group string `yaml:"group" json:"group"`
// Tags of scenario
Tags []string `yaml:"tags" json:"tags"`
// Predicate for the request
Predicate string `yaml:"predicate" json:"predicate"`
// AssertQueryParamsPattern for the API
AssertQueryParamsPattern map[string]string `yaml:"assert_query_params_pattern" json:"assert_query_params_pattern"`
// AssertPostParamsPattern for the API
AssertPostParamsPattern map[string]string `yaml:"assert_post_params_pattern" json:"assert_post_params_pattern"`
// AssertHeadersPattern for api response
AssertHeadersPattern map[string]string `yaml:"assert_headers_pattern" json:"assert_headers_pattern"`
// AssertContentsPattern for request optionally
AssertContentsPattern string `yaml:"assert_contents_pattern" json:"assert_contents_pattern"`
// LastUsageTime of key data
LastUsageTime int64
// RequestCount for the API
RequestCount uint64
}
// Equals compares path and query path
func (kd *APIKeyData) Equals(other *APIKeyData) error {
if kd.Method != other.Method {
return NewNotFoundError(fmt.Sprintf("method '%s' didn't match '%s'", kd.Method, other.Method))
}
if kd.Group != "" && other.Group != "" && kd.Group != other.Group {
return NewNotFoundError(fmt.Sprintf("group '%s' didn't match '%s'", kd.Group, other.Group))
}
otherPath := filterURLQueryParams(other.Path)
rePath := rePath(kd.Path)
matched, err := regexp.Match(rePath, []byte(otherPath))
if err != nil {
return err
}
log.WithFields(log.Fields{
"Group": kd.Group,
"Order": kd.Order,
"Other": other.String(),
"This": kd.String(),
"OtherPath": otherPath,
"ThisPath": kd.Path,
"RegexPath": rePath,
"Matched": matched,
}).Debugf("matching path...")
if !matched {
return NewNotFoundError(fmt.Sprintf("path '%s' didn't match '%s'", kd.Path, other.Path))
}
for k, msdQueryParamVal := range kd.AssertQueryParamsPattern {
targetQueryParamVal := other.AssertQueryParamsPattern[k]
if targetQueryParamVal != msdQueryParamVal &&
!reMatch(msdQueryParamVal, targetQueryParamVal) {
return NewValidationError(fmt.Sprintf("request queryParam '%s' didn't match [%v == %v]",
k, kd.AssertQueryParamsPattern, other.AssertQueryParamsPattern))
}
}
for k, msdPostParamVal := range kd.AssertPostParamsPattern {
targetPostParamVal := other.AssertPostParamsPattern[k]
if targetPostParamVal != msdPostParamVal &&
!reMatch(msdPostParamVal, targetPostParamVal) {
return NewValidationError(fmt.Sprintf("request post'%s' didn't match [%v == %v]",
k, kd.AssertPostParamsPattern, other.AssertPostParamsPattern))
}
}
if kd.AssertContentsPattern != "" &&
!strings.Contains(kd.AssertContentsPattern, other.AssertContentsPattern) &&
!reMatch(kd.AssertContentsPattern, other.AssertContentsPattern) {
if other.AssertContentsPattern == "" {
return NewValidationError(fmt.Sprintf("contents '%s' didn't match '%s'",
kd.AssertContentsPattern, other.AssertContentsPattern))
}
regex := make(map[string]string)
err := json.Unmarshal([]byte(kd.AssertContentsPattern), ®ex)
if err != nil {
return fmt.Errorf("failed to unmarshal contents '%s' regex due to %w", kd.AssertContentsPattern, err)
}
matchContents, err := fuzz.UnmarshalArrayOrObject([]byte(other.AssertContentsPattern))
if err != nil {
return fmt.Errorf("failed to unmarshal other contents '%s' regex due to %w", other.AssertContentsPattern, err)
}
err = fuzz.ValidateRegexMap(matchContents, regex)
if err != nil {
log.WithFields(log.Fields{
"Group": kd.Group,
"AssertContentsPattern": kd.AssertContentsPattern,
"OtherAssertContentsPattern": other.AssertContentsPattern,
"Error": err,
}).Debugf("didn't match")
return NewValidationError(fmt.Sprintf("contents didn't match due to %s", err))
}
}
for k, msdHeaderVal := range kd.AssertHeadersPattern {
targetHeaderVal := getDictValue(k, other.AssertHeadersPattern)
if targetHeaderVal != msdHeaderVal &&
!reMatch(msdHeaderVal, targetHeaderVal) {
return NewValidationError(fmt.Sprintf("%s request header didn't match [%v == %v], all headers %v",
k, targetHeaderVal, msdHeaderVal, other.AssertHeadersPattern))
}
}
if len(kd.Tags) > 0 && len(other.Tags) > 0 {
strMap := toStringMap(kd.Tags)
for _, tag := range other.Tags {
if !strMap[strings.ToUpper(tag)] {
return NewValidationError(fmt.Sprintf("%s request tag didn't match %v, all tags %v",
tag, kd.Tags, other.Tags))
}
}
}
if other.Name != "" && kd.Name != other.Name {
return NewValidationError(fmt.Sprintf("scenario name '%s' didn't match '%s'",
kd.Name, other.Name))
}
return nil
}
// MatchGroups return match groups for dynamic params in path
func (kd *APIKeyData) MatchGroups(path string) map[string]string {
return MatchPathGroups(kd.Path, path)
}
// MatchPathGroups return match groups for dynamic params in path
func MatchPathGroups(rawPath string, targetPath string) (res map[string]string) {
rePath := rePath(rawPath)
matched, err := regexp.Match(rePath, []byte(targetPath))
if err != nil {
return
}
if !matched {
return
}
res = make(map[string]string)
// extract dynamic properties using :id or {id} format
var rawParts [][]string
if strings.Contains(rawPath, ":") {
rawRe := regexp.MustCompile(`(:[\d\w-_]+)`)
rawParts = rawRe.FindAllStringSubmatch(rawPath, -1)
} else if strings.Contains(rawPath, "{") && strings.Contains(rawPath, "}") {
rawRe := regexp.MustCompile(`(\{[\d\w-_]+)`)
rawParts = rawRe.FindAllStringSubmatch(rawPath, -1)
} else {
return
}
// extract values
re := regexp.MustCompile(rePath)
parts := re.FindStringSubmatch(targetPath)
for i := 1; i < len(parts); i++ {
if len(rawParts[i-1]) > 0 && len(rawParts[i-1][0]) > 0 {
res[rawParts[i-1][0][1:]] = parts[i]
}
}
return
}
// Validate scenario
func (kd *APIKeyData) Validate() error {
if kd.Method == "" {
return fmt.Errorf("key method is not specified")
}
if kd.Path == "" {
return fmt.Errorf("key path is not specified")
}
if len(kd.Path) > 200 {
return fmt.Errorf("key path is too long %d", len(kd.Path))
}
if matched, err := regexp.Match(`^[\w\d\.\-_\/\\:{}]+$`, []byte(kd.Path)); err == nil && !matched {
return fmt.Errorf("key path is invalid with special characters '%s'", kd.Path)
}
kd.Path = NormalizePath(kd.Path, '/')
if !strings.HasPrefix(kd.Path, "/") {
kd.Path = "/" + kd.Path
}
if kd.Name == "" {
return fmt.Errorf("key scenario name is not specified")
}
if len(kd.Name) > 200 {
return fmt.Errorf("key scenario name is too long %d", len(kd.Name))
}
kd.Name = sanitizeSpecialChars(kd.Name, "")
return nil
}
// String
func (kd *APIKeyData) String() string {
return string(kd.Method) + "|" + kd.Path + "|" + kd.Name
}
// MethodPath helper method
func (kd *APIKeyData) MethodPath() string {
return strings.ToLower(string(kd.Method)) + "_" + SanitizeNonAlphabet(kd.Path, "_") // replace slash
}
// SafeName strips invalid characters
func (kd *APIKeyData) SafeName() string {
return SanitizeNonAlphabet(kd.Name, "")
}
// MethodNamePathPrefixKey returns full key for the scenario
func (kd *APIKeyData) MethodNamePathPrefixKey() string {
return string(kd.Method) + kd.Name + kd.PathPrefix(1)
}
// PartialMethodPathKey for key by method and first-level path
func (kd *APIKeyData) PartialMethodPathKey() string {
return string(kd.Method) + kd.PathPrefix(1)
}
// PathPrefix builds prefix of path
func (kd *APIKeyData) PathPrefix(max int) string {
parts := strings.Split(kd.Path, "/")
if len(parts) <= max {
return kd.Path
}
var buf strings.Builder
j := 0
for i := 0; i < len(parts); i++ {
if parts[i] != "" && j < max {
buf.WriteString("/" + parts[i])
j++
}
}
return buf.String()
}
func filterURLQueryParams(rawPath string) string {
ndx := strings.Index(rawPath, "?")
if ndx != -1 {
return rawPath[0:ndx]
}
return rawPath
}
func rePath(rawPath string) (rePath string) {
rawPath = filterURLQueryParams(rawPath)
targetPattern := `([^/]*)`
rePath = rawPath
if strings.Contains(rePath, ":") {
re := regexp.MustCompile(`:[\w\d-_]+`)
rePath = re.ReplaceAllString(rawPath, targetPattern)
} else if strings.Contains(rePath, "{") && strings.Contains(rePath, "}") {
re := regexp.MustCompile(`{[\w\d-_]+}`)
rePath = re.ReplaceAllString(rawPath, targetPattern)
}
ndx := strings.LastIndex(rePath, targetPattern)
if ndx != -1 {
rePath = fmt.Sprintf("%s(.+)%s", rePath[0:ndx], rePath[ndx+len(targetPattern):])
}
if len(rePath) > 0 {
rePath += `$`
}
return
}
func getDictValue(name string, dict map[string]string) string {
name = strings.ToUpper(name)
for k, v := range dict {
if strings.ToUpper(k) == name {
return v
}
}
return ""
}
func toStringMap(arr []string) (res map[string]bool) {
res = make(map[string]bool)
for _, e := range arr {
res[strings.ToUpper(e)] = true
}
return
}