Debian Codegraph @

parameters/validation_functions.go

raw
1 // Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package parameters
5
6 import (
7 "encoding/json"
8 "fmt"
9 "strconv"
10 "strings"
11
12 "github.com/pb33f/libopenapi/datamodel/high/base"
13 v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
14
15 "github.com/pb33f/libopenapi-validator/config"
16 "github.com/pb33f/libopenapi-validator/errors"
17 "github.com/pb33f/libopenapi-validator/helpers"
18 )
19
20 // ValidateCookieArray will validate a cookie parameter that is an array
21 func ValidateCookieArray(
22 sch *base.Schema, param *v3.Parameter, value string, pathTemplate string, operation string, renderedSchema string,
23 ) []*errors.ValidationError {
24 var validationErrors []*errors.ValidationError
25 itemsSchema := sch.Items.A.Schema()
26
27 var renderedItemsSchema string
28 if itemsSchema != nil {
29 rendered, _ := itemsSchema.RenderInline()
30 schemaBytes, _ := json.Marshal(rendered)
31 renderedItemsSchema = string(schemaBytes)
32 }
33
34 // header arrays can only be encoded as CSV
35 items := helpers.ExplodeQueryValue(value, helpers.DefaultDelimited)
36
37 // now check each item in the array
38 for _, item := range items {
39 // for each type defined in the item's schema, check the item
40 for _, itemType := range itemsSchema.Type {
41 switch itemType {
42 case helpers.Integer, helpers.Number:
43 if _, err := strconv.ParseFloat(item, 64); err != nil {
44 validationErrors = append(validationErrors,
45 errors.IncorrectCookieParamArrayNumber(param, item, sch, itemsSchema, pathTemplate, operation, renderedItemsSchema))
46 }
47 case helpers.Boolean:
48 if _, err := strconv.ParseBool(item); err != nil {
49 validationErrors = append(validationErrors,
50 errors.IncorrectCookieParamArrayBoolean(param, item, sch, itemsSchema, pathTemplate, operation, renderedItemsSchema))
51 break
52 }
53 // check for edge-cases "0" and "1" which can also be parsed into valid booleans
54 if item == "0" || item == "1" {
55 validationErrors = append(validationErrors,
56 errors.IncorrectCookieParamArrayBoolean(param, item, sch, itemsSchema, pathTemplate, operation, renderedItemsSchema))
57 }
58 case helpers.String:
59 // do nothing for now.
60 continue
61 }
62 }
63 }
64 return validationErrors
65 }
66
67 // ValidateHeaderArray will validate a header parameter that is an array
68 func ValidateHeaderArray(
69 sch *base.Schema, param *v3.Parameter, value string, pathTemplate string, operation string, renderedSchema string,
70 ) []*errors.ValidationError {
71 var validationErrors []*errors.ValidationError
72 itemsSchema := sch.Items.A.Schema()
73
74 var renderedItemsSchema string
75 if itemsSchema != nil {
76 rendered, _ := itemsSchema.RenderInline()
77 schemaBytes, _ := json.Marshal(rendered)
78 renderedItemsSchema = string(schemaBytes)
79 }
80
81 // header arrays can only be encoded as CSV
82 items := helpers.ExplodeQueryValue(value, helpers.DefaultDelimited)
83
84 // now check each item in the array
85 for _, item := range items {
86 // for each type defined in the item's schema, check the item
87 for _, itemType := range itemsSchema.Type {
88 switch itemType {
89 case helpers.Integer, helpers.Number:
90 if _, err := strconv.ParseFloat(item, 64); err != nil {
91 validationErrors = append(validationErrors,
92 errors.IncorrectHeaderParamArrayNumber(param, item, sch, itemsSchema, pathTemplate, operation, renderedItemsSchema))
93 }
94 case helpers.Boolean:
95 if _, err := strconv.ParseBool(item); err != nil {
96 validationErrors = append(validationErrors,
97 errors.IncorrectHeaderParamArrayBoolean(param, item, sch, itemsSchema, pathTemplate, operation, renderedItemsSchema))
98 break
99 }
100 // check for edge-cases "0" and "1" which can also be parsed into valid booleans
101 if item == "0" || item == "1" {
102 validationErrors = append(validationErrors,
103 errors.IncorrectHeaderParamArrayBoolean(param, item, sch, itemsSchema, pathTemplate, operation, renderedItemsSchema))
104 }
105 case helpers.String:
106 // do nothing for now.
107 continue
108 }
109 }
110 }
111 return validationErrors
112 }
113
114 // ValidateQueryArray will validate a query parameter that is an array
115 func ValidateQueryArray(
116 sch *base.Schema, param *v3.Parameter, ef string, contentWrapped bool, validationOptions *config.ValidationOptions, pathTemplate string, operation string, renderedSchema string,
117 ) []*errors.ValidationError {
118 var validationErrors []*errors.ValidationError
119 itemsSchema := sch.Items.A.Schema()
120
121 // Get rendered items schema for ReferenceSchema field in errors (uses cache if available)
122 renderedItemsSchema := GetRenderedSchema(itemsSchema, validationOptions)
123
124 // check for an exploded bit on the schema.
125 // if it's exploded, then we need to check each item in the array
126 // if it's not exploded, then we need to check the whole array as a string
127 var items []string
128 if param.IsExploded() {
129 items = helpers.ExplodeQueryValue(ef, param.Style)
130 } else {
131 // check for a style of form (or no style) and if so, explode the value
132 if param.Style == "" || param.Style == helpers.Form {
133 if !contentWrapped {
134 items = helpers.ExplodeQueryValue(ef, param.Style)
135 } else {
136 items = []string{ef}
137 }
138 } else {
139 switch param.Style {
140 case helpers.PipeDelimited, helpers.SpaceDelimited:
141 items = helpers.ExplodeQueryValue(ef, param.Style)
142 }
143 }
144 }
145
146 // check if the param is within an enum
147 checkEnum := func(item string) {
148 // check if the array param is within an enum
149 if sch.Items.IsA() {
150 itemsSch := sch.Items.A.Schema()
151 if itemsSch.Enum != nil {
152 matchFound := false
153 for _, enumVal := range itemsSch.Enum {
154 if strings.TrimSpace(item) == fmt.Sprint(enumVal.Value) {
155 matchFound = true
156 break
157 }
158 }
159 if !matchFound {
160 validationErrors = append(validationErrors,
161 errors.IncorrectQueryParamEnumArray(param, item, sch, pathTemplate, operation, renderedItemsSchema))
162 }
163 }
164 }
165 }
166
167 // now check each item in the array
168 seen := make(map[string]struct{})
169 uniqueItems := true
170 var duplicates []string
171 for _, item := range items {
172
173 if _, exists := seen[item]; exists {
174 uniqueItems = false
175 duplicates = append(duplicates, item)
176 }
177 seen[item] = struct{}{}
178
179 // for each type defined in the item's schema, check the item
180 for _, itemType := range itemsSchema.Type {
181 switch itemType {
182 case helpers.Integer:
183 if _, err := strconv.ParseInt(item, 10, 64); err != nil {
184 validationErrors = append(validationErrors,
185 errors.IncorrectQueryParamArrayInteger(param, item, sch, itemsSchema, pathTemplate, operation, renderedItemsSchema))
186 break
187 }
188 // will it blend?
189 checkEnum(item)
190 case helpers.Number:
191 if _, err := strconv.ParseFloat(item, 64); err != nil {
192 validationErrors = append(validationErrors,
193 errors.IncorrectQueryParamArrayNumber(param, item, sch, itemsSchema, pathTemplate, operation, renderedItemsSchema))
194 break
195 }
196 // will it blend?
197 checkEnum(item)
198
199 case helpers.Boolean:
200 if _, err := strconv.ParseBool(item); err != nil {
201 validationErrors = append(validationErrors,
202 errors.IncorrectQueryParamArrayBoolean(param, item, sch, itemsSchema, pathTemplate, operation, renderedItemsSchema))
203 }
204 case helpers.Object:
205 validationErrors = append(validationErrors,
206 ValidateParameterSchema(itemsSchema,
207 nil,
208 item,
209 "Query array parameter",
210 "The query parameter (which is an array)",
211 param.Name,
212 helpers.ParameterValidation,
213 helpers.ParameterValidationQuery, validationOptions)...)
214
215 case helpers.String:
216
217 // will it float?
218 checkEnum(item)
219 }
220 }
221 }
222
223 // check for min and max items
224 if sch.MaxItems != nil {
225 if len(items) > int(*sch.MaxItems) {
226 validationErrors = append(validationErrors,
227 errors.IncorrectParamArrayMaxNumItems(param, sch, *sch.MaxItems, int64(len(items)), pathTemplate, operation, renderedSchema))
228 }
229 }
230
231 if sch.MinItems != nil {
232 if len(items) < int(*sch.MinItems) {
233 validationErrors = append(validationErrors,
234 errors.IncorrectParamArrayMinNumItems(param, sch, *sch.MinItems, int64(len(items)), pathTemplate, operation, renderedSchema))
235 }
236 }
237
238 // check for unique items
239 if sch.UniqueItems != nil {
240 if *sch.UniqueItems && !uniqueItems {
241 validationErrors = append(validationErrors,
242 errors.IncorrectParamArrayUniqueItems(param, sch, strings.Join(duplicates, ", "), pathTemplate, operation, renderedSchema))
243 }
244 }
245 return validationErrors
246 }
247
248 // ValidateQueryParamStyle will validate a query parameter by style
249 func ValidateQueryParamStyle(param *v3.Parameter, as []*helpers.QueryParam) []*errors.ValidationError {
250 var validationErrors []*errors.ValidationError
251 if param.Style == helpers.DeepObject {
252 if prefixParam, nestedParam, ok := helpers.DeepObjectPathConflict(as); ok {
253 return []*errors.ValidationError{errors.InvalidDeepObjectPathConflict(param, prefixParam, nestedParam)}
254 }
255 }
256 stopValidation:
257 for _, qp := range as {
258 for i := range qp.Values {
259 switch param.Style {
260 case helpers.DeepObject:
261 // check if the object has additional properties defined that treat this as an array
262 if param.Schema != nil && helpers.DeepObjectAllowsMultipleValues(param.Schema.Schema(), qp) {
263 continue
264 }
265 if len(qp.Values) > 1 {
266 validationErrors = append(validationErrors, errors.InvalidDeepObject(param, qp))
267 break stopValidation
268 }
269
270 case helpers.PipeDelimited:
271 // check if explode is false, but we have used an array style
272 if !param.IsExploded() {
273 if len(qp.Values) > 1 {
274 validationErrors = append(validationErrors, errors.IncorrectPipeDelimiting(param, qp))
275 break stopValidation
276 }
277 }
278 case helpers.SpaceDelimited:
279 // check if explode is false, but we have used an array style
280 if !param.IsExploded() {
281 if len(qp.Values) > 1 {
282 validationErrors = append(validationErrors, errors.IncorrectSpaceDelimiting(param, qp))
283 break stopValidation
284 }
285 }
286 default:
287 // check for a delimited list.
288 if helpers.DoesFormParamContainDelimiter(qp.Values[i], param.Style) {
289 if param.Explode != nil && *param.Explode {
290 validationErrors = append(validationErrors, errors.IncorrectFormEncoding(param, qp, i))
291 break stopValidation
292 }
293 }
294 }
295 }
296 }
297 return validationErrors // defaults to true if no style is set.
298 }