Debian Codegraph @

parameters/header_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 "strconv"
10 "strings"
11
12 "github.com/pb33f/libopenapi/datamodel/high/base"
13
14 v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
15 lowbase "github.com/pb33f/libopenapi/datamodel/low/base"
16
17 "github.com/pb33f/libopenapi-validator/errors"
18 "github.com/pb33f/libopenapi-validator/helpers"
19 "github.com/pb33f/libopenapi-validator/paths"
20 "github.com/pb33f/libopenapi-validator/strict"
21 )
22
23 func (v *paramValidator) ValidateHeaderParams(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.ValidateHeaderParamsWithPathItem(request, pathItem, foundPath)
29 }
30
31 func (v *paramValidator) ValidateHeaderParamsWithPathItem(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 // extract params for the operation
46 params := helpers.ExtractParamsForOperation(request, pathItem)
47
48 var validationErrors []*errors.ValidationError
49 seenHeaders := make(map[string]bool)
50 operation := strings.ToLower(request.Method)
51 for _, p := range params {
52 if p.In == helpers.Header {
53
54 seenHeaders[strings.ToLower(p.Name)] = true
55 if param := request.Header.Get(p.Name); param != "" {
56
57 var sch *base.Schema
58 if p.Schema != nil {
59 sch = p.Schema.Schema()
60 }
61
62 // Get rendered schema for ReferenceSchema field in errors (uses cache if available)
63 renderedSchema := GetRenderedSchema(sch, v.options)
64
65 pType := sch.Type
66
67 for _, ty := range pType {
68 switch ty {
69 case helpers.Integer:
70 if _, err := strconv.ParseInt(param, 10, 64); err != nil {
71 validationErrors = append(validationErrors,
72 errors.InvalidHeaderParamInteger(p, strings.ToLower(param), sch, pathValue, operation, renderedSchema))
73 break
74 }
75 // check if the param is within the enum
76 if sch.Enum != nil {
77 matchFound := false
78 for _, enumVal := range sch.Enum {
79 if strings.TrimSpace(param) == fmt.Sprint(enumVal.Value) {
80 matchFound = true
81 break
82 }
83 }
84 if !matchFound {
85 validationErrors = append(validationErrors,
86 errors.IncorrectHeaderParamEnum(p, strings.ToLower(param), sch, pathValue, operation, renderedSchema))
87 }
88 }
89
90 case helpers.Number:
91 if _, err := strconv.ParseFloat(param, 64); err != nil {
92 validationErrors = append(validationErrors,
93 errors.InvalidHeaderParamNumber(p, strings.ToLower(param), sch, pathValue, operation, renderedSchema))
94 break
95 }
96 // check if the param is within the enum
97 if sch.Enum != nil {
98 matchFound := false
99 for _, enumVal := range sch.Enum {
100 if strings.TrimSpace(param) == fmt.Sprint(enumVal.Value) {
101 matchFound = true
102 break
103 }
104 }
105 if !matchFound {
106 validationErrors = append(validationErrors,
107 errors.IncorrectHeaderParamEnum(p, strings.ToLower(param), sch, pathValue, operation, renderedSchema))
108 }
109 }
110
111 case helpers.Boolean:
112 if _, err := strconv.ParseBool(param); err != nil {
113 validationErrors = append(validationErrors,
114 errors.IncorrectHeaderParamBool(p, strings.ToLower(param), sch, pathValue, operation, renderedSchema))
115 }
116
117 case helpers.Object:
118
119 // check if the header is default encoded or not
120 var encodedObj map[string]interface{}
121 // we have found our header, check the explode type.
122 if p.IsDefaultHeaderEncoding() {
123 encodedObj = helpers.ConstructMapFromCSVWithSchema(param, sch)
124 } else {
125 if p.IsExploded() { // only option is to be exploded for KV extraction.
126 encodedObj = helpers.ConstructKVFromCSVWithSchema(param, sch)
127 }
128 }
129
130 if len(encodedObj) == 0 {
131 validationErrors = append(validationErrors,
132 errors.HeaderParameterCannotBeDecoded(p, strings.ToLower(param), pathValue, operation, renderedSchema))
133 break
134 }
135
136 // if a schema was extracted
137 if sch != nil {
138 validationErrors = append(validationErrors,
139 ValidateParameterSchema(sch,
140 encodedObj,
141 "",
142 "Header parameter",
143 "The header parameter",
144 p.Name,
145 helpers.ParameterValidation,
146 helpers.ParameterValidationQuery, v.options)...)
147 }
148
149 case helpers.Array:
150 if !p.IsExploded() { // only unexploded arrays are supported for cookie params
151 if sch.Items.IsA() {
152 validationErrors = append(validationErrors,
153 ValidateHeaderArray(sch, p, param, pathValue, operation, renderedSchema)...)
154 }
155 }
156
157 case helpers.String:
158
159 // check if the schema has an enum, and if so, match the value against one of
160 // the defined enum values.
161 if sch.Enum != nil {
162 matchFound := false
163 for _, enumVal := range sch.Enum {
164 if strings.TrimSpace(param) == fmt.Sprint(enumVal.Value) {
165 matchFound = true
166 break
167 }
168 }
169 if !matchFound {
170 validationErrors = append(validationErrors,
171 errors.IncorrectHeaderParamEnum(p, strings.ToLower(param), sch, pathValue, operation, renderedSchema))
172 break
173 }
174 }
175 validationErrors = append(validationErrors,
176 ValidateSingleParameterSchema(
177 sch,
178 param,
179 "Header parameter",
180 "The header parameter",
181 p.Name,
182 helpers.ParameterValidation,
183 helpers.ParameterValidationHeader,
184 v.options,
185 pathValue,
186 operation,
187 )...)
188 }
189 }
190 if len(pType) == 0 {
191 // validate schema as there is no type information.
192 validationErrors = append(validationErrors, ValidateSingleParameterSchema(sch,
193 param,
194 p.Name,
195 lowbase.SchemaLabel, p.Name, helpers.ParameterValidation, helpers.ParameterValidationHeader, v.options,
196 pathValue,
197 operation)...)
198 }
199 } else {
200 if p.Required != nil && *p.Required {
201 // Get rendered schema for missing required parameter (uses cache if available)
202 var renderedSchema string
203 if p.Schema != nil {
204 renderedSchema = GetRenderedSchema(p.Schema.Schema(), v.options)
205 }
206 validationErrors = append(validationErrors, errors.HeaderParameterMissing(p, pathValue, operation, renderedSchema))
207 }
208 }
209 }
210 }
211
212 errors.PopulateValidationErrors(validationErrors, request, pathValue)
213
214 if len(validationErrors) > 0 {
215 return false, validationErrors
216 }
217
218 // strict mode: check for undeclared headers
219 if v.options.StrictMode {
220 // Extract security headers applicable to this operation
221 var securityHeaders []string
222 if v.document.Components != nil && v.document.Components.SecuritySchemes != nil {
223 security := helpers.EffectiveSecurityForOperation(request, pathItem, v.document.Security)
224 // Convert orderedmap to regular map for the helper
225 schemesMap := make(map[string]*v3.SecurityScheme)
226 for pair := v.document.Components.SecuritySchemes.First(); pair != nil; pair = pair.Next() {
227 schemesMap[pair.Key()] = pair.Value()
228 }
229 securityHeaders = helpers.ExtractSecurityHeaderNames(security, schemesMap)
230 }
231
232 undeclaredHeaders := strict.ValidateRequestHeaders(request.Header, params, securityHeaders, v.options)
233 for _, undeclared := range undeclaredHeaders {
234 validationErrors = append(validationErrors,
235 errors.UndeclaredHeaderError(
236 undeclared.Name,
237 undeclared.Value.(string),
238 undeclared.DeclaredProperties,
239 undeclared.Direction.String(),
240 request.URL.Path,
241 request.Method,
242 ))
243 }
244 }
245
246 if len(validationErrors) > 0 {
247 return false, validationErrors
248 }
249 return true, nil
250 }