Debian Codegraph @

schema_validation/validate_urlencoded.go

raw
1 package schema_validation
2
3 import (
4 "encoding/json"
5 "fmt"
6 "log/slog"
7 "net/url"
8 "regexp"
9 "slices"
10 "sort"
11 "strconv"
12 "strings"
13
14 "github.com/pb33f/libopenapi-validator/errors"
15 "github.com/pb33f/libopenapi-validator/helpers"
16 "github.com/pb33f/libopenapi/datamodel/high/base"
17 v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
18 "github.com/pb33f/libopenapi/orderedmap"
19 )
20
21 var rxReserved = regexp.MustCompile(`[:/?#\[\]@!$&'()*+,;=]`)
22
23 func TransformURLEncodedToSchemaJSON(bodyString string, schema *base.Schema, encoding *orderedmap.Map[string, *v3.Encoding]) (map[string]any, []*errors.ValidationError) {
24 rawValues, err := url.ParseQuery(bodyString)
25 if err != nil {
26 return nil, []*errors.ValidationError{errors.InvalidURLEncodedParsing("empty form-urlencoded context", bodyString)}
27 }
28
29 jsonMap := unflattenValues(rawValues)
30
31 var validationErrors []*errors.ValidationError
32
33 if schema != nil {
34 if schema.Properties != nil {
35 for pair := orderedmap.First(schema.Properties); pair != nil; pair = pair.Next() {
36 propName := pair.Key()
37 propSchema := pair.Value().Schema()
38
39 var contentEncoding *v3.Encoding
40 var allowReserved bool
41
42 if encoding != nil {
43 contentEncoding = encoding.GetOrZero(propName)
44
45 if contentEncoding != nil {
46 allowReserved = contentEncoding.AllowReserved
47 }
48 }
49
50 if val, exists := jsonMap[propName]; exists {
51 newVal, err := applyEncodingRules(val, contentEncoding, propSchema)
52 if err != nil {
53 contentType := ""
54 if contentEncoding != nil {
55 contentType = contentEncoding.ContentType
56 }
57
58 validationErrors = append(validationErrors, errors.InvalidTypeEncoding(propSchema, propName, contentType))
59 } else {
60 jsonMap[propName] = newVal
61 val = newVal
62 }
63
64 validateEncodingRecursive(propName, val, allowReserved, &validationErrors, propSchema)
65 }
66 }
67 }
68
69 coerced := coerceValue(jsonMap, schema)
70 if asMap, ok := coerced.(map[string]any); ok {
71 jsonMap = asMap
72 }
73 }
74
75 return jsonMap, validationErrors
76 }
77
78 func applyEncodingRules(data any, encoding *v3.Encoding, schema *base.Schema) (any, error) {
79 style := "form"
80 explode := true
81 contentType := ""
82
83 if encoding != nil {
84 contentType = encoding.ContentType
85
86 if encoding.Style != "" {
87 style = encoding.Style
88 contentType = ""
89 }
90
91 if encoding.AllowReserved {
92 contentType = ""
93 }
94
95 if encoding.Explode != nil {
96 explode = *encoding.Explode
97 contentType = ""
98 } else if style != "form" {
99 explode = false
100 }
101 }
102
103 if contentType != "" && !IsURLEncodedContentType(contentType) && !strings.Contains(contentType, "text/plain") {
104 if strVal, ok := data.(string); ok {
105 if strings.Contains(contentType, helpers.JSONContentType) {
106 var parsed any
107 if err := json.Unmarshal([]byte(strVal), &parsed); err == nil {
108 return parsed, nil
109 }
110 return nil, fmt.Errorf("value matches content-type '%s' but could not be parsed", contentType)
111 }
112 }
113 }
114
115 if isArraySchema(schema) {
116 if strVal, ok := data.(string); ok {
117 if !explode {
118 switch style {
119 case helpers.Form:
120 return strings.Split(strVal, ","), nil
121 case helpers.SpaceDelimited:
122 return strings.Split(strVal, " "), nil
123 case helpers.PipeDelimited:
124 return strings.Split(strVal, "|"), nil
125 }
126 }
127 }
128 }
129
130 if style == helpers.DeepObject {
131 if _, ok := data.(map[string]any); !ok {
132 return data, nil
133 }
134 }
135
136 return data, nil
137 }
138
139 func unflattenValues(values url.Values) map[string]any {
140 result := make(map[string]any)
141
142 for k, v := range values {
143 if strings.Contains(k, "[") {
144 buildDeepMap(result, k, v)
145 } else {
146 if len(v) == 1 {
147 result[k] = v[0]
148 } else {
149 result[k] = v
150 }
151 }
152 }
153 return result
154 }
155
156 func buildDeepMap(root map[string]any, key string, value []string) {
157 parts := strings.FieldsFunc(key, func(r rune) bool {
158 return r == '[' || r == ']'
159 })
160
161 current := root
162 for i, part := range parts {
163 isLeaf := i == len(parts)-1
164
165 if isLeaf {
166 if len(value) == 1 {
167 current[part] = value[0]
168 } else {
169 current[part] = value
170 }
171 } else {
172 if _, ok := current[part]; !ok {
173 current[part] = make(map[string]any)
174 }
175 if nextMap, ok := current[part].(map[string]any); ok {
176 current = nextMap
177 } else {
178 return
179 }
180 }
181 }
182 }
183
184 func validateEncodingRecursive(path string, val any, allowReserved bool, errs *[]*errors.ValidationError, schema *base.Schema) {
185 if allowReserved {
186 return
187 }
188
189 switch v := val.(type) {
190 case string:
191 if rxReserved.MatchString(v) {
192 *errs = append(*errs, errors.ReservedURLEncodedValue(schema, path, v))
193 }
194 case []any:
195 for i, item := range v {
196 validateEncodingRecursive(fmt.Sprintf("%s[%d]", path, i), item, allowReserved, errs, schema)
197 }
198 case map[string]any:
199 for k, item := range v {
200 validateEncodingRecursive(fmt.Sprintf("%s[%s]", path, k), item, allowReserved, errs, schema)
201 }
202 case []string:
203 for i, item := range v {
204 if rxReserved.MatchString(item) {
205 *errs = append(*errs, errors.ReservedURLEncodedValue(schema, fmt.Sprintf("%s[%d]", path, i), item))
206 }
207 }
208 }
209 }
210
211 func coerceValue(data any, schema *base.Schema) any {
212 if schema == nil {
213 return data
214 }
215
216 targetTypes := []string{}
217 if len(schema.Type) > 0 {
218 targetTypes = append(targetTypes, schema.Type...)
219 }
220
221 extractTypes := func(proxies []*base.SchemaProxy) {
222 for _, proxy := range proxies {
223 sch := proxy.Schema()
224 if len(sch.Type) > 0 {
225 targetTypes = append(targetTypes, sch.Type...)
226 }
227 }
228 }
229 extractTypes(schema.AllOf)
230 extractTypes(schema.OneOf)
231 extractTypes(schema.AnyOf)
232
233 if len(targetTypes) == 0 {
234 return data
235 }
236
237 for _, t := range targetTypes {
238 converted, ok := tryConvert(data, t, schema)
239 if ok {
240 return converted
241 }
242 }
243 return data
244 }
245
246 func tryConvert(data any, targetType string, schema *base.Schema) (any, bool) {
247 var strVal string
248 var isString bool
249
250 switch v := data.(type) {
251 case string:
252 strVal = v
253 isString = true
254 case []string:
255 if len(v) > 0 {
256 strVal = v[0]
257 isString = true
258 }
259 }
260
261 switch targetType {
262 case helpers.Integer:
263 if !isString || strVal == "" {
264 return nil, false
265 }
266 i, err := strconv.ParseInt(strVal, 10, 64)
267 if err == nil {
268 return i, true
269 }
270
271 case helpers.Number:
272 if !isString || strVal == "" {
273 return nil, false
274 }
275 f, err := strconv.ParseFloat(strVal, 64)
276 if err == nil {
277 return f, true
278 }
279
280 case helpers.Boolean:
281 if !isString {
282 return nil, false
283 }
284 b, err := strconv.ParseBool(strVal)
285 if err == nil {
286 return b, true
287 }
288
289 case helpers.String:
290 if isString {
291 return strVal, true
292 }
293 return fmt.Sprintf("%v", data), true
294
295 case helpers.Array:
296 var arr []any
297 itemSchema := getSchemaItem(schema)
298
299 if vSlice, ok := data.([]any); ok {
300 for _, s := range vSlice {
301 arr = append(arr, coerceValue(s, itemSchema))
302 }
303 return arr, true
304 }
305
306 if vStringSlice, ok := data.([]string); ok {
307 for _, s := range vStringSlice {
308 arr = append(arr, coerceValue(s, itemSchema))
309 }
310 return arr, true
311 }
312
313 if vMap, ok := data.(map[string]any); ok {
314 keys := make([]int, 0, len(vMap))
315 mapIsArray := true
316 for k := range vMap {
317 idx, err := strconv.Atoi(k)
318 if err != nil {
319 mapIsArray = false
320 break
321 }
322 keys = append(keys, idx)
323 }
324 if mapIsArray {
325 sort.Ints(keys)
326 for _, k := range keys {
327 val := vMap[strconv.Itoa(k)]
328 arr = append(arr, coerceValue(val, itemSchema))
329 }
330 return arr, true
331 }
332 }
333
334 if isString {
335 arr = append(arr, coerceValue(strVal, itemSchema))
336 return arr, true
337 }
338
339 case helpers.Object:
340 if m, ok := data.(map[string]any); ok {
341 newMap := make(map[string]any)
342 for k, v := range m {
343 newMap[k] = v
344 }
345 if schema.Properties != nil {
346 for pair := orderedmap.First(schema.Properties); pair != nil; pair = pair.Next() {
347 propName := pair.Key()
348 if val, exists := newMap[propName]; exists {
349 newMap[propName] = coerceValue(val, pair.Value().Schema())
350 }
351 }
352 }
353 return newMap, true
354 }
355 }
356
357 return nil, false
358 }
359
360 func isArraySchema(schema *base.Schema) bool {
361 if schema == nil {
362 return false
363 }
364
365 return slices.Contains(schema.Type, helpers.Array)
366 }
367
368 func getSchemaItem(schema *base.Schema) *base.Schema {
369 if schema.Items != nil && schema.Items.IsA() {
370 return schema.Items.A.Schema()
371 }
372 return nil
373 }
374
375 func (v *urlEncodedValidator) validateURLEncodedWithVersion(schema *base.Schema, encoding *orderedmap.Map[string, *v3.Encoding], bodyString string, log *slog.Logger, version float32) (bool, []*errors.ValidationError) {
376 if schema == nil {
377 log.Info("schema is empty and cannot be validated")
378 return false, nil
379 }
380
381 transformedJSON, prevalidationErrors := TransformURLEncodedToSchemaJSON(bodyString, schema, encoding)
382 if len(prevalidationErrors) > 0 {
383 return false, prevalidationErrors
384 }
385
386 return v.schemaValidator.validateSchemaWithVersion(schema, nil, transformedJSON, log, version)
387 }
388
389 func IsURLEncodedContentType(mediaType string) bool {
390 mt := strings.ToLower(strings.TrimSpace(mediaType))
391 return strings.HasPrefix(mt, helpers.URLEncodedContentType)
392 }