| 1 |
// Copyright 2023-2025 Princess Beef Heavy Industries, LLC / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
package parameters |
| 5 |
|
| 6 |
import ( |
| 7 |
"encoding/json" |
| 8 |
"fmt" |
| 9 |
"net/http" |
| 10 |
"regexp" |
| 11 |
"strconv" |
| 12 |
"strings" |
| 13 |
|
| 14 |
"github.com/pb33f/libopenapi/datamodel/high/base" |
| 15 |
"github.com/pb33f/libopenapi/orderedmap" |
| 16 |
|
| 17 |
v3 "github.com/pb33f/libopenapi/datamodel/high/v3" |
| 18 |
|
| 19 |
"github.com/pb33f/libopenapi-validator/errors" |
| 20 |
"github.com/pb33f/libopenapi-validator/helpers" |
| 21 |
"github.com/pb33f/libopenapi-validator/paths" |
| 22 |
"github.com/pb33f/libopenapi-validator/strict" |
| 23 |
) |
| 24 |
|
| 25 |
const rx = `[:\/\?#\[\]\@!\$&'\(\)\*\+,;=]` |
| 26 |
|
| 27 |
var rxRxp = regexp.MustCompile(rx) |
| 28 |
|
| 29 |
func (v *paramValidator) ValidateQueryParams(request *http.Request) (bool, []*errors.ValidationError) { |
| 30 |
pathItem, errs, foundPath := paths.FindPath(request, v.document, v.options) |
| 31 |
if len(errs) > 0 { |
| 32 |
return false, errs |
| 33 |
} |
| 34 |
return v.ValidateQueryParamsWithPathItem(request, pathItem, foundPath) |
| 35 |
} |
| 36 |
|
| 37 |
func (v *paramValidator) ValidateQueryParamsWithPathItem(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError) { |
| 38 |
if pathItem == nil { |
| 39 |
return false, []*errors.ValidationError{{ |
| 40 |
ValidationType: helpers.PathValidation, |
| 41 |
ValidationSubType: helpers.ValidationMissing, |
| 42 |
Message: fmt.Sprintf("%s Path '%s' not found", request.Method, request.URL.Path), |
| 43 |
Reason: fmt.Sprintf("The %s request contains a path of '%s' "+ |
| 44 |
"however that path, or the %s method for that path does not exist in the specification", |
| 45 |
request.Method, request.URL.Path, request.Method), |
| 46 |
SpecLine: -1, |
| 47 |
SpecCol: -1, |
| 48 |
HowToFix: errors.HowToFixPath, |
| 49 |
}} |
| 50 |
} |
| 51 |
// extract params for the operation |
| 52 |
params := helpers.ExtractParamsForOperation(request, pathItem) |
| 53 |
queryParams := make(map[string][]*helpers.QueryParam) |
| 54 |
var validationErrors []*errors.ValidationError |
| 55 |
|
| 56 |
// build a set of spec parameter names for exact matching |
| 57 |
specParamNames := make(map[string]bool) |
| 58 |
for _, p := range params { |
| 59 |
if p.In == helpers.Query { |
| 60 |
specParamNames[p.Name] = true |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
for qKey, qVal := range request.URL.Query() { |
| 65 |
// check if the query key exactly matches a spec parameter name (e.g., "match[]") |
| 66 |
// if so, store it literally without deepObject stripping |
| 67 |
if specParamNames[qKey] { |
| 68 |
queryParams[qKey] = append(queryParams[qKey], &helpers.QueryParam{ |
| 69 |
Key: qKey, |
| 70 |
Values: qVal, |
| 71 |
}) |
| 72 |
} else if stripped, propertyPath, ok := helpers.ParseDeepObjectKey(qKey); ok { |
| 73 |
// check if the param is encoded as a property / deepObject |
| 74 |
queryParams[stripped] = append(queryParams[stripped], &helpers.QueryParam{ |
| 75 |
Key: stripped, |
| 76 |
Values: qVal, |
| 77 |
Property: propertyPath[0], |
| 78 |
PropertyPath: propertyPath, |
| 79 |
}) |
| 80 |
} else { |
| 81 |
queryParams[qKey] = append(queryParams[qKey], &helpers.QueryParam{ |
| 82 |
Key: qKey, |
| 83 |
Values: qVal, |
| 84 |
}) |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
// Get operation from request method (lowercase for JSON Pointer) |
| 89 |
operation := strings.ToLower(request.Method) |
| 90 |
|
| 91 |
// look through the params for the query key |
| 92 |
doneLooking: |
| 93 |
for p := range params { |
| 94 |
if params[p].In == helpers.Query { |
| 95 |
|
| 96 |
contentWrapped := false |
| 97 |
var contentType string |
| 98 |
// check if this param is found as a set of query strings |
| 99 |
if jk, ok := queryParams[params[p].Name]; ok { |
| 100 |
skipValues: |
| 101 |
for _, fp := range jk { |
| 102 |
// let's check styles first. |
| 103 |
validationErrors = append(validationErrors, ValidateQueryParamStyle(params[p], jk)...) |
| 104 |
|
| 105 |
// there is a match, is the type correct |
| 106 |
// this context is extracted from the 3.1 spec to explain what is going on here: |
| 107 |
// For more complex scenarios, the content property can define the media type and schema of the |
| 108 |
// parameter. A parameter MUST contain either a schema property, or a content property, but not both. |
| 109 |
// The map MUST only contain one entry. (for content) |
| 110 |
var sch *base.Schema |
| 111 |
if params[p].Schema != nil { |
| 112 |
sch = params[p].Schema.Schema() |
| 113 |
} else { |
| 114 |
// ok, no schema, check for a content type |
| 115 |
for pair := orderedmap.First(params[p].Content); pair != nil; pair = pair.Next() { |
| 116 |
sch = pair.Value().Schema.Schema() |
| 117 |
contentWrapped = true |
| 118 |
contentType = pair.Key() |
| 119 |
break |
| 120 |
} |
| 121 |
} |
| 122 |
|
| 123 |
// Get rendered schema for ReferenceSchema field in errors (uses cache if available) |
| 124 |
renderedSchema := GetRenderedSchema(sch, v.options) |
| 125 |
|
| 126 |
pType := sch.Type |
| 127 |
|
| 128 |
// for each param, check each type |
| 129 |
for _, ef := range fp.Values { |
| 130 |
|
| 131 |
// check allowReserved values. If this is set to true, then we can allow the |
| 132 |
// following characters |
| 133 |
// :/?#[]@!$&'()*+,;= |
| 134 |
// to be present as they are, without being URLEncoded. |
| 135 |
if !params[p].AllowReserved { |
| 136 |
if rxRxp.MatchString(ef) && params[p].IsExploded() { |
| 137 |
validationErrors = append(validationErrors, |
| 138 |
errors.IncorrectReservedValues(params[p], ef, sch, pathValue, operation, renderedSchema)) |
| 139 |
} |
| 140 |
} |
| 141 |
for _, ty := range pType { |
| 142 |
switch ty { |
| 143 |
|
| 144 |
case helpers.String: |
| 145 |
validationErrors = append(validationErrors, v.validateSimpleParam(sch, ef, ef, params[p], pathValue, operation, renderedSchema)...) |
| 146 |
case helpers.Integer: |
| 147 |
efF, err := strconv.ParseInt(ef, 10, 64) |
| 148 |
if err != nil { |
| 149 |
validationErrors = append(validationErrors, |
| 150 |
errors.InvalidQueryParamInteger(params[p], ef, sch, pathValue, operation, renderedSchema)) |
| 151 |
break |
| 152 |
} |
| 153 |
validationErrors = append(validationErrors, v.validateSimpleParam(sch, ef, efF, params[p], pathValue, operation, renderedSchema)...) |
| 154 |
case helpers.Number: |
| 155 |
efF, err := strconv.ParseFloat(ef, 64) |
| 156 |
if err != nil { |
| 157 |
validationErrors = append(validationErrors, |
| 158 |
errors.InvalidQueryParamNumber(params[p], ef, sch, pathValue, operation, renderedSchema)) |
| 159 |
break |
| 160 |
} |
| 161 |
validationErrors = append(validationErrors, v.validateSimpleParam(sch, ef, efF, params[p], pathValue, operation, renderedSchema)...) |
| 162 |
case helpers.Boolean: |
| 163 |
if _, err := strconv.ParseBool(ef); err != nil { |
| 164 |
validationErrors = append(validationErrors, |
| 165 |
errors.IncorrectQueryParamBool(params[p], ef, sch, pathValue, operation, renderedSchema)) |
| 166 |
} |
| 167 |
case helpers.Object: |
| 168 |
|
| 169 |
// check what style of encoding was used and then construct a map[string]interface{} |
| 170 |
// and pass that in as encoded JSON. |
| 171 |
var encodedObj map[string]interface{} |
| 172 |
|
| 173 |
switch params[p].Style { |
| 174 |
case helpers.DeepObject: |
| 175 |
encodedObj = helpers.ConstructParamMapFromDeepObjectEncoding(jk, sch) |
| 176 |
case helpers.PipeDelimited: |
| 177 |
encodedObj = helpers.ConstructParamMapFromPipeEncodingWithSchema(jk, sch) |
| 178 |
case helpers.SpaceDelimited: |
| 179 |
encodedObj = helpers.ConstructParamMapFromSpaceEncodingWithSchema(jk, sch) |
| 180 |
default: |
| 181 |
// form encoding is default. |
| 182 |
if contentWrapped { |
| 183 |
switch contentType { |
| 184 |
case helpers.JSONContentType: |
| 185 |
// we need to unmarshal the JSON into a map[string]interface{} |
| 186 |
encodedParams := make(map[string]interface{}) |
| 187 |
encodedObj = make(map[string]interface{}) |
| 188 |
if err := json.Unmarshal([]byte(ef), &encodedParams); err != nil { |
| 189 |
validationErrors = append(validationErrors, |
| 190 |
errors.IncorrectParamEncodingJSON(params[p], ef, sch, pathValue, operation, renderedSchema)) |
| 191 |
break skipValues |
| 192 |
} |
| 193 |
encodedObj[params[p].Name] = encodedParams |
| 194 |
} |
| 195 |
} else { |
| 196 |
encodedObj = helpers.ConstructParamMapFromFormEncodingArrayWithSchema(jk, sch) |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
numErrors := len(validationErrors) |
| 201 |
validationErrors = append(validationErrors, |
| 202 |
ValidateParameterSchema(sch, encodedObj[params[p].Name].(map[string]interface{}), |
| 203 |
ef, |
| 204 |
"Query parameter", |
| 205 |
"The query parameter", |
| 206 |
params[p].Name, |
| 207 |
helpers.ParameterValidation, |
| 208 |
helpers.ParameterValidationQuery, v.options)...) |
| 209 |
if len(validationErrors) > numErrors { |
| 210 |
// we've already added an error for this, so we can skip the rest of the values |
| 211 |
break skipValues |
| 212 |
} |
| 213 |
|
| 214 |
case helpers.Array: |
| 215 |
// well we're already in an array, so we need to check the items schema |
| 216 |
// to ensure this array items matches the type |
| 217 |
// only check if items is a schema, not a boolean |
| 218 |
if sch.Items != nil && sch.Items.IsA() { |
| 219 |
validationErrors = append(validationErrors, |
| 220 |
ValidateQueryArray(sch, params[p], ef, contentWrapped, v.options, pathValue, operation, renderedSchema)...) |
| 221 |
} |
| 222 |
} |
| 223 |
} |
| 224 |
} |
| 225 |
} |
| 226 |
} else { |
| 227 |
// if the param is not in the requests, so let's check if this param is an |
| 228 |
// object, and if we should use default encoding and explode values. |
| 229 |
if params[p].Schema != nil { |
| 230 |
sch := params[p].Schema.Schema() |
| 231 |
|
| 232 |
if len(sch.Type) > 0 && sch.Type[0] == helpers.Object && params[p].IsDefaultFormEncoding() { |
| 233 |
// if the param is an object, and we're using default encoding, then we need to |
| 234 |
// validate the schema. |
| 235 |
decoded := helpers.ConstructParamMapFromQueryParamInputWithSchema(queryParams, sch) |
| 236 |
validationErrors = append(validationErrors, |
| 237 |
ValidateParameterSchema(sch, |
| 238 |
decoded, |
| 239 |
"", |
| 240 |
"Query array parameter", |
| 241 |
"The query parameter (which is an array)", |
| 242 |
params[p].Name, |
| 243 |
helpers.ParameterValidation, |
| 244 |
helpers.ParameterValidationQuery, v.options)...) |
| 245 |
break doneLooking |
| 246 |
} |
| 247 |
} |
| 248 |
// if there is no match, check if the param is required or not. |
| 249 |
if params[p].Required != nil && *params[p].Required { |
| 250 |
// Render schema for missing parameter |
| 251 |
var sch *base.Schema |
| 252 |
if params[p].Schema != nil { |
| 253 |
sch = params[p].Schema.Schema() |
| 254 |
} else { |
| 255 |
for pair := orderedmap.First(params[p].Content); pair != nil; pair = pair.Next() { |
| 256 |
sch = pair.Value().Schema.Schema() |
| 257 |
break |
| 258 |
} |
| 259 |
} |
| 260 |
// Get rendered schema for ReferenceSchema field in errors (uses cache if available) |
| 261 |
renderedSchema := GetRenderedSchema(sch, v.options) |
| 262 |
validationErrors = append(validationErrors, errors.QueryParameterMissing(params[p], pathValue, operation, renderedSchema)) |
| 263 |
} |
| 264 |
} |
| 265 |
} |
| 266 |
} |
| 267 |
|
| 268 |
errors.PopulateValidationErrors(validationErrors, request, pathValue) |
| 269 |
|
| 270 |
if len(validationErrors) > 0 { |
| 271 |
return false, validationErrors |
| 272 |
} |
| 273 |
|
| 274 |
// strict mode: check for undeclared query parameters |
| 275 |
if v.options.StrictMode { |
| 276 |
undeclaredParams := strict.ValidateQueryParams(request, params, v.options) |
| 277 |
for _, undeclared := range undeclaredParams { |
| 278 |
validationErrors = append(validationErrors, |
| 279 |
errors.UndeclaredQueryParamError( |
| 280 |
undeclared.Path, |
| 281 |
undeclared.Name, |
| 282 |
undeclared.Value, |
| 283 |
undeclared.DeclaredProperties, |
| 284 |
request.URL.Path, |
| 285 |
request.Method, |
| 286 |
)) |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
if len(validationErrors) > 0 { |
| 291 |
return false, validationErrors |
| 292 |
} |
| 293 |
return true, nil |
| 294 |
} |
| 295 |
|
| 296 |
func (v *paramValidator) validateSimpleParam(sch *base.Schema, rawParam string, parsedParam any, parameter *v3.Parameter, pathTemplate string, operation string, renderedSchema string) (validationErrors []*errors.ValidationError) { |
| 297 |
// check if the param is within an enum |
| 298 |
if sch.Enum != nil { |
| 299 |
matchFound := false |
| 300 |
for _, enumVal := range sch.Enum { |
| 301 |
if strings.TrimSpace(rawParam) == fmt.Sprint(enumVal.Value) { |
| 302 |
matchFound = true |
| 303 |
break |
| 304 |
} |
| 305 |
} |
| 306 |
if !matchFound { |
| 307 |
return []*errors.ValidationError{errors.IncorrectQueryParamEnum(parameter, rawParam, sch, pathTemplate, operation, renderedSchema)} |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
return ValidateSingleParameterSchema( |
| 312 |
sch, |
| 313 |
parsedParam, |
| 314 |
"Query parameter", |
| 315 |
"The query parameter", |
| 316 |
parameter.Name, |
| 317 |
helpers.ParameterValidation, |
| 318 |
helpers.ParameterValidationQuery, |
| 319 |
v.options, |
| 320 |
pathTemplate, |
| 321 |
operation, |
| 322 |
) |
| 323 |
} |