Debian Codegraph @

helpers/parameter_utilities.go

raw
1 // Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package helpers
5
6 import (
7 "fmt"
8 "net/http"
9 "slices"
10 "strconv"
11 "strings"
12
13 "github.com/pb33f/libopenapi/datamodel/high/base"
14
15 v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
16 )
17
18 // QueryParam is a struct that holds the key, values and property name for a query parameter
19 // it's used for complex query types that need to be parsed and tracked differently depending
20 // on the encoding styles used.
21 type QueryParam struct {
22 Key string
23 Values []string
24 Property string
25 PropertyPath []string
26 }
27
28 // ExtractParamsForOperation will extract the parameters for the operation based on the request method.
29 // Both the path level params and the method level params will be returned.
30 func ExtractParamsForOperation(request *http.Request, item *v3.PathItem) []*v3.Parameter {
31 params := item.Parameters
32 switch request.Method {
33 case http.MethodGet:
34 if item.Get != nil {
35 params = append(params, item.Get.Parameters...)
36 }
37 case http.MethodPost:
38 if item.Post != nil {
39 params = append(params, item.Post.Parameters...)
40 }
41 case http.MethodPut:
42 if item.Put != nil {
43 params = append(params, item.Put.Parameters...)
44 }
45 case http.MethodDelete:
46 if item.Delete != nil {
47 params = append(params, item.Delete.Parameters...)
48 }
49 case http.MethodOptions:
50 if item.Options != nil {
51 params = append(params, item.Options.Parameters...)
52 }
53 case http.MethodHead:
54 if item.Head != nil {
55 params = append(params, item.Head.Parameters...)
56 }
57 case http.MethodPatch:
58 if item.Patch != nil {
59 params = append(params, item.Patch.Parameters...)
60 }
61 case http.MethodTrace:
62 if item.Trace != nil {
63 params = append(params, item.Trace.Parameters...)
64 }
65 }
66 return params
67 }
68
69 // ExtractSecurityForOperation will extract the security requirements for the operation based on the request method.
70 //
71 // Deprecated: use EffectiveSecurityForOperation instead, which also handles
72 // document-level global security inheritance per the OpenAPI specification.
73 func ExtractSecurityForOperation(request *http.Request, item *v3.PathItem) []*base.SecurityRequirement {
74 var schemes []*base.SecurityRequirement
75 switch request.Method {
76 case http.MethodGet:
77 if item.Get != nil {
78 schemes = append(schemes, item.Get.Security...)
79 }
80 case http.MethodPost:
81 if item.Post != nil {
82 schemes = append(schemes, item.Post.Security...)
83 }
84 case http.MethodPut:
85 if item.Put != nil {
86 schemes = append(schemes, item.Put.Security...)
87 }
88 case http.MethodDelete:
89 if item.Delete != nil {
90 schemes = append(schemes, item.Delete.Security...)
91 }
92 case http.MethodOptions:
93 if item.Options != nil {
94 schemes = append(schemes, item.Options.Security...)
95 }
96 case http.MethodHead:
97 if item.Head != nil {
98 schemes = append(schemes, item.Head.Security...)
99 }
100 case http.MethodPatch:
101 if item.Patch != nil {
102 schemes = append(schemes, item.Patch.Security...)
103 }
104 case http.MethodTrace:
105 if item.Trace != nil {
106 schemes = append(schemes, item.Trace.Security...)
107 }
108 }
109 return schemes
110 }
111
112 // ExtractSecurityHeaderNames extracts header names from applicable security schemes.
113 // Returns header names from apiKey schemes with in:"header", plus "Authorization"
114 // for http/oauth2/openIdConnect schemes.
115 //
116 // This function is used by strict mode validation to recognize security headers
117 // as "declared" headers that should not trigger undeclared header errors.
118 func ExtractSecurityHeaderNames(
119 security []*base.SecurityRequirement,
120 securitySchemes map[string]*v3.SecurityScheme,
121 ) []string {
122 if security == nil || securitySchemes == nil {
123 return nil
124 }
125
126 seen := make(map[string]bool)
127 var headers []string
128
129 for _, sec := range security {
130 if sec == nil || sec.ContainsEmptyRequirement {
131 continue // No security required for this option
132 }
133
134 if sec.Requirements == nil {
135 continue
136 }
137
138 for pair := sec.Requirements.First(); pair != nil; pair = pair.Next() {
139 schemeName := pair.Key()
140 scheme, ok := securitySchemes[schemeName]
141 if !ok || scheme == nil {
142 continue
143 }
144
145 var headerName string
146 switch strings.ToLower(scheme.Type) {
147 case "apikey":
148 if strings.ToLower(scheme.In) == Header {
149 headerName = scheme.Name
150 }
151 case "http", "oauth2", "openidconnect":
152 headerName = "Authorization"
153 }
154
155 if headerName != "" && !seen[strings.ToLower(headerName)] {
156 seen[strings.ToLower(headerName)] = true
157 headers = append(headers, headerName)
158 }
159 }
160 }
161
162 return headers
163 }
164
165 // EffectiveSecurityForOperation returns the security requirements that apply to the
166 // operation matched by request method. It implements OpenAPI's inheritance rule:
167 // - If the operation defines security (even an empty array), use that.
168 // - Otherwise, fall back to the document-level global security.
169 // - Returns nil only when neither level defines security.
170 func EffectiveSecurityForOperation(request *http.Request, item *v3.PathItem, docSecurity []*base.SecurityRequirement) []*base.SecurityRequirement {
171 op := ExtractOperation(request, item)
172 if op != nil && op.Security != nil {
173 return op.Security // operation-level (may be empty [] = "no security")
174 }
175 return docSecurity // nil when no global security either
176 }
177
178 func cast(v string) any {
179 if v == "true" || v == "false" {
180 b, _ := strconv.ParseBool(v)
181 return b
182 }
183 if i, err := strconv.ParseFloat(v, 64); err == nil {
184 // check if this is an int or not
185 if !strings.Contains(v, Period) {
186 iv, _ := strconv.ParseInt(v, 10, 64)
187 return iv
188 }
189 return i
190 }
191 return v
192 }
193
194 // getPropertySchema looks up a property's schema from an object schema's Properties map.
195 // Returns nil if objectSchema is nil, has no Properties, or the property is not found.
196 func getPropertySchema(objectSchema *base.Schema, propertyName string) *base.Schema {
197 if objectSchema == nil || objectSchema.Properties == nil {
198 return nil
199 }
200 proxy := objectSchema.Properties.GetOrZero(propertyName)
201 if proxy == nil {
202 return nil
203 }
204 return proxy.Schema()
205 }
206
207 func getAdditionalPropertiesSchema(objectSchema *base.Schema) *base.Schema {
208 if objectSchema == nil || objectSchema.AdditionalProperties == nil || !objectSchema.AdditionalProperties.IsA() ||
209 objectSchema.AdditionalProperties.A == nil {
210 return nil
211 }
212 return objectSchema.AdditionalProperties.A.Schema()
213 }
214
215 func getSchemaForObjectProperty(objectSchema *base.Schema, propertyName string) *base.Schema {
216 if propSchema := getPropertySchema(objectSchema, propertyName); propSchema != nil {
217 return propSchema
218 }
219 return getAdditionalPropertiesSchema(objectSchema)
220 }
221
222 // ParseDeepObjectKey splits a query-string key using qs-style deepObject bracket notation.
223 // It returns ok=false for non-deepObject keys or malformed bracket paths.
224 func ParseDeepObjectKey(key string) (baseName string, propertyPath []string, ok bool) {
225 open := strings.IndexRune(key, '[')
226 if open <= 0 {
227 return "", nil, false
228 }
229 baseName = key[:open]
230 rest := key[open:]
231 for len(rest) > 0 {
232 if rest[0] != '[' {
233 return "", nil, false
234 }
235 close := strings.IndexRune(rest, ']')
236 if close <= 1 {
237 return "", nil, false
238 }
239 propertyPath = append(propertyPath, rest[1:close])
240 rest = rest[close+1:]
241 }
242 return baseName, propertyPath, len(propertyPath) > 0
243 }
244
245 // castWithSchema casts a string value consulting the schema for the property's declared type.
246 // If the schema says the property, or array property item, is a string, the value is returned
247 // as-is (no numeric/bool guessing).
248 // For other declared types, it falls back to cast() which produces correct results for integer,
249 // number, and boolean values. The explicit string check prevents the most common miscast: numeric-
250 // looking strings like "10" being converted to int64 when the schema declares type: string.
251 func castWithSchema(v string, objectSchema *base.Schema, propertyName string) any {
252 propSchema := schemaForPropertyPath(objectSchema, []string{propertyName})
253 if schemaPreservesStringValue(propSchema) {
254 return v
255 }
256 if propSchema == nil && schemaPreservesStringValue(objectSchema) {
257 return v
258 }
259 return cast(v)
260 }
261
262 func queryParamPropertyPath(v *QueryParam) []string {
263 if len(v.PropertyPath) > 0 {
264 return v.PropertyPath
265 }
266 return []string{v.Property}
267 }
268
269 func queryParamDeepObjectPath(v *QueryParam) []string {
270 if v == nil {
271 return nil
272 }
273 if len(v.PropertyPath) > 0 {
274 return v.PropertyPath
275 }
276 if v.Property != "" {
277 return []string{v.Property}
278 }
279 return nil
280 }
281
282 func schemaForPropertyPath(objectSchema *base.Schema, propertyPath []string) *base.Schema {
283 current := objectSchema
284 for _, propertyName := range propertyPath {
285 current = getSchemaForObjectProperty(current, propertyName)
286 if current == nil {
287 return nil
288 }
289 }
290 return current
291 }
292
293 func schemaTypeIncludes(sch *base.Schema, schemaType string) bool {
294 return sch != nil && slices.Contains(sch.Type, schemaType)
295 }
296
297 func schemaArrayItems(sch *base.Schema) *base.Schema {
298 if sch == nil || sch.Items == nil || !sch.Items.IsA() || sch.Items.A == nil {
299 return nil
300 }
301 return sch.Items.A.Schema()
302 }
303
304 func schemaPreservesStringValue(sch *base.Schema) bool {
305 if schemaTypeIncludes(sch, String) {
306 return true
307 }
308 return schemaTypeIncludes(sch, Array) && schemaTypeIncludes(schemaArrayItems(sch), String)
309 }
310
311 // DeepObjectAllowsMultipleValues reports whether repeated values are allowed for a deepObject
312 // property. It preserves existing top-level array/additionalProperties behavior and adds support
313 // for nested properties declared as arrays.
314 func DeepObjectAllowsMultipleValues(objectSchema *base.Schema, qp *QueryParam) bool {
315 if objectSchema == nil {
316 return false
317 }
318 if schemaTypeIncludes(objectSchema, Array) {
319 return true
320 }
321 propertyPath := queryParamPropertyPath(qp)
322 if schemaTypeIncludes(schemaForPropertyPath(objectSchema, propertyPath), Array) {
323 return true
324 }
325 return schemaTypeIncludes(getAdditionalPropertiesSchema(objectSchema), Array)
326 }
327
328 func schemaForCastingPath(objectSchema *base.Schema, propertyPath []string) *base.Schema {
329 propSchema := schemaForPropertyPath(objectSchema, propertyPath)
330 if propSchema != nil {
331 return propSchema
332 }
333 if schemaTypeIncludes(objectSchema, Array) {
334 return objectSchema
335 }
336 return nil
337 }
338
339 func castWithSchemaPath(v string, objectSchema *base.Schema, propertyPath []string) any {
340 if schemaPreservesStringValue(schemaForCastingPath(objectSchema, propertyPath)) {
341 return v
342 }
343 if len(propertyPath) == 1 {
344 return castWithSchema(v, objectSchema, propertyPath[0])
345 }
346 return cast(v)
347 }
348
349 func deepObjectPathHasPrefix(prefix, path []string) bool {
350 if len(prefix) >= len(path) {
351 return false
352 }
353 for i := range prefix {
354 if prefix[i] != path[i] {
355 return false
356 }
357 }
358 return true
359 }
360
361 // DeepObjectPathConflict reports whether any deepObject property path is also used
362 // as a prefix for a nested path, such as obj[nested] and obj[nested][child].
363 func DeepObjectPathConflict(values []*QueryParam) (prefixParam, nestedParam *QueryParam, ok bool) {
364 for i := range values {
365 leftPath := queryParamDeepObjectPath(values[i])
366 if len(leftPath) == 0 {
367 continue
368 }
369 for j := i + 1; j < len(values); j++ {
370 rightPath := queryParamDeepObjectPath(values[j])
371 if len(rightPath) == 0 || slices.Equal(leftPath, rightPath) {
372 continue
373 }
374 if deepObjectPathHasPrefix(leftPath, rightPath) {
375 return values[i], values[j], true
376 }
377 if deepObjectPathHasPrefix(rightPath, leftPath) {
378 return values[j], values[i], true
379 }
380 }
381 }
382 return nil, nil, false
383 }
384
385 func setNestedDeepObjectValue(target map[string]interface{}, propertyPath []string, value any) bool {
386 if len(propertyPath) == 0 {
387 target[""] = value
388 return true
389 }
390 current := target
391 for _, propertyName := range propertyPath[:len(propertyPath)-1] {
392 next, ok := current[propertyName].(map[string]interface{})
393 if !ok {
394 if existing, exists := current[propertyName]; exists {
395 current[propertyName] = []interface{}{existing, value}
396 return false
397 }
398 next = make(map[string]interface{})
399 current[propertyName] = next
400 }
401 current = next
402 }
403
404 propertyName := propertyPath[len(propertyPath)-1]
405 if existing, exists := current[propertyName]; exists {
406 if _, existingIsMap := existing.(map[string]interface{}); existingIsMap {
407 if _, valueIsMap := value.(map[string]interface{}); !valueIsMap {
408 current[propertyName] = []interface{}{existing, value}
409 return false
410 }
411 }
412 }
413 current[propertyName] = value
414 return true
415 }
416
417 // constructKVFromDelimited is the shared implementation for constructing key=value maps
418 // from delimited strings (comma, period, semicolon). The delimiter determines how to split
419 // entries, and each entry is further split on '=' to extract key-value pairs.
420 func constructKVFromDelimited(values string, delimiter string, sch *base.Schema) map[string]interface{} {
421 props := make(map[string]interface{})
422 exploded := strings.Split(values, delimiter)
423 for i := range exploded {
424 obK := strings.Split(exploded[i], Equals)
425 if len(obK) == 2 {
426 props[obK[0]] = castWithSchema(obK[1], sch, obK[0])
427 }
428 }
429 return props
430 }
431
432 // constructParamMapFromDelimitedEncoding is the shared implementation for constructing
433 // parameter maps from pipe-delimited or space-delimited query parameter values.
434 // Entries alternate between keys and values (key|value|key|value or key value key value).
435 func constructParamMapFromDelimitedEncoding(values []*QueryParam, delimiter string, sch *base.Schema) map[string]interface{} {
436 decoded := make(map[string]interface{})
437 for _, v := range values {
438 props := make(map[string]interface{})
439 exploded := strings.Split(v.Values[0], delimiter)
440 for i := range exploded {
441 if i%2 == 0 && i+1 < len(exploded) {
442 props[exploded[i]] = castWithSchema(exploded[i+1], sch, exploded[i])
443 }
444 }
445 decoded[v.Key] = props
446 }
447 return decoded
448 }
449
450 // ConstructParamMapFromDeepObjectEncoding will construct a map from the query parameters that are encoded as
451 // deep objects. It's kind of a crazy way to do things, but hey, each to their own.
452 func ConstructParamMapFromDeepObjectEncoding(values []*QueryParam, sch *base.Schema) map[string]interface{} {
453 decoded := make(map[string]interface{})
454 for _, v := range values {
455 propertyPath := queryParamPropertyPath(v)
456 castForProp := func(val string) any {
457 return castWithSchemaPath(val, sch, propertyPath)
458 }
459
460 props, ok := decoded[v.Key].(map[string]interface{})
461 if !ok {
462 props = make(map[string]interface{})
463 decoded[v.Key] = props
464 }
465
466 rawValues := make([]interface{}, len(v.Values))
467 for i := range v.Values {
468 rawValues[i] = castForProp(v.Values[i])
469 }
470 if DeepObjectAllowsMultipleValues(sch, v) {
471 setNestedDeepObjectValue(props, propertyPath, rawValues)
472 continue
473 }
474 setNestedDeepObjectValue(props, propertyPath, castForProp(v.Values[0]))
475 }
476 return decoded
477 }
478
479 // ConstructParamMapFromQueryParamInput will construct a param map from an existing map of *QueryParam slices.
480 //
481 // Deprecated: use ConstructParamMapFromQueryParamInputWithSchema instead.
482 func ConstructParamMapFromQueryParamInput(values map[string][]*QueryParam) map[string]interface{} {
483 return ConstructParamMapFromQueryParamInputWithSchema(values, nil)
484 }
485
486 // ConstructParamMapFromPipeEncoding will construct a map from the query parameters that are encoded as
487 // pipe separated values.
488 //
489 // Deprecated: use ConstructParamMapFromPipeEncodingWithSchema instead.
490 func ConstructParamMapFromPipeEncoding(values []*QueryParam) map[string]interface{} {
491 return ConstructParamMapFromPipeEncodingWithSchema(values, nil)
492 }
493
494 // ConstructParamMapFromSpaceEncoding will construct a map from the query parameters that are encoded as
495 // space delimited values.
496 //
497 // Deprecated: use ConstructParamMapFromSpaceEncodingWithSchema instead.
498 func ConstructParamMapFromSpaceEncoding(values []*QueryParam) map[string]interface{} {
499 return ConstructParamMapFromSpaceEncodingWithSchema(values, nil)
500 }
501
502 // ConstructMapFromCSV will construct a map from a comma separated value string.
503 //
504 // Deprecated: use ConstructMapFromCSVWithSchema instead.
505 func ConstructMapFromCSV(csv string) map[string]interface{} {
506 return ConstructMapFromCSVWithSchema(csv, nil)
507 }
508
509 // ConstructKVFromCSV will construct a map from a comma separated value string that denotes key value pairs.
510 //
511 // Deprecated: use ConstructKVFromCSVWithSchema instead.
512 func ConstructKVFromCSV(values string) map[string]interface{} {
513 return ConstructKVFromCSVWithSchema(values, nil)
514 }
515
516 // ConstructKVFromLabelEncoding will construct a map from a period separated value string that denotes key value pairs.
517 //
518 // Deprecated: use ConstructKVFromLabelEncodingWithSchema instead.
519 func ConstructKVFromLabelEncoding(values string) map[string]interface{} {
520 return ConstructKVFromLabelEncodingWithSchema(values, nil)
521 }
522
523 // ConstructKVFromMatrixCSV will construct a map from a semicolon separated value string that denotes key value pairs.
524 //
525 // Deprecated: use ConstructKVFromMatrixCSVWithSchema instead.
526 func ConstructKVFromMatrixCSV(values string) map[string]interface{} {
527 return ConstructKVFromMatrixCSVWithSchema(values, nil)
528 }
529
530 // ConstructParamMapFromFormEncodingArray will construct a map from the query parameters that are encoded as
531 // form encoded values.
532 //
533 // Deprecated: use ConstructParamMapFromFormEncodingArrayWithSchema instead.
534 func ConstructParamMapFromFormEncodingArray(values []*QueryParam) map[string]interface{} {
535 return ConstructParamMapFromFormEncodingArrayWithSchema(values, nil)
536 }
537
538 // DoesFormParamContainDelimiter will determine if a form parameter contains a delimiter.
539 func DoesFormParamContainDelimiter(value, style string) bool {
540 if strings.Contains(value, Comma) && (style == "" || style == Form) {
541 return true
542 }
543 return false
544 }
545
546 // ExplodeQueryValue will explode a query value based on the style (space, pipe, or form/default).
547 func ExplodeQueryValue(value, style string) []string {
548 switch style {
549 case SpaceDelimited:
550 return strings.Split(value, Space)
551 case PipeDelimited:
552 return strings.Split(value, Pipe)
553 default:
554 return strings.Split(value, Comma)
555 }
556 }
557
558 func CollapseCSVIntoFormStyle(key string, value string) string {
559 return fmt.Sprintf("&%s=%s", key,
560 strings.Join(strings.Split(value, ","), fmt.Sprintf("&%s=", key)))
561 }
562
563 func CollapseCSVIntoSpaceDelimitedStyle(key string, values []string) string {
564 return fmt.Sprintf("%s=%s", key, strings.Join(values, "%20"))
565 }
566
567 func CollapseCSVIntoPipeDelimitedStyle(key string, values []string) string {
568 return fmt.Sprintf("%s=%s", key, strings.Join(values, Pipe))
569 }
570
571 // ConstructParamMapFromQueryParamInputWithSchema constructs a param map from an existing map of
572 // *QueryParam slices, using the object schema to determine property types before casting.
573 func ConstructParamMapFromQueryParamInputWithSchema(values map[string][]*QueryParam, sch *base.Schema) map[string]interface{} {
574 decoded := make(map[string]interface{})
575 for _, q := range values {
576 for _, v := range q {
577 decoded[v.Key] = castWithSchema(v.Values[0], sch, v.Key)
578 }
579 }
580 return decoded
581 }
582
583 // ConstructParamMapFromPipeEncodingWithSchema constructs a map from pipe-delimited query parameters,
584 // using the object schema to determine property types before casting.
585 func ConstructParamMapFromPipeEncodingWithSchema(values []*QueryParam, sch *base.Schema) map[string]interface{} {
586 return constructParamMapFromDelimitedEncoding(values, Pipe, sch)
587 }
588
589 // ConstructParamMapFromSpaceEncodingWithSchema constructs a map from space-delimited query parameters,
590 // using the object schema to determine property types before casting.
591 func ConstructParamMapFromSpaceEncodingWithSchema(values []*QueryParam, sch *base.Schema) map[string]interface{} {
592 return constructParamMapFromDelimitedEncoding(values, Space, sch)
593 }
594
595 // ConstructMapFromCSVWithSchema constructs a map from a comma separated value string,
596 // using the object schema to determine property types before casting.
597 func ConstructMapFromCSVWithSchema(csv string, sch *base.Schema) map[string]interface{} {
598 decoded := make(map[string]interface{})
599 exploded := strings.Split(csv, Comma)
600 for i := range exploded {
601 if i%2 == 0 {
602 if len(exploded) == i+1 {
603 break
604 }
605 decoded[exploded[i]] = castWithSchema(exploded[i+1], sch, exploded[i])
606 }
607 }
608 return decoded
609 }
610
611 // ConstructKVFromCSVWithSchema constructs a map from a comma-separated key=value string,
612 // using the object schema to determine property types before casting.
613 func ConstructKVFromCSVWithSchema(values string, sch *base.Schema) map[string]interface{} {
614 return constructKVFromDelimited(values, Comma, sch)
615 }
616
617 // ConstructKVFromLabelEncodingWithSchema constructs a map from a period-separated key=value string,
618 // using the object schema to determine property types before casting.
619 func ConstructKVFromLabelEncodingWithSchema(values string, sch *base.Schema) map[string]interface{} {
620 return constructKVFromDelimited(values, Period, sch)
621 }
622
623 // ConstructKVFromMatrixCSVWithSchema constructs a map from a semicolon-separated key=value string,
624 // using the object schema to determine property types before casting.
625 func ConstructKVFromMatrixCSVWithSchema(values string, sch *base.Schema) map[string]interface{} {
626 return constructKVFromDelimited(values, SemiColon, sch)
627 }
628
629 // ConstructParamMapFromFormEncodingArrayWithSchema constructs a map from form-encoded query parameters,
630 // using the object schema to determine property types before casting.
631 func ConstructParamMapFromFormEncodingArrayWithSchema(values []*QueryParam, sch *base.Schema) map[string]interface{} {
632 decoded := make(map[string]interface{})
633 for _, v := range values {
634 props := make(map[string]interface{})
635 exploded := strings.Split(v.Values[0], Comma)
636 for i := range exploded {
637 if i%2 == 0 {
638 if len(exploded) > i+1 {
639 props[exploded[i]] = castWithSchema(exploded[i+1], sch, exploded[i])
640 }
641 }
642 }
643 decoded[v.Key] = props
644 }
645 return decoded
646 }