-
-
Notifications
You must be signed in to change notification settings - Fork 433
/
req_resp_decoder.go
1591 lines (1440 loc) · 45 KB
/
req_resp_decoder.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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package openapi3filter
import (
"archive/zip"
"bytes"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"gopkg.in/yaml.v3"
"github.com/getkin/kin-openapi/openapi3"
)
// ParseErrorKind describes a kind of ParseError.
// The type simplifies comparison of errors.
type ParseErrorKind int
const (
// KindOther describes an untyped parsing error.
KindOther ParseErrorKind = iota
// KindUnsupportedFormat describes an error that happens when a value has an unsupported format.
KindUnsupportedFormat
// KindInvalidFormat describes an error that happens when a value does not conform a format
// that is required by a serialization method.
KindInvalidFormat
)
// ParseError describes errors which happens while parse operation's parameters, requestBody, or response.
type ParseError struct {
Kind ParseErrorKind
Value any
Reason string
Cause error
path []any
}
var _ interface{ Unwrap() error } = ParseError{}
func (e *ParseError) Error() string {
var msg []string
if p := e.Path(); len(p) > 0 {
var arr []string
for _, v := range p {
arr = append(arr, fmt.Sprintf("%v", v))
}
msg = append(msg, fmt.Sprintf("path %v", strings.Join(arr, ".")))
}
msg = append(msg, e.innerError())
return strings.Join(msg, ": ")
}
func (e *ParseError) innerError() string {
var msg []string
if e.Value != nil {
msg = append(msg, fmt.Sprintf("value %v", e.Value))
}
if e.Reason != "" {
msg = append(msg, e.Reason)
}
if e.Cause != nil {
if v, ok := e.Cause.(*ParseError); ok {
msg = append(msg, v.innerError())
} else {
msg = append(msg, e.Cause.Error())
}
}
return strings.Join(msg, ": ")
}
// RootCause returns a root cause of ParseError.
func (e *ParseError) RootCause() error {
if v, ok := e.Cause.(*ParseError); ok {
return v.RootCause()
}
return e.Cause
}
func (e ParseError) Unwrap() error {
return e.Cause
}
// Path returns a path to the root cause.
func (e *ParseError) Path() []any {
var path []any
if v, ok := e.Cause.(*ParseError); ok {
p := v.Path()
if len(p) > 0 {
path = append(path, p...)
}
}
if len(e.path) > 0 {
path = append(path, e.path...)
}
return path
}
func invalidSerializationMethodErr(sm *openapi3.SerializationMethod) error {
return fmt.Errorf("invalid serialization method: style=%q, explode=%v", sm.Style, sm.Explode)
}
// Decodes a parameter defined via the content property as an object. It uses
// the user specified decoder, or our build-in decoder for application/json
func decodeContentParameter(param *openapi3.Parameter, input *RequestValidationInput) (
value any,
schema *openapi3.Schema,
found bool,
err error,
) {
var paramValues []string
switch param.In {
case openapi3.ParameterInPath:
var paramValue string
if paramValue, found = input.PathParams[param.Name]; found {
paramValues = []string{paramValue}
}
case openapi3.ParameterInQuery:
paramValues, found = input.GetQueryParams()[param.Name]
case openapi3.ParameterInHeader:
var headerValues []string
if headerValues, found = input.Request.Header[http.CanonicalHeaderKey(param.Name)]; found {
paramValues = headerValues
}
case openapi3.ParameterInCookie:
var cookie *http.Cookie
if cookie, err = input.Request.Cookie(param.Name); err == http.ErrNoCookie {
found = false
} else if err != nil {
return
} else {
paramValues = []string{cookie.Value}
found = true
}
default:
err = fmt.Errorf("unsupported parameter.in: %q", param.In)
return
}
if !found {
if param.Required {
err = fmt.Errorf("parameter %q is required, but missing", param.Name)
}
return
}
decoder := input.ParamDecoder
if decoder == nil {
decoder = defaultContentParameterDecoder
}
value, schema, err = decoder(param, paramValues)
return
}
func defaultContentParameterDecoder(param *openapi3.Parameter, values []string) (
outValue any,
outSchema *openapi3.Schema,
err error,
) {
// Only query parameters can have multiple values.
if len(values) > 1 && param.In != openapi3.ParameterInQuery {
err = fmt.Errorf("%s parameter %q cannot have multiple values", param.In, param.Name)
return
}
content := param.Content
if content == nil {
err = fmt.Errorf("parameter %q expected to have content", param.Name)
return
}
// We only know how to decode a parameter if it has one content, application/json
if len(content) != 1 {
err = fmt.Errorf("multiple content types for parameter %q", param.Name)
return
}
mt := content.Get("application/json")
if mt == nil {
err = fmt.Errorf("parameter %q has no content schema", param.Name)
return
}
outSchema = mt.Schema.Value
unmarshal := func(encoded string, paramSchema *openapi3.SchemaRef) (decoded any, err error) {
if err = json.Unmarshal([]byte(encoded), &decoded); err != nil {
if paramSchema != nil && !paramSchema.Value.Type.Is("object") {
decoded, err = encoded, nil
}
}
return
}
if len(values) == 1 {
if outValue, err = unmarshal(values[0], mt.Schema); err != nil {
err = fmt.Errorf("error unmarshaling parameter %q", param.Name)
return
}
} else {
outArray := make([]any, 0, len(values))
for _, v := range values {
var item any
if item, err = unmarshal(v, outSchema.Items); err != nil {
err = fmt.Errorf("error unmarshaling parameter %q", param.Name)
return
}
outArray = append(outArray, item)
}
outValue = outArray
}
return
}
type valueDecoder interface {
DecodePrimitive(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error)
DecodeArray(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) ([]any, bool, error)
DecodeObject(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (map[string]any, bool, error)
}
// decodeStyledParameter returns a value of an operation's parameter from HTTP request for
// parameters defined using the style format, and whether the parameter is supplied in the input.
// The function returns ParseError when HTTP request contains an invalid value of a parameter.
func decodeStyledParameter(param *openapi3.Parameter, input *RequestValidationInput) (any, bool, error) {
sm, err := param.SerializationMethod()
if err != nil {
return nil, false, err
}
var dec valueDecoder
switch param.In {
case openapi3.ParameterInPath:
if len(input.PathParams) == 0 {
return nil, false, nil
}
dec = &pathParamDecoder{pathParams: input.PathParams}
case openapi3.ParameterInQuery:
if len(input.GetQueryParams()) == 0 {
return nil, false, nil
}
dec = &urlValuesDecoder{values: input.GetQueryParams()}
case openapi3.ParameterInHeader:
dec = &headerParamDecoder{header: input.Request.Header}
case openapi3.ParameterInCookie:
dec = &cookieParamDecoder{req: input.Request}
default:
return nil, false, fmt.Errorf("unsupported parameter's 'in': %s", param.In)
}
return decodeValue(dec, param.Name, sm, param.Schema, param.Required)
}
func decodeValue(dec valueDecoder, param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef, required bool) (any, bool, error) {
var found bool
if len(schema.Value.AllOf) > 0 {
var value any
var err error
for _, sr := range schema.Value.AllOf {
var f bool
value, f, err = decodeValue(dec, param, sm, sr, required)
found = found || f
if value == nil || err != nil {
break
}
}
return value, found, err
}
if len(schema.Value.AnyOf) > 0 {
for _, sr := range schema.Value.AnyOf {
value, f, _ := decodeValue(dec, param, sm, sr, required)
found = found || f
if value != nil {
return value, found, nil
}
}
if required {
return nil, found, fmt.Errorf("decoding anyOf for parameter %q failed", param)
}
return nil, found, nil
}
if len(schema.Value.OneOf) > 0 {
isMatched := 0
var value any
for _, sr := range schema.Value.OneOf {
v, f, _ := decodeValue(dec, param, sm, sr, required)
found = found || f
if v != nil {
value = v
isMatched++
}
}
if isMatched >= 1 {
return value, found, nil
}
if required {
return nil, found, fmt.Errorf("decoding oneOf failed: %q is required", param)
}
return nil, found, nil
}
if schema.Value.Not != nil {
// TODO(decode not): handle decoding "not" JSON Schema
return nil, found, errors.New("not implemented: decoding 'not'")
}
if schema.Value.Type != nil {
var decodeFn func(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error)
switch {
case schema.Value.Type.Is("array"):
decodeFn = func(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) {
res, b, e := dec.DecodeArray(param, sm, schema)
if len(res) == 0 {
return nil, b, e
}
return res, b, e
}
case schema.Value.Type.Is("object"):
decodeFn = func(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) {
return dec.DecodeObject(param, sm, schema)
}
default:
decodeFn = dec.DecodePrimitive
}
return decodeFn(param, sm, schema)
}
switch vDecoder := dec.(type) {
case *pathParamDecoder:
_, found = vDecoder.pathParams[param]
case *urlValuesDecoder:
if schema.Value.Pattern != "" {
return dec.DecodePrimitive(param, sm, schema)
}
_, found = vDecoder.values[param]
case *headerParamDecoder:
_, found = vDecoder.header[http.CanonicalHeaderKey(param)]
case *cookieParamDecoder:
_, err := vDecoder.req.Cookie(param)
found = err != http.ErrNoCookie
default:
return nil, found, errors.New("unsupported decoder")
}
return nil, found, nil
}
// pathParamDecoder decodes values of path parameters.
type pathParamDecoder struct {
pathParams map[string]string
}
func (d *pathParamDecoder) DecodePrimitive(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) {
var prefix string
switch sm.Style {
case "simple":
// A prefix is empty for style "simple".
case "label":
prefix = "."
case "matrix":
prefix = ";" + param + "="
default:
return nil, false, invalidSerializationMethodErr(sm)
}
if d.pathParams == nil {
// HTTP request does not contains a value of the target path parameter.
return nil, false, nil
}
raw, ok := d.pathParams[param]
if !ok || raw == "" {
// HTTP request does not contains a value of the target path parameter.
return nil, false, nil
}
src, err := cutPrefix(raw, prefix)
if err != nil {
return nil, ok, err
}
val, err := parsePrimitive(src, schema)
return val, ok, err
}
func (d *pathParamDecoder) DecodeArray(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) ([]any, bool, error) {
var prefix, delim string
switch {
case sm.Style == "simple":
delim = ","
case sm.Style == "label" && !sm.Explode:
prefix = "."
delim = ","
case sm.Style == "label" && sm.Explode:
prefix = "."
delim = "."
case sm.Style == "matrix" && !sm.Explode:
prefix = ";" + param + "="
delim = ","
case sm.Style == "matrix" && sm.Explode:
prefix = ";" + param + "="
delim = ";" + param + "="
default:
return nil, false, invalidSerializationMethodErr(sm)
}
if d.pathParams == nil {
// HTTP request does not contains a value of the target path parameter.
return nil, false, nil
}
raw, ok := d.pathParams[param]
if !ok || raw == "" {
// HTTP request does not contains a value of the target path parameter.
return nil, false, nil
}
src, err := cutPrefix(raw, prefix)
if err != nil {
return nil, ok, err
}
val, err := parseArray(strings.Split(src, delim), schema)
return val, ok, err
}
func (d *pathParamDecoder) DecodeObject(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (map[string]any, bool, error) {
var prefix, propsDelim, valueDelim string
switch {
case sm.Style == "simple" && !sm.Explode:
propsDelim = ","
valueDelim = ","
case sm.Style == "simple" && sm.Explode:
propsDelim = ","
valueDelim = "="
case sm.Style == "label" && !sm.Explode:
prefix = "."
propsDelim = ","
valueDelim = ","
case sm.Style == "label" && sm.Explode:
prefix = "."
propsDelim = "."
valueDelim = "="
case sm.Style == "matrix" && !sm.Explode:
prefix = ";" + param + "="
propsDelim = ","
valueDelim = ","
case sm.Style == "matrix" && sm.Explode:
prefix = ";"
propsDelim = ";"
valueDelim = "="
default:
return nil, false, invalidSerializationMethodErr(sm)
}
if d.pathParams == nil {
// HTTP request does not contains a value of the target path parameter.
return nil, false, nil
}
raw, ok := d.pathParams[param]
if !ok || raw == "" {
// HTTP request does not contains a value of the target path parameter.
return nil, false, nil
}
src, err := cutPrefix(raw, prefix)
if err != nil {
return nil, ok, err
}
props, err := propsFromString(src, propsDelim, valueDelim)
if err != nil {
return nil, ok, err
}
val, err := makeObject(props, schema)
return val, ok, err
}
// cutPrefix validates that a raw value of a path parameter has the specified prefix,
// and returns a raw value without the prefix.
func cutPrefix(raw, prefix string) (string, error) {
if prefix == "" {
return raw, nil
}
if len(raw) < len(prefix) || raw[:len(prefix)] != prefix {
return "", &ParseError{
Kind: KindInvalidFormat,
Value: raw,
Reason: fmt.Sprintf("a value must be prefixed with %q", prefix),
}
}
return raw[len(prefix):], nil
}
// urlValuesDecoder decodes values of query parameters.
type urlValuesDecoder struct {
values url.Values
}
func (d *urlValuesDecoder) DecodePrimitive(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) {
if sm.Style != "form" {
return nil, false, invalidSerializationMethodErr(sm)
}
values, ok := d.values[param]
if len(values) == 0 {
// HTTP request does not contain a value of the target query parameter.
return nil, ok, nil
}
if schema.Value.Type == nil && schema.Value.Pattern != "" {
return values[0], ok, nil
}
val, err := parsePrimitive(values[0], schema)
return val, ok, err
}
func (d *urlValuesDecoder) DecodeArray(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) ([]any, bool, error) {
if sm.Style == "deepObject" {
return nil, false, invalidSerializationMethodErr(sm)
}
values, ok := d.values[param]
if len(values) == 0 {
// HTTP request does not contain a value of the target query parameter.
return nil, ok, nil
}
if !sm.Explode {
var delim string
switch sm.Style {
case "form":
delim = ","
case "spaceDelimited":
delim = " "
case "pipeDelimited":
delim = "|"
}
values = strings.Split(values[0], delim)
}
val, err := d.parseArray(values, sm, schema)
return val, ok, err
}
// parseArray returns an array that contains items from a raw array.
// Every item is parsed as a primitive value.
// The function returns an error when an error happened while parse array's items.
func (d *urlValuesDecoder) parseArray(raw []string, sm *openapi3.SerializationMethod, schemaRef *openapi3.SchemaRef) ([]any, error) {
var value []any
for i, v := range raw {
item, err := d.parseValue(v, schemaRef.Value.Items)
if err != nil {
if v, ok := err.(*ParseError); ok {
return nil, &ParseError{path: []any{i}, Cause: v}
}
return nil, fmt.Errorf("item %d: %w", i, err)
}
// If the items are nil, then the array is nil. There shouldn't be case where some values are actual primitive
// values and some are nil values.
if item == nil {
return nil, nil
}
value = append(value, item)
}
return value, nil
}
func (d *urlValuesDecoder) parseValue(v string, schema *openapi3.SchemaRef) (any, error) {
if len(schema.Value.AllOf) > 0 {
var value any
var err error
for _, sr := range schema.Value.AllOf {
value, err = d.parseValue(v, sr)
if value == nil || err != nil {
break
}
}
return value, err
}
if len(schema.Value.AnyOf) > 0 {
var value any
var err error
for _, sr := range schema.Value.AnyOf {
if value, err = d.parseValue(v, sr); err == nil {
return value, nil
}
}
return nil, err
}
if len(schema.Value.OneOf) > 0 {
isMatched := 0
var value any
var err error
for _, sr := range schema.Value.OneOf {
result, err := d.parseValue(v, sr)
if err == nil {
value = result
isMatched++
}
}
if isMatched == 1 {
return value, nil
} else if isMatched > 1 {
return nil, fmt.Errorf("decoding oneOf failed: %d schemas matched", isMatched)
} else if isMatched == 0 {
return nil, fmt.Errorf("decoding oneOf failed: %d schemas matched", isMatched)
}
return nil, err
}
if schema.Value.Not != nil {
// TODO(decode not): handle decoding "not" JSON Schema
return nil, errors.New("not implemented: decoding 'not'")
}
return parsePrimitive(v, schema)
}
const (
urlDecoderDelimiter = "\x1F" // should not conflict with URL characters
)
func (d *urlValuesDecoder) DecodeObject(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (map[string]any, bool, error) {
var propsFn func(url.Values) (map[string]string, error)
switch sm.Style {
case "form":
propsFn = func(params url.Values) (map[string]string, error) {
if len(params) == 0 {
// HTTP request does not contain query parameters.
return nil, nil
}
if sm.Explode {
props := make(map[string]string)
for key, values := range params {
props[key] = values[0]
}
return props, nil
}
values := params[param]
if len(values) == 0 {
// HTTP request does not contain a value of the target query parameter.
return nil, nil
}
return propsFromString(values[0], ",", ",")
}
case "deepObject":
propsFn = func(params url.Values) (map[string]string, error) {
props := make(map[string]string)
for key, values := range params {
if !regexp.MustCompile(fmt.Sprintf(`^%s\[`, regexp.QuoteMeta(param))).MatchString(key) {
continue
}
matches := regexp.MustCompile(`\[(.*?)\]`).FindAllStringSubmatch(key, -1)
switch l := len(matches); {
case l == 0:
// A query parameter's name does not match the required format, so skip it.
continue
case l >= 1:
kk := []string{}
for _, m := range matches {
kk = append(kk, m[1])
}
props[strings.Join(kk, urlDecoderDelimiter)] = strings.Join(values, urlDecoderDelimiter)
}
}
if len(props) == 0 {
// HTTP request does not contain query parameters encoded by rules of style "deepObject".
return nil, nil
}
return props, nil
}
default:
return nil, false, invalidSerializationMethodErr(sm)
}
props, err := propsFn(d.values)
if err != nil {
return nil, false, err
}
if props == nil {
return nil, false, nil
}
val, err := makeObject(props, schema)
if err != nil {
return nil, false, err
}
found := false
for propName := range schema.Value.Properties {
if _, ok := props[propName]; ok {
found = true
break
}
if schema.Value.Type.Permits("array") || schema.Value.Type.Permits("object") {
for k := range props {
path := strings.Split(k, urlDecoderDelimiter)
if _, ok := deepGet(val, path...); ok {
found = true
break
}
}
}
}
return val, found, nil
}
// headerParamDecoder decodes values of header parameters.
type headerParamDecoder struct {
header http.Header
}
func (d *headerParamDecoder) DecodePrimitive(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) {
if sm.Style != "simple" {
return nil, false, invalidSerializationMethodErr(sm)
}
raw, ok := d.header[http.CanonicalHeaderKey(param)]
if !ok || len(raw) == 0 {
// HTTP request does not contains a corresponding header or has the empty value
return nil, ok, nil
}
val, err := parsePrimitive(raw[0], schema)
return val, ok, err
}
func (d *headerParamDecoder) DecodeArray(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) ([]any, bool, error) {
if sm.Style != "simple" {
return nil, false, invalidSerializationMethodErr(sm)
}
raw, ok := d.header[http.CanonicalHeaderKey(param)]
if !ok || len(raw) == 0 {
// HTTP request does not contains a corresponding header
return nil, ok, nil
}
val, err := parseArray(strings.Split(raw[0], ","), schema)
return val, ok, err
}
func (d *headerParamDecoder) DecodeObject(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (map[string]any, bool, error) {
if sm.Style != "simple" {
return nil, false, invalidSerializationMethodErr(sm)
}
valueDelim := ","
if sm.Explode {
valueDelim = "="
}
raw, ok := d.header[http.CanonicalHeaderKey(param)]
if !ok || len(raw) == 0 {
// HTTP request does not contain a corresponding header.
return nil, ok, nil
}
props, err := propsFromString(raw[0], ",", valueDelim)
if err != nil {
return nil, ok, err
}
val, err := makeObject(props, schema)
return val, ok, err
}
// cookieParamDecoder decodes values of cookie parameters.
type cookieParamDecoder struct {
req *http.Request
}
func (d *cookieParamDecoder) DecodePrimitive(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (any, bool, error) {
if sm.Style != "form" {
return nil, false, invalidSerializationMethodErr(sm)
}
cookie, err := d.req.Cookie(param)
found := err != http.ErrNoCookie
if !found {
// HTTP request does not contain a corresponding cookie.
return nil, found, nil
}
if err != nil {
return nil, found, fmt.Errorf("decoding param %q: %w", param, err)
}
val, err := parsePrimitive(cookie.Value, schema)
return val, found, err
}
func (d *cookieParamDecoder) DecodeArray(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) ([]any, bool, error) {
if sm.Style != "form" || sm.Explode {
return nil, false, invalidSerializationMethodErr(sm)
}
cookie, err := d.req.Cookie(param)
found := err != http.ErrNoCookie
if !found {
// HTTP request does not contain a corresponding cookie.
return nil, found, nil
}
if err != nil {
return nil, found, fmt.Errorf("decoding param %q: %w", param, err)
}
val, err := parseArray(strings.Split(cookie.Value, ","), schema)
return val, found, err
}
func (d *cookieParamDecoder) DecodeObject(param string, sm *openapi3.SerializationMethod, schema *openapi3.SchemaRef) (map[string]any, bool, error) {
if sm.Style != "form" || sm.Explode {
return nil, false, invalidSerializationMethodErr(sm)
}
cookie, err := d.req.Cookie(param)
found := err != http.ErrNoCookie
if !found {
// HTTP request does not contain a corresponding cookie.
return nil, found, nil
}
if err != nil {
return nil, found, fmt.Errorf("decoding param %q: %w", param, err)
}
props, err := propsFromString(cookie.Value, ",", ",")
if err != nil {
return nil, found, err
}
val, err := makeObject(props, schema)
return val, found, err
}
// propsFromString returns a properties map that is created by splitting a source string by propDelim and valueDelim.
// The source string must have a valid format: pairs <propName><valueDelim><propValue> separated by <propDelim>.
// The function returns an error when the source string has an invalid format.
func propsFromString(src, propDelim, valueDelim string) (map[string]string, error) {
props := make(map[string]string)
pairs := strings.Split(src, propDelim)
// When propDelim and valueDelim is equal the source string follow the next rule:
// every even item of pairs is a properties's name, and the subsequent odd item is a property's value.
if propDelim == valueDelim {
// Taking into account the rule above, a valid source string must be splitted by propDelim
// to an array with an even number of items.
if len(pairs)%2 != 0 {
return nil, &ParseError{
Kind: KindInvalidFormat,
Value: src,
Reason: fmt.Sprintf("a value must be a list of object's properties in format \"name%svalue\" separated by %s", valueDelim, propDelim),
}
}
for i := 0; i < len(pairs)/2; i++ {
props[pairs[i*2]] = pairs[i*2+1]
}
return props, nil
}
// When propDelim and valueDelim is not equal the source string follow the next rule:
// every item of pairs is a string that follows format <propName><valueDelim><propValue>.
for _, pair := range pairs {
prop := strings.Split(pair, valueDelim)
if len(prop) != 2 {
return nil, &ParseError{
Kind: KindInvalidFormat,
Value: src,
Reason: fmt.Sprintf("a value must be a list of object's properties in format \"name%svalue\" separated by %s", valueDelim, propDelim),
}
}
props[prop[0]] = prop[1]
}
return props, nil
}
func deepGet(m map[string]any, keys ...string) (any, bool) {
for _, key := range keys {
val, ok := m[key]
if !ok {
return nil, false
}
if m, ok = val.(map[string]any); !ok {
return val, true
}
}
return m, true
}
func deepSet(m map[string]any, keys []string, value any) {
for i := 0; i < len(keys)-1; i++ {
key := keys[i]
if _, ok := m[key]; !ok {
m[key] = make(map[string]any)
}
m = m[key].(map[string]any)
}
m[keys[len(keys)-1]] = value
}
func findNestedSchema(parentSchema *openapi3.SchemaRef, keys []string) (*openapi3.SchemaRef, error) {
currentSchema := parentSchema
for _, key := range keys {
if currentSchema.Value.Type.Includes(openapi3.TypeArray) {
currentSchema = currentSchema.Value.Items
} else {
propertySchema, ok := currentSchema.Value.Properties[key]
if !ok {
if currentSchema.Value.AdditionalProperties.Schema == nil {
return nil, fmt.Errorf("nested schema for key %q not found", key)
}
currentSchema = currentSchema.Value.AdditionalProperties.Schema
continue
}
currentSchema = propertySchema
}
}
return currentSchema, nil
}
// makeObject returns an object that contains properties from props.
func makeObject(props map[string]string, schema *openapi3.SchemaRef) (map[string]any, error) {
mobj := make(map[string]any)
for kk, value := range props {
keys := strings.Split(kk, urlDecoderDelimiter)
if strings.Contains(value, urlDecoderDelimiter) {
// don't support implicit array indexes anymore
p := pathFromKeys(keys)
return nil, &ParseError{path: p, Kind: KindInvalidFormat, Reason: "array items must be set with indexes"}
}
deepSet(mobj, keys, value)
}
r, err := buildResObj(mobj, nil, "", schema)
if err != nil {
return nil, err
}
result, ok := r.(map[string]any)
if !ok {
return nil, &ParseError{Kind: KindOther, Reason: "invalid param object", Value: result}
}
return result, nil
}
// example: map[0:map[key:true] 1:map[key:false]] -> [map[key:true] map[key:false]]
func sliceMapToSlice(m map[string]any) ([]any, error) {
var result []any
keys := make([]int, 0, len(m))
for k := range m {
key, err := strconv.Atoi(k)
if err != nil {
return nil, fmt.Errorf("array indexes must be integers: %w", err)
}
keys = append(keys, key)
}
max := -1
for _, k := range keys {
if k > max {
max = k
}
}
for i := 0; i <= max; i++ {
val, ok := m[strconv.Itoa(i)]
if !ok {
result = append(result, nil)
continue
}
result = append(result, val)
}
return result, nil
}
// buildResObj constructs an object based on a given schema and param values
func buildResObj(params map[string]any, parentKeys []string, key string, schema *openapi3.SchemaRef) (any, error) {
mapKeys := parentKeys
if key != "" {
mapKeys = append(mapKeys, key)
}
switch {
case schema.Value.Type.Is("array"):
paramArr, ok := deepGet(params, mapKeys...)
if !ok {
return nil, nil
}
t, isMap := paramArr.(map[string]any)
if !isMap {
return nil, &ParseError{path: pathFromKeys(mapKeys), Kind: KindInvalidFormat, Reason: "array items must be set with indexes"}
}
// intermediate arrays have to be instantiated
arr, err := sliceMapToSlice(t)
if err != nil {
return nil, &ParseError{path: pathFromKeys(mapKeys), Kind: KindInvalidFormat, Reason: fmt.Sprintf("could not convert value map to array: %v", err)}
}
resultArr := make([]any /*not 0,*/, len(arr))
for i := range arr {
r, err := buildResObj(params, mapKeys, strconv.Itoa(i), schema.Value.Items)