-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_scenario.go
960 lines (896 loc) · 28.1 KB
/
api_scenario.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
package types
import (
"encoding/json"
"fmt"
"github.com/bhatti/api-mock-service/internal/fuzz"
log "github.com/sirupsen/logrus"
"hash/adler32"
"net/http"
"net/url"
"os"
"regexp"
"runtime/debug"
"strconv"
"strings"
"time"
)
// APIAuthorization defines mock auth parameters
type APIAuthorization struct {
Type string `json:"type,omitempty" yaml:"type,omitempty"`
Name string `json:"name,omitempty" yaml:"name,omitempty"`
In string `json:"in,omitempty" yaml:"in,omitempty"`
Format string `json:"format,omitempty" yaml:"format,omitempty"`
Scheme string `json:"scheme,omitempty" yaml:"scheme,omitempty"`
URL string `json:"url,omitempty" yaml:"url,omitempty"`
}
// APIRequest defines mock request for APIs
type APIRequest struct {
// PathParams for the API
PathParams map[string]string `yaml:"path_params" json:"path_params"`
// QueryParams for the API
QueryParams map[string]string `yaml:"query_params" json:"query_params"`
// PostParams for the API
PostParams map[string]string `yaml:"post_params" json:"post_params"`
// Headers for mock response
Headers map[string]string `yaml:"headers" json:"headers"`
// Contents for request optionally
Contents string `yaml:"contents" json:"contents"`
// ExampleContents sample for request optionally
ExampleContents string `yaml:"example_contents" json:"example_contents"`
// HTTPVersion version of http
HTTPVersion string `yaml:"http_version" json:"http_version"`
// 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 mock 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"`
// Assertions for validating response
Assertions []string `yaml:"assertions" json:"assertions"`
// Variables to set for templates
Variables map[string]string `yaml:"variables" json:"variables"`
}
// AddAssertion helper method
func AddAssertion(assertions []string, assert string) []string {
for _, next := range assertions {
if assert == next {
return assertions
}
}
return append(assertions, assert)
}
// ContentType find content-type
func (r APIRequest) ContentType(defContentType string) string {
for k, v := range r.Headers {
if strings.ToUpper(k) == strings.ToUpper(ContentTypeHeader) {
return fuzz.StripTypeTags(v)
}
}
return defContentType
}
// AuthHeader finds AuthHeaderType
func (r APIRequest) AuthHeader() string {
for k, v := range r.Headers {
if strings.ToUpper(k) == "AUTHORIZATION" {
return fuzz.StripTypeTags(v)
}
}
return ""
}
// SanitizeRegexValue sanitizes (val string) string {
func SanitizeRegexValue(val string) string {
if strings.HasPrefix(val, "__") || strings.HasPrefix(val, "(") {
return fuzz.RandRegex(val)
}
return fuzz.StripTypeTags(val)
}
// BuildTemplateParams builds template
func (r APIRequest) BuildTemplateParams(
req *http.Request,
pathGroups map[string]string,
inHeaders map[string][]string,
overrides map[string]any,
) (templateParams map[string]any, queryParams map[string]string, postParams map[string]string, reqHeaders map[string][]string) {
templateParams = make(map[string]any)
queryParams = make(map[string]string)
postParams = make(map[string]string)
reqHeaders = make(map[string][]string)
//for _, env := range os.Environ() {
// parts := strings.Split(env, "=")
// if len(parts) == 2 {
// templateParams[parts[0]] = parts[1]
// }
//}
for k, v := range r.Variables {
templateParams[k] = fuzz.StripTypeTags(v)
}
for k, v := range r.PathParams {
templateParams[k] = fuzz.StripTypeTags(v)
queryParams[k] = fuzz.StripTypeTags(v)
}
for k, v := range r.AssertQueryParamsPattern {
templateParams[k] = SanitizeRegexValue(v)
queryParams[k] = SanitizeRegexValue(v)
}
for k, v := range r.QueryParams {
templateParams[k] = fuzz.StripTypeTags(v)
queryParams[k] = fuzz.StripTypeTags(v)
}
for k, v := range r.AssertPostParamsPattern {
templateParams[k] = SanitizeRegexValue(v)
postParams[k] = SanitizeRegexValue(v)
}
for k, v := range r.PostParams {
templateParams[k] = fuzz.StripTypeTags(v)
postParams[k] = fuzz.StripTypeTags(v)
}
for k, v := range r.AssertHeadersPattern {
templateParams[k] = SanitizeRegexValue(v)
reqHeaders[k] = []string{SanitizeRegexValue(v)}
}
for k, v := range r.Headers {
templateParams[k] = fuzz.StripTypeTags(v)
reqHeaders[k] = []string{fuzz.StripTypeTags(v)}
}
if req.URL != nil {
for k, v := range req.URL.Query() {
templateParams[k] = fuzz.StripTypeTags(v[0])
queryParams[k] = fuzz.StripTypeTags(v[0])
}
for k, v := range req.PostForm {
templateParams[k] = fuzz.StripTypeTags(v[0])
postParams[k] = fuzz.StripTypeTags(v[0])
}
}
for k, v := range req.Header {
templateParams[k] = fuzz.StripTypeTags(v[0])
reqHeaders[k] = []string{fuzz.StripTypeTags(v[0])}
}
// Find any params for query params and path variables
for k, v := range pathGroups {
templateParams[k] = v
}
for k, v := range overrides {
templateParams[k] = v
queryParams[k] = fmt.Sprintf("%v", v)
}
for k, v := range inHeaders {
reqHeaders[k] = v
}
return
}
// TargetHeader find header matching target
func (r APIRequest) TargetHeader() string {
for k, v := range r.Headers {
if strings.Contains(strings.ToUpper(k), "TARGET") {
return fuzz.StripTypeTags(v)
}
}
return ""
}
// Assert asserts response
func (r APIRequest) Assert(
queryParams map[string]string,
postParams map[string]string,
reqHeaders map[string][]string,
reqContents any,
templateParams map[string]any) error {
if reqContents != nil {
templateParams["contents"] = reqContents
}
templateParams["headers"] = toFlatMap(reqHeaders)
for k, v := range r.AssertQueryParamsPattern {
actual := queryParams[k]
if actual == "" {
return fmt.Errorf("failed to find required query parameter '%s' with regex '%s'", k, v)
}
match, err := regexp.MatchString(v, actual)
if err != nil {
return fmt.Errorf("failed to fuzz required request query param '%s' with regex '%s' and actual value '%s' due to '%w'",
k, v, actual, err)
}
if !match {
return fmt.Errorf("didn't match required request query param '%s' with regex '%s' and actual value '%s'",
k, v, actual)
}
}
for k, v := range r.AssertPostParamsPattern {
actual := postParams[k]
if actual == "" {
return fmt.Errorf("failed to find required post parameter '%s' with regex '%s'", k, v)
}
match, err := regexp.MatchString(v, actual)
if err != nil {
return fmt.Errorf("failed to fuzz required request post param '%s' with regex '%s' and actual value '%s' due to '%w'",
k, v, actual, err)
}
if !match {
return fmt.Errorf("didn't match required request post param '%s' with regex '%s' and actual value '%s'",
k, v, actual)
}
}
for k, v := range r.AssertHeadersPattern {
actual := reqHeaders[k]
if len(actual) == 0 {
return fmt.Errorf("failed to find required request header '%s' with regex '%s'", k, v)
}
match, err := regexp.MatchString(v, actual[0])
if err != nil {
return fmt.Errorf("failed to fuzz required request header '%s' with regex '%s' and actual value '%s' due to '%w'",
k, v, actual[0], err)
}
if !match {
return fmt.Errorf("didn't match required request header '%s' with regex '%s' and actual value '%s'",
k, v, actual[0])
}
}
if r.AssertContentsPattern != "" {
regex := make(map[string]string)
err := json.Unmarshal([]byte(r.AssertContentsPattern), ®ex)
if err != nil {
return fmt.Errorf("failed to unmarshal request '%s' regex due to %w", r.AssertContentsPattern, err)
}
err = fuzz.ValidateRegexMap(reqContents, regex)
if err != nil {
return fmt.Errorf("failed to validate request due to %w", err)
}
}
for _, assertion := range r.Assertions {
assertion = normalizeAssertion(assertion)
b, err := fuzz.ParseTemplate("", []byte(assertion), templateParams)
if err != nil {
return fmt.Errorf("failed to parse request assertion %s due to %w", assertion, err)
}
if string(b) != "true" {
return fmt.Errorf("failed to assert request '%s' with value '%s', params: %v",
assertion, b, templateParams)
}
}
return nil
}
// AssertContentsPatternOrContent helper method
func (r APIRequest) AssertContentsPatternOrContent() string {
if r.ExampleContents != "" {
return r.ExampleContents
}
if r.AssertContentsPattern != "" {
return r.AssertContentsPattern
}
return r.Contents
}
// APIResponse defines mock response for APIs
type APIResponse struct {
// Headers for mock response
Headers map[string][]string `yaml:"headers" json:"headers"`
// Contents for request
Contents string `yaml:"contents" json:"contents"`
// ContentsFile for request
ContentsFile string `yaml:"contents_file" json:"contents_file"`
// ExampleContents sample for response optionally
ExampleContents string `yaml:"example_contents" json:"example_contents"`
// StatusCode for response
StatusCode int `yaml:"status_code" json:"status_code"`
// HTTPVersion version of http
HTTPVersion string `yaml:"http_version" json:"http_version"`
// SetVariables to set shared variables from response
SetVariables []string `yaml:"set_variables" json:"set_variables"`
// UnsetVariables to reset shared variables
UnsetVariables []string `yaml:"unset_variables" json:"unset_variables"`
// AssertHeadersPattern for mock 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"`
// Assertions for validating response
Assertions []string `yaml:"assertions" json:"assertions"`
}
// ContentType find content-type
func (r APIResponse) ContentType(defContentType string) string {
for k, v := range r.Headers {
if strings.ToUpper(k) == strings.ToUpper(ContentTypeHeader) {
return fuzz.StripTypeTags(v[0])
}
}
return defContentType
}
// Assert asserts response
func (r APIResponse) Assert(
resHeaders map[string][]string,
resContents any,
templateParams map[string]any) error {
if resContents != nil {
templateParams["contents"] = resContents
}
templateParams["headers"] = toFlatMap(resHeaders)
for k, v := range r.AssertHeadersPattern {
actualHeader := resHeaders[k]
if len(actualHeader) == 0 {
return fmt.Errorf("failed to find required response header %s with regex %s", k, v)
}
match, err := regexp.MatchString(v, actualHeader[0])
if err != nil {
return fmt.Errorf("failed to fuzz required response header %s with regex %s and actual value %s due to %w",
k, v, actualHeader[0], err)
}
if !match {
return fmt.Errorf("didn't match required response header %s with regex %s and actual value %s",
k, v, actualHeader[0])
}
}
if r.AssertContentsPattern != "" {
regex := make(map[string]string)
err := json.Unmarshal([]byte(r.AssertContentsPattern), ®ex)
if err != nil {
return fmt.Errorf("failed to unmarshal response '%s' regex due to %w", r.AssertContentsPattern, err)
}
err = fuzz.ValidateRegexMap(resContents, regex)
if err != nil {
return fmt.Errorf("failed to validate response due to %w", err)
}
}
for _, assertion := range r.Assertions {
assertion = normalizeAssertion(assertion)
b, err := fuzz.ParseTemplate("", []byte(assertion), templateParams)
if err != nil {
return fmt.Errorf("failed to parse assertion %s due to %w", assertion, err)
}
if string(b) != "true" {
return fmt.Errorf("failed to assert response '%s' with value '%s', params: %v",
assertion, b, templateParams)
}
}
return nil
}
// AssertContentsPatternOrContent helper method
func (r APIResponse) AssertContentsPatternOrContent() string {
if r.ExampleContents != "" {
return r.ExampleContents
}
if r.AssertContentsPattern != "" {
return r.AssertContentsPattern
}
return r.Contents
}
// APIScenario defines mock scenario for APIs
type APIScenario 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"`
// BaseURL of remote server
BaseURL string `yaml:"base_url" json:"base_url"`
// Description of scenario
Description string `yaml:"description" json:"description"`
// 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"`
// Authentication for the API
Authentication map[string]APIAuthorization `yaml:"authentication" json:"authentication"`
// Request for the API
Request APIRequest `yaml:"request" json:"request"`
// Response for the API
Response APIResponse `yaml:"response" json:"response"`
// WaitMillisBeforeReply for response
WaitBeforeReply time.Duration `yaml:"wait_before_reply" json:"wait_before_reply"`
// StartTime of request
StartTime time.Time `yaml:"start_time" json:"start_time"`
// EndTime of request
EndTime time.Time `yaml:"end_time" json:"end_time"`
// RequestCount of request
RequestCount uint64 `yaml:"-" json:"-"`
}
// ToKeyData converts scenario to key data
func (api *APIScenario) ToKeyData() *APIKeyData {
rawPath := NormalizePath(api.Path, '/')
if !strings.HasPrefix(rawPath, "/") {
rawPath = "/" + rawPath
}
return &APIKeyData{
Method: api.Method,
Name: api.Name,
Path: rawPath,
Group: api.Group,
Tags: api.Tags,
Order: api.Order,
Predicate: api.Predicate,
AssertQueryParamsPattern: api.Request.AssertQueryParamsPattern,
AssertContentsPattern: api.Request.AssertContentsPattern,
AssertHeadersPattern: api.Request.AssertHeadersPattern,
}
}
// BuildScenarioFromHTTP helper method
func BuildScenarioFromHTTP(
config *Configuration,
prefix string,
u *url.URL,
method string,
group string,
reqHTTPVersion string,
resHTTPVersion string,
reqBody []byte,
resBody []byte,
queryParams map[string][]string,
postParams map[string][]string,
reqHeaders map[string][]string,
reqContentType string,
resHeaders map[string][]string,
resContentType string,
resStatus int,
started time.Time,
ended time.Time,
) (*APIScenario, error) {
if u == nil {
return nil, fmt.Errorf("url is not specified for building api scenario")
}
if queryParams == nil {
queryParams = make(map[string][]string)
}
if postParams == nil {
postParams = make(map[string][]string)
}
if reqHeaders == nil {
reqHeaders = make(map[string][]string)
}
if resHeaders == nil {
resHeaders = make(map[string][]string)
}
reqContentType = headerValue(reqHeaders, ContentTypeHeader, reqContentType)
resContentType = headerValue(resHeaders, ContentTypeHeader, resContentType)
dataTemplate := fuzz.NewDataTemplateRequest(true, 1, 1)
matchReqContents, err := fuzz.UnmarshalArrayOrObjectAndExtractTypesAndMarshal(string(reqBody), dataTemplate)
if err != nil {
log.WithFields(log.Fields{
"Path": u,
"Method": method,
"Error": err,
}).Warnf("failed to unmarshal and extrate types for request")
}
matchResContents, err := fuzz.UnmarshalArrayOrObjectAndExtractTypesAndMarshal(string(resBody), dataTemplate)
if err != nil {
log.WithFields(log.Fields{
"Path": u,
"Method": method,
"Error": err,
}).Warnf("failed to unmarshal and extrate types for response")
}
reqAssertions := make([]string, 0)
resAssertions := []string{
`ResponseTimeMillisLE 5000`,
fmt.Sprintf(`ResponseStatusMatches %d`, resStatus),
}
reqHeaderAssertions := make(map[string]string)
if reqContentType != "" {
reqAssertions = AddAssertion(reqAssertions, fmt.Sprintf(`VariableMatches headers.Content-Type %s`,
reqContentType))
reqHeaderAssertions[ContentTypeHeader] = reqContentType
}
respHeaderAssertions := make(map[string]string)
if resContentType != "" {
resAssertions = AddAssertion(resAssertions, fmt.Sprintf(`VariableMatches headers.Content-Type %s`,
resContentType))
respHeaderAssertions[ContentTypeHeader] = resContentType
}
path := u.Path
if path == "" {
path = "/"
}
scenario := &APIScenario{
Method: MethodType(method),
Name: headerValue(reqHeaders, MockScenarioHeader, ""),
Path: path,
BaseURL: u.Scheme + "://" + u.Host,
Group: group,
Authentication: make(map[string]APIAuthorization),
Request: APIRequest{
QueryParams: make(map[string]string),
PostParams: make(map[string]string),
Headers: make(map[string]string),
Contents: fuzz.ReMarshalArrayOrObjectWithIndent(reqBody),
ExampleContents: fuzz.ReMarshalArrayOrObjectWithIndent(reqBody),
HTTPVersion: reqHTTPVersion,
AssertQueryParamsPattern: make(map[string]string),
AssertHeadersPattern: reqHeaderAssertions,
AssertContentsPattern: matchReqContents,
Assertions: reqAssertions,
Variables: make(map[string]string),
},
Response: APIResponse{
Headers: resHeaders,
Contents: fuzz.ReMarshalArrayOrObjectWithIndent(resBody),
ExampleContents: fuzz.ReMarshalArrayOrObjectWithIndent(resBody),
StatusCode: resStatus,
HTTPVersion: resHTTPVersion,
AssertHeadersPattern: respHeaderAssertions,
AssertContentsPattern: matchResContents,
Assertions: resAssertions,
SetVariables: fuzz.ExtractTopPrimitiveAttributes(resBody, 5),
},
}
if scenario.Group == "" {
scenario.Group = NormalizeGroup("", u.Path)
}
for k, v := range queryParams {
if len(v) > 0 {
scenario.Request.QueryParams[k] = fuzz.PrefixTypeExample + v[0]
if config.AssertQueryParams(k) {
scenario.Request.AssertQueryParamsPattern[k] = v[0]
}
}
}
for k, v := range postParams {
if len(v) > 0 {
scenario.Request.PostParams[k] = fuzz.PrefixTypeExample + v[0]
if config.AssertQueryParams(k) {
scenario.Request.AssertQueryParamsPattern[k] = v[0]
}
}
}
for k, v := range reqHeaders {
if len(v) > 0 {
scenario.Request.Headers[k] = fuzz.PrefixTypeExample + v[0]
if strings.Contains(strings.ToUpper(k), "TARGET") {
scenario.Request.AssertHeadersPattern[k] = v[0]
parts := strings.Split(v[0], ".")
if u.Path == "/" {
if len(parts) >= 2 {
scenario.Group = parts[len(parts)-2] + "_" + parts[len(parts)-1]
scenario.Tags = []string{scenario.Group}
}
}
} else if config.AssertHeader(k) {
scenario.Request.AssertHeadersPattern[k] = v[0]
}
}
}
authHeader := scenario.Request.AuthHeader()
if strings.Contains(authHeader, "AWS") {
scenario.addAWSHeaders()
} else if authHeader != "" {
scenario.addAuthHeaders()
}
if scenario.Name == "" {
scenario.SetName(prefix + scenario.Group) // Request / Response are added
}
scenario.Tags = []string{scenario.Group}
if scenario.Response.StatusCode >= 300 {
scenario.Predicate = "{{NthRequest 2}}"
} else {
scenario.Predicate = "{{NthRequest 1}}"
}
scenario.Description = fmt.Sprintf("%s at %v for %s", time.Now().UTC(), prefix, u)
scenario.StartTime = started.UTC()
scenario.EndTime = ended.UTC()
return scenario, nil
}
func (api *APIScenario) addAuthHeaders() {
api.Authentication["basicAuth"] = APIAuthorization{
Type: "http",
Name: AuthorizationHeader,
In: "header",
Scheme: "basic",
}
api.Authentication["bearerAuth"] = APIAuthorization{
Type: "http",
Name: AuthorizationHeader,
In: "header",
Scheme: "bearer",
Format: "auth-scheme",
}
}
func (api *APIScenario) addAWSHeaders() {
api.Authentication["aws.auth.sigv4"] = APIAuthorization{
Type: "apiKey",
Name: AuthorizationHeader,
In: "header",
Scheme: "x-amazon-apigateway-authtype",
Format: "awsSigv4",
}
api.Authentication["smithy.scenario.httpApiKeyAuth"] = APIAuthorization{
Type: "apiKey",
Name: "x-scenario-key",
In: "header",
}
api.Authentication["bearerAuth"] = APIAuthorization{
Type: "http",
Name: AuthorizationHeader,
In: "header",
Scheme: "bearer",
Format: "JWT",
}
}
// GetStartTime helper method
func (api *APIScenario) GetStartTime() time.Time {
if !api.StartTime.IsZero() {
return api.StartTime
}
return api.StartTime
}
// GetMillisTime helper method
func (api *APIScenario) GetMillisTime() int64 {
return api.GetEndTime().UnixMilli() - api.GetStartTime().UnixMilli()
}
// GetEndTime helper method
func (api *APIScenario) GetEndTime() time.Time {
if !api.EndTime.IsZero() {
return api.EndTime
}
return api.EndTime
}
// HasURL helper method
func (api *APIScenario) HasURL() bool {
return api.BaseURL != ""
}
// GetNetURL helper method
func (api *APIScenario) GetNetURL(u *url.URL) (*url.URL, error) {
return api.GetURL(u.Scheme + "://" + u.Host)
}
// GetURL helper method
func (api *APIScenario) GetURL(defBase string) (u *url.URL, err error) {
if api.BaseURL != "" {
u, err = url.Parse(api.BaseURL)
} else {
u, err = url.Parse(defBase)
}
if err != nil {
return nil, fmt.Errorf("failed to parse base '%s' due to %s", defBase, err)
}
params := url.Values{}
for k, v := range api.Request.QueryParams {
params.Add(k, v)
}
u, err = url.Parse(u.Scheme + "://" + u.Host + api.Path)
if u != nil {
u.RawQuery = params.Encode()
}
return
}
// String
func (api *APIScenario) String() string {
return string(api.Method) + api.Name + api.Group + api.Path
}
// SafeName strips invalid characters
func (api *APIScenario) SafeName() string {
return SanitizeNonAlphabet(api.Name, "")
}
// MethodPath helper method
func (api *APIScenario) MethodPath() string {
return strings.ToLower(string(api.Method)) + "_" + SanitizeNonAlphabet(api.Path, "_")
}
// MethodPathTarget helper method
func (api *APIScenario) MethodPathTarget() string {
return strings.ToLower(string(api.Method)) + "_" + SanitizeNonAlphabet(api.Path, "_") + // replace slashes
"_" + strings.ToLower(api.Request.TargetHeader())
}
// BuildURL helper method
func (api *APIScenario) BuildURL(overrideBaseURL string) string {
if overrideBaseURL == "" {
overrideBaseURL = api.BaseURL
}
return overrideBaseURL + api.Path
}
// Digest of scenario
func (api *APIScenario) Digest() string {
h := adler32.New()
_, _ = h.Write([]byte(api.Method))
_, _ = h.Write([]byte(api.Group))
_, _ = h.Write([]byte(api.Path))
_, _ = h.Write([]byte(api.Request.Contents))
for k, v := range api.Request.AssertQueryParamsPattern {
_, _ = h.Write([]byte(k))
_, _ = h.Write([]byte(v))
}
for k, v := range api.Request.AssertHeadersPattern {
_, _ = h.Write([]byte(k))
_, _ = h.Write([]byte(v))
}
_, _ = h.Write([]byte(api.Request.AssertContentsPattern))
_, _ = h.Write([]byte(api.Response.Contents))
_, _ = h.Write([]byte(api.Response.ContentsFile))
return fmt.Sprintf("%x", h.Sum(nil))
}
// Validate scenario
func (api *APIScenario) Validate() error {
if api.Method == "" {
return fmt.Errorf("method is not specified")
}
if api.Path == "" {
debug.PrintStack()
return fmt.Errorf("scenario path is not specified %s", api.BaseURL)
}
if len(api.Path) > 200 {
return fmt.Errorf("path is too long %d", len(api.Path))
}
if matched, err := regexp.Match(`^[\w\d\.\-_\/\\:{}]+$`, []byte(api.Path)); err == nil && !matched {
return fmt.Errorf("path is invalid with special characters '%s'", api.Path)
}
api.Path = NormalizePath(api.Path, '/')
if !strings.HasPrefix(api.Path, "/") {
api.Path = "/" + api.Path
}
if api.Name == "" {
return fmt.Errorf("scenario name is not specified")
}
if len(api.Name) > 200 {
return fmt.Errorf("scenario name is too long %d", len(api.Name))
}
api.Name = sanitizeSpecialChars(api.Name, "")
if len(api.Response.Contents) > 1024*1024*1024 {
return fmt.Errorf("contents is too long %d", len(api.Response.Contents))
}
return nil
}
// NormalPath normalizes path
func (api *APIScenario) NormalPath(sep uint8) string {
return NormalizePath(api.Path, sep)
}
// SetName sets name
func (api *APIScenario) SetName(prefix string) {
api.Name = api.BuildName(prefix)
}
// BuildName builds name
func (api *APIScenario) BuildName(prefix string) string {
return fmt.Sprintf("%s%s-%d-%s", prefix, NormalizeDirPath(api.NormalName()), api.Response.StatusCode, api.Digest())
}
// NormalName normalizes name from path
func (api *APIScenario) NormalName() string {
return NormalizePath(api.Path, '-')
}
// NormalizeDirPath normalizes dir path
func NormalizeDirPath(path string) string {
path = NormalizePath(path, os.PathSeparator)
ndx := strings.Index(path, ":")
if ndx == -1 {
ndx = strings.Index(path, "{")
}
if ndx > 1 {
path = path[0 : ndx-1]
} else if ndx == 0 {
path = ""
}
return path
}
// NormalizePath normalizes path
func NormalizePath(path string, sepChar uint8) string {
sep := fmt.Sprintf("%c", sepChar)
if re, err := regexp.Compile(`[\/\\]+`); err == nil {
path = re.ReplaceAllString(path, sep)
}
if len(path) < 2 {
return path
}
from := 0
to := len(path)
if strings.HasPrefix(path, sep) {
from = 1
}
if strings.HasSuffix(path, sep) {
to = len(path) - 1
}
return path[from:to]
}
func reMatch(re string, str string) bool {
re = fuzz.StripTypeTags(re)
match, err := regexp.MatchString(re, str)
if err != nil {
return false
}
return match
}
func normalizeAssertion(assertion string) string {
if !strings.HasPrefix(assertion, "{{") {
parts := strings.Split(assertion, " ")
var sb strings.Builder
sb.WriteString("{{")
for i, next := range parts {
if i > 0 {
if strings.HasPrefix(next, "\"") {
sb.WriteString(fmt.Sprintf(` %s`, next))
} else {
sb.WriteString(fmt.Sprintf(` "%s"`, next))
}
} else {
sb.WriteString(next)
}
}
sb.WriteString("}}")
assertion = sb.String()
}
return assertion
}
func toFlatMap(headers map[string][]string) map[string]string {
flatHeaders := make(map[string]string)
for k, v := range headers {
flatHeaders[k] = v[0]
}
return flatHeaders
}
// sanitizeSpecialChars helper method
func sanitizeSpecialChars(name string, rep string) string {
re := regexp.MustCompile(`[^\w\d-_\. ]`)
return strings.TrimSpace(re.ReplaceAllString(name, rep))
}
// SanitizeNonAlphabet helper method
func SanitizeNonAlphabet(name string, rep string) string {
if re, err := regexp.Compile(`[^a-zA-Z0-9_\-:]`); err == nil {
name = re.ReplaceAllString(name, rep)
}
if re, err := regexp.Compile(rep + `+`); err == nil {
name = re.ReplaceAllString(name, rep)
}
if re, err := regexp.Compile(rep + `$`); err == nil {
name = re.ReplaceAllString(name, "")
}
return name
}
// BuildTestScenario helper method
func BuildTestScenario(method MethodType, name string, path string, n int) *APIScenario {
return &APIScenario{
Method: method,
Name: name,
Path: path,
Group: path,
Description: name,
Request: APIRequest{
HTTPVersion: "1.1",
QueryParams: make(map[string]string),
PostParams: make(map[string]string),
Headers: make(map[string]string),
AssertQueryParamsPattern: map[string]string{"a": `\d+`, "b": "abc"},
AssertHeadersPattern: map[string]string{
ContentTypeHeader: "application/json",
"ETag": `\d{3}`,
},
},
Response: APIResponse{
HTTPVersion: "1.1",
Headers: map[string][]string{
"ETag": {strconv.Itoa(n)},
ContentTypeHeader: {"application/json"},
},
Contents: "test body",
StatusCode: 200,
},
WaitBeforeReply: time.Duration(1) * time.Second,
}
}
// NormalizeGroup normalizes group name
func NormalizeGroup(title string, path string) string {
if title != "" {
return title
}
n := strings.Index(path, "{")
if n > 0 {
path = path[0 : n-1]
} else if n == 0 {
path = ""
}
n = strings.Index(path, ":")
if n > 0 {
path = path[0 : n-1]
} else if n == 0 {
path = ""
}
if len(path) > 0 {
path = path[1:]
}
group := strings.ReplaceAll(path, "/", "_")
if group == "" {
group = "root"
}
return group
}
func headerValue(headers map[string][]string, name string, defVal string) string {
vals := headers[name]
if len(vals) == 0 {
return defVal
}
return vals[0]
}