Debian Codegraph @

parameters/path_parameters.go

raw
1 // Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package parameters
5
6 import (
7 "fmt"
8 "net/http"
9 "net/url"
10 "regexp"
11 "strconv"
12 "strings"
13
14 "github.com/pb33f/libopenapi/datamodel/high/base"
15
16 v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
17
18 "github.com/pb33f/libopenapi-validator/errors"
19 "github.com/pb33f/libopenapi-validator/helpers"
20 "github.com/pb33f/libopenapi-validator/paths"
21 )
22
23 func (v *paramValidator) ValidatePathParams(request *http.Request) (bool, []*errors.ValidationError) {
24 pathItem, errs, foundPath := paths.FindPath(request, v.document, v.options)
25 if len(errs) > 0 {
26 return false, errs
27 }
28 return v.ValidatePathParamsWithPathItem(request, pathItem, foundPath)
29 }
30
31 func (v *paramValidator) ValidatePathParamsWithPathItem(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError) {
32 if pathItem == nil {
33 return false, []*errors.ValidationError{{
34 ValidationType: helpers.PathValidation,
35 ValidationSubType: helpers.ValidationMissing,
36 Message: fmt.Sprintf("%s Path '%s' not found", request.Method, request.URL.Path),
37 Reason: fmt.Sprintf("The %s request contains a path of '%s' "+
38 "however that path, or the %s method for that path does not exist in the specification",
39 request.Method, request.URL.Path, request.Method),
40 SpecLine: -1,
41 SpecCol: -1,
42 HowToFix: errors.HowToFixPath,
43 }}
44 }
45 // split the path into segments
46 submittedSegments := strings.Split(paths.StripRequestPath(request, v.document), helpers.Slash)
47 pathSegments := strings.Split(pathValue, helpers.Slash)
48
49 // get the operation method for error reporting
50 operation := strings.ToLower(request.Method)
51
52 // extract params for the operation
53 params := helpers.ExtractParamsForOperation(request, pathItem)
54 var validationErrors []*errors.ValidationError
55 for _, p := range params {
56 if p.In == helpers.Path {
57 // var paramTemplate string
58 for x := range pathSegments {
59 if pathSegments[x] == "" { // skip empty segments
60 continue
61 }
62
63 var rgx *regexp.Regexp
64
65 if v.options.RegexCache != nil {
66 if cachedRegex, found := v.options.RegexCache.Load(pathSegments[x]); found {
67 rgx = cachedRegex.(*regexp.Regexp)
68 }
69 }
70
71 if rgx == nil {
72
73 r, err := helpers.GetRegexForPath(pathSegments[x])
74 if err != nil {
75 continue
76 }
77
78 rgx = r
79
80 if v.options.RegexCache != nil {
81 v.options.RegexCache.Store(pathSegments[x], r)
82 }
83 }
84
85 matches := rgx.FindStringSubmatch(submittedSegments[x])
86 matches = matches[1:]
87
88 // Check if it is well-formed.
89 idxs, errBraces := helpers.BraceIndices(pathSegments[x])
90 if errBraces != nil {
91 continue
92 }
93
94 idx := 0
95
96 for _, match := range matches {
97
98 isMatrix := false
99 isLabel := false
100 // isExplode := false
101 isSimple := true
102 paramTemplate := pathSegments[x][idxs[idx]+1 : idxs[idx+1]-1]
103 idx += 2 // move to the next brace pair
104 paramName := paramTemplate
105
106 // check for an asterisk on the end of the parameter (explode)
107 if strings.HasSuffix(paramTemplate, helpers.Asterisk) {
108 // isExplode = true
109 paramName = paramTemplate[:len(paramTemplate)-1]
110 }
111 if strings.HasPrefix(paramTemplate, helpers.Period) {
112 isLabel = true
113 isSimple = false
114 paramName = paramName[1:]
115 }
116 if strings.HasPrefix(paramTemplate, helpers.SemiColon) {
117 isMatrix = true
118 isSimple = false
119 paramName = paramName[1:]
120 }
121
122 // does this param name match the current path segment param name
123 if paramName != p.Name {
124 continue
125 }
126
127 paramValue := match
128
129 // URL decode the parameter value before validation
130 decodedParamValue, _ := url.PathUnescape(paramValue)
131
132 if decodedParamValue == "" {
133 // Mandatory path parameter cannot be empty
134 if p.Required != nil && *p.Required {
135 validationErrors = append(validationErrors, errors.PathParameterMissing(p, pathValue, request.URL.Path))
136 break
137 }
138 continue
139 }
140
141 // extract the schema from the parameter
142 sch := p.Schema.Schema()
143
144 // Get rendered schema for ReferenceSchema field in errors (uses cache if available)
145 renderedSchema := GetRenderedSchema(sch, v.options)
146
147 // check enum (if present)
148 enumCheck := func(decodedValue string) {
149 matchFound := false
150 for _, enumVal := range sch.Enum {
151 if strings.TrimSpace(decodedValue) == fmt.Sprint(enumVal.Value) {
152 matchFound = true
153 break
154 }
155 }
156 if !matchFound {
157 validationErrors = append(validationErrors,
158 errors.IncorrectPathParamEnum(p, strings.ToLower(decodedValue), sch, pathValue, renderedSchema))
159 }
160 }
161
162 // for each type, check the value.
163 if sch != nil && sch.Type != nil {
164 for typ := range sch.Type {
165 switch sch.Type[typ] {
166 case helpers.String:
167
168 // TODO: label and matrix style validation
169
170 // check if the param is within the enum
171 if sch.Enum != nil {
172 enumCheck(decodedParamValue)
173 break
174 }
175 validationErrors = append(validationErrors,
176 ValidateSingleParameterSchema(
177 sch,
178 decodedParamValue,
179 "Path parameter",
180 "The path parameter",
181 p.Name,
182 helpers.ParameterValidation,
183 helpers.ParameterValidationPath,
184 v.options,
185 pathValue,
186 operation,
187 )...)
188
189 case helpers.Integer:
190 // simple use case is already handled in find param.
191 rawParamValue, paramValueParsed, err := v.resolveInteger(sch, p, isLabel, isMatrix, decodedParamValue, pathValue, renderedSchema)
192 if err != nil {
193 validationErrors = append(validationErrors, err...)
194 break
195 }
196 // check if the param is within the enum
197 if sch.Enum != nil {
198 enumCheck(rawParamValue)
199 break
200 }
201 validationErrors = append(validationErrors, ValidateSingleParameterSchema(
202 sch,
203 paramValueParsed,
204 "Path parameter",
205 "The path parameter",
206 p.Name,
207 helpers.ParameterValidation,
208 helpers.ParameterValidationPath,
209 v.options,
210 pathValue,
211 operation,
212 )...)
213
214 case helpers.Number:
215 // simple use case is already handled in find param.
216 rawParamValue, paramValueParsed, err := v.resolveNumber(sch, p, isLabel, isMatrix, decodedParamValue, pathValue, renderedSchema)
217 if err != nil {
218 validationErrors = append(validationErrors, err...)
219 break
220 }
221 // check if the param is within the enum
222 if sch.Enum != nil {
223 enumCheck(rawParamValue)
224 break
225 }
226 validationErrors = append(validationErrors, ValidateSingleParameterSchema(
227 sch,
228 paramValueParsed,
229 "Path parameter",
230 "The path parameter",
231 p.Name,
232 helpers.ParameterValidation,
233 helpers.ParameterValidationPath,
234 v.options,
235 pathValue,
236 operation,
237 )...)
238
239 case helpers.Boolean:
240 if isLabel && p.Style == helpers.LabelStyle {
241 if _, err := strconv.ParseBool(decodedParamValue[1:]); err != nil {
242 validationErrors = append(validationErrors,
243 errors.IncorrectPathParamBool(p, decodedParamValue[1:], sch, pathValue, renderedSchema))
244 }
245 }
246 if isSimple {
247 if _, err := strconv.ParseBool(decodedParamValue); err != nil {
248 validationErrors = append(validationErrors,
249 errors.IncorrectPathParamBool(p, decodedParamValue, sch, pathValue, renderedSchema))
250 }
251 }
252 if isMatrix && p.Style == helpers.MatrixStyle {
253 // strip off the colon and the parameter name
254 decodedForMatrix := strings.Replace(decodedParamValue[1:], fmt.Sprintf("%s=", p.Name), "", 1)
255 if _, err := strconv.ParseBool(decodedForMatrix); err != nil {
256 validationErrors = append(validationErrors,
257 errors.IncorrectPathParamBool(p, decodedForMatrix, sch, pathValue, renderedSchema))
258 }
259 }
260 case helpers.Object:
261 var encodedObject interface{}
262
263 if p.IsDefaultPathEncoding() {
264 encodedObject = helpers.ConstructMapFromCSVWithSchema(decodedParamValue, sch)
265 } else {
266 switch p.Style {
267 case helpers.LabelStyle:
268 if !p.IsExploded() {
269 encodedObject = helpers.ConstructMapFromCSVWithSchema(decodedParamValue[1:], sch)
270 } else {
271 encodedObject = helpers.ConstructKVFromLabelEncodingWithSchema(decodedParamValue, sch)
272 }
273 case helpers.MatrixStyle:
274 if !p.IsExploded() {
275 decodedForMatrix := strings.Replace(decodedParamValue[1:], fmt.Sprintf("%s=", p.Name), "", 1)
276 encodedObject = helpers.ConstructMapFromCSVWithSchema(decodedForMatrix, sch)
277 } else {
278 decodedForMatrix := strings.Replace(decodedParamValue[1:], fmt.Sprintf("%s=", p.Name), "", 1)
279 encodedObject = helpers.ConstructKVFromMatrixCSVWithSchema(decodedForMatrix, sch)
280 }
281 default:
282 if p.IsExploded() {
283 encodedObject = helpers.ConstructKVFromCSVWithSchema(decodedParamValue, sch)
284 }
285 }
286 }
287 // if a schema was extracted
288 if sch != nil {
289 validationErrors = append(validationErrors,
290 ValidateParameterSchema(sch,
291 encodedObject,
292 "",
293 "Path parameter",
294 "The path parameter",
295 p.Name,
296 helpers.ParameterValidation,
297 helpers.ParameterValidationPath, v.options)...)
298 }
299
300 case helpers.Array:
301
302 // extract the items schema in order to validate the array items.
303 if sch.Items != nil && sch.Items.IsA() {
304 iSch := sch.Items.A.Schema()
305
306 // Get rendered items schema for ReferenceSchema field in errors (uses cache if available)
307 renderedItemsSchema := GetRenderedSchema(iSch, v.options)
308
309 for n := range iSch.Type {
310 // determine how to explode the array
311 var arrayValues []string
312 if isSimple {
313 arrayValues = strings.Split(decodedParamValue, helpers.Comma)
314 }
315 if isLabel {
316 if !p.IsExploded() {
317 arrayValues = strings.Split(decodedParamValue[1:], helpers.Comma)
318 } else {
319 arrayValues = strings.Split(decodedParamValue[1:], helpers.Period)
320 }
321 }
322 if isMatrix {
323 if !p.IsExploded() {
324 decodedForMatrix := strings.Replace(decodedParamValue[1:], fmt.Sprintf("%s=", p.Name), "", 1)
325 arrayValues = strings.Split(decodedForMatrix, helpers.Comma)
326 } else {
327 decodedForMatrix := strings.ReplaceAll(decodedParamValue[1:], fmt.Sprintf("%s=", p.Name), "")
328 arrayValues = strings.Split(decodedForMatrix, helpers.SemiColon)
329 }
330 }
331 switch iSch.Type[n] {
332 case helpers.Integer:
333 for pv := range arrayValues {
334 if _, err := strconv.ParseInt(arrayValues[pv], 10, 64); err != nil {
335 validationErrors = append(validationErrors,
336 errors.IncorrectPathParamArrayInteger(p, arrayValues[pv], sch, iSch, pathValue, renderedItemsSchema))
337 }
338 }
339 case helpers.Number:
340 for pv := range arrayValues {
341 if _, err := strconv.ParseFloat(arrayValues[pv], 64); err != nil {
342 validationErrors = append(validationErrors,
343 errors.IncorrectPathParamArrayNumber(p, arrayValues[pv], sch, iSch, pathValue, renderedItemsSchema))
344 }
345 }
346 case helpers.Boolean:
347 for pv := range arrayValues {
348 bc := len(validationErrors)
349 if _, err := strconv.ParseBool(arrayValues[pv]); err != nil {
350 validationErrors = append(validationErrors,
351 errors.IncorrectPathParamArrayBoolean(p, arrayValues[pv], sch, iSch, pathValue, renderedItemsSchema))
352 continue
353 }
354 if len(validationErrors) == bc {
355 // ParseBool will parse 0 or 1 as false/true to we
356 // need to catch this edge case.
357 if arrayValues[pv] == "0" || arrayValues[pv] == "1" {
358 validationErrors = append(validationErrors,
359 errors.IncorrectPathParamArrayBoolean(p, arrayValues[pv], sch, iSch, pathValue, renderedItemsSchema))
360 continue
361 }
362 }
363 }
364 }
365 }
366 }
367 }
368 }
369 }
370 }
371 }
372 }
373 }
374
375 errors.PopulateValidationErrors(validationErrors, request, pathValue)
376
377 if len(validationErrors) > 0 {
378 return false, validationErrors
379 }
380 return true, nil
381 }
382
383 func (v *paramValidator) resolveNumber(sch *base.Schema, p *v3.Parameter, isLabel bool, isMatrix bool, paramValue string, pathValue string, renderedSchema string) (string, float64, []*errors.ValidationError) {
384 if isLabel && p.Style == helpers.LabelStyle {
385 paramValueParsed, err := strconv.ParseFloat(paramValue[1:], 64)
386 if err != nil {
387 return "", 0, []*errors.ValidationError{errors.IncorrectPathParamNumber(p, paramValue[1:], sch, pathValue, renderedSchema)}
388 }
389 return paramValue[1:], paramValueParsed, nil
390 }
391 if isMatrix && p.Style == helpers.MatrixStyle {
392 // strip off the colon and the parameter name
393 paramValue = strings.Replace(paramValue[1:], fmt.Sprintf("%s=", p.Name), "", 1)
394 paramValueParsed, err := strconv.ParseFloat(paramValue, 64)
395 if err != nil {
396 return "", 0, []*errors.ValidationError{errors.IncorrectPathParamNumber(p, paramValue[1:], sch, pathValue, renderedSchema)}
397 }
398 return paramValue, paramValueParsed, nil
399 }
400 paramValueParsed, err := strconv.ParseFloat(paramValue, 64)
401 if err != nil {
402 return "", 0, []*errors.ValidationError{errors.IncorrectPathParamNumber(p, paramValue, sch, pathValue, renderedSchema)}
403 }
404 return paramValue, paramValueParsed, nil
405 }
406
407 func (v *paramValidator) resolveInteger(sch *base.Schema, p *v3.Parameter, isLabel bool, isMatrix bool, paramValue string, pathValue string, renderedSchema string) (string, int64, []*errors.ValidationError) {
408 if isLabel && p.Style == helpers.LabelStyle {
409 paramValueParsed, err := strconv.ParseInt(paramValue[1:], 10, 64)
410 if err != nil {
411 return "", 0, []*errors.ValidationError{errors.IncorrectPathParamInteger(p, paramValue[1:], sch, pathValue, renderedSchema)}
412 }
413 return paramValue[1:], paramValueParsed, nil
414 }
415 if isMatrix && p.Style == helpers.MatrixStyle {
416 // strip off the colon and the parameter name
417 paramValue = strings.Replace(paramValue[1:], fmt.Sprintf("%s=", p.Name), "", 1)
418 paramValueParsed, err := strconv.ParseInt(paramValue, 10, 64)
419 if err != nil {
420 return "", 0, []*errors.ValidationError{errors.IncorrectPathParamInteger(p, paramValue[1:], sch, pathValue, renderedSchema)}
421 }
422 return paramValue, paramValueParsed, nil
423 }
424 paramValueParsed, err := strconv.ParseInt(paramValue, 10, 64)
425 if err != nil {
426 return "", 0, []*errors.ValidationError{errors.IncorrectPathParamInteger(p, paramValue, sch, pathValue, renderedSchema)}
427 }
428 return paramValue, paramValueParsed, nil
429 }