Debian Codegraph @

responses/validate_headers.go

raw
1 // Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley
2 // https://pb33f.io
3
4 package responses
5
6 import (
7 "fmt"
8 "net/http"
9 "strings"
10
11 "github.com/pb33f/libopenapi/orderedmap"
12
13 v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
14 lowv3 "github.com/pb33f/libopenapi/datamodel/low/v3"
15
16 "github.com/pb33f/libopenapi-validator/config"
17 "github.com/pb33f/libopenapi-validator/errors"
18 "github.com/pb33f/libopenapi-validator/helpers"
19 "github.com/pb33f/libopenapi-validator/parameters"
20 "github.com/pb33f/libopenapi-validator/strict"
21 )
22
23 // ValidateResponseHeaders validates the response headers against the OpenAPI spec.
24 func ValidateResponseHeaders(
25 request *http.Request,
26 response *http.Response,
27 headers *orderedmap.Map[string, *v3.Header],
28 pathTemplate string,
29 statusCode string,
30 opts ...config.Option,
31 ) (bool, []*errors.ValidationError) {
32 options := config.NewValidationOptions(opts...)
33
34 // locate headers
35 type headerPair struct {
36 name string
37 value []string
38 model *v3.Header
39 }
40 locatedHeaders := make(map[string]headerPair)
41 var validationErrors []*errors.ValidationError
42 // iterate through the response headers
43 for name, v := range response.Header {
44 // check if the model is in the spec
45 for pair := headers.First(); pair != nil; pair = pair.Next() {
46 k := pair.Key()
47 header := pair.Value()
48 if strings.EqualFold(k, name) {
49 locatedHeaders[strings.ToLower(name)] = headerPair{
50 name: k,
51 value: v,
52 model: header,
53 }
54 }
55 }
56 }
57
58 // determine if any required headers are missing from the response
59 for pair := headers.First(); pair != nil; pair = pair.Next() {
60 name := pair.Key()
61 header := pair.Value()
62 if header.Required {
63 if _, ok := locatedHeaders[strings.ToLower(name)]; !ok {
64 keywordLocation := helpers.ConstructResponseHeaderJSONPointer(pathTemplate, request.Method, statusCode, name, "required")
65
66 specLine, specCol := 1, 0
67 if low := header.GoLow(); low != nil && low.KeyNode != nil {
68 specLine = low.KeyNode.Line
69 specCol = low.KeyNode.Column
70 }
71
72 validationErrors = append(validationErrors, &errors.ValidationError{
73 ValidationType: helpers.ResponseBodyValidation,
74 ValidationSubType: helpers.ParameterValidationHeader,
75 Message: "Missing required header",
76 Reason: fmt.Sprintf("Required header '%s' was not found in response", name),
77 SpecLine: specLine,
78 SpecCol: specCol,
79 HowToFix: errors.HowToFixMissingHeader,
80 RequestPath: request.URL.Path,
81 RequestMethod: request.Method,
82 SchemaValidationErrors: []*errors.SchemaValidationFailure{{
83 Reason: fmt.Sprintf("Required header '%s' is missing", name),
84 FieldName: name,
85 InstancePath: []string{name},
86 KeywordLocation: keywordLocation,
87 }},
88 })
89 }
90 }
91 }
92
93 // validate the model schemas if they are set.
94 for h, header := range locatedHeaders {
95 if header.model.Schema != nil {
96 schema := header.model.Schema.Schema()
97 if schema != nil && header.model.Required {
98 for _, headerValue := range header.value {
99 validationErrors = append(validationErrors,
100 parameters.ValidateParameterSchema(schema, nil, headerValue, "header",
101 "response header", h, helpers.ResponseBodyValidation, lowv3.HeadersLabel, options)...)
102 }
103 }
104 }
105 }
106
107 if len(validationErrors) > 0 {
108 return false, validationErrors
109 }
110
111 // strict mode: check for undeclared response headers
112 if options.StrictMode {
113 // convert orderedmap to regular map for strict validation
114 declaredMap := make(map[string]*v3.Header)
115 for name, header := range headers.FromOldest() {
116 declaredMap[name] = header
117 }
118
119 undeclaredHeaders := strict.ValidateResponseHeaders(response.Header, &declaredMap, options)
120 for _, undeclared := range undeclaredHeaders {
121 validationErrors = append(validationErrors,
122 errors.UndeclaredHeaderError(
123 undeclared.Name,
124 undeclared.Value.(string),
125 undeclared.DeclaredProperties,
126 undeclared.Direction.String(),
127 request.URL.Path,
128 request.Method,
129 ))
130 }
131 }
132
133 if len(validationErrors) > 0 {
134 return false, validationErrors
135 }
136 return true, nil
137 }