Debian Codegraph @

responses/validate_body.go

raw
1 // Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley
2 // SPDX-License-Identifier: MIT
3
4 package responses
5
6 import (
7 "bytes"
8 "encoding/json"
9 "fmt"
10 "io"
11 "net/http"
12 "strconv"
13 "strings"
14
15 "github.com/pb33f/libopenapi/orderedmap"
16
17 v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
18
19 "github.com/pb33f/libopenapi-validator/config"
20 "github.com/pb33f/libopenapi-validator/errors"
21 "github.com/pb33f/libopenapi-validator/helpers"
22 "github.com/pb33f/libopenapi-validator/paths"
23 "github.com/pb33f/libopenapi-validator/schema_validation"
24 )
25
26 func (v *responseBodyValidator) ValidateResponseBody(
27 request *http.Request,
28 response *http.Response,
29 ) (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.ValidateResponseBodyWithPathItem(request, response, pathItem, foundPath)
35 }
36
37 func (v *responseBodyValidator) ValidateResponseBodyWithPathItem(request *http.Request, response *http.Response, pathItem *v3.PathItem, pathFound 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 var validationErrors []*errors.ValidationError
52 operation := helpers.ExtractOperation(request, pathItem)
53 if operation == nil {
54 return false, []*errors.ValidationError{errors.OperationNotFound(pathItem, request, request.Method, pathFound)}
55 }
56 // extract the response code from the response
57 httpCode := response.StatusCode
58 contentType := response.Header.Get(helpers.ContentTypeHeader)
59 codeStr := strconv.Itoa(httpCode)
60
61 // extract the media type from the content type header.
62 mediaTypeSting, _, _ := helpers.ExtractContentType(contentType)
63
64 // check if operation has responses defined
65 if operation.Responses == nil || operation.Responses.Codes == nil {
66 return true, nil
67 }
68
69 // check if the response code is in the contract
70 foundResponse := operation.Responses.Codes.GetOrZero(codeStr)
71 if foundResponse == nil {
72 // check range definition for response codes
73 foundResponse = operation.Responses.Codes.GetOrZero(fmt.Sprintf("%dXX", httpCode/100))
74 if foundResponse != nil {
75 codeStr = fmt.Sprintf("%dXX", httpCode/100)
76 }
77 }
78
79 if foundResponse != nil {
80 if foundResponse.Content != nil { // only validate if we have content types.
81 // check content type has been defined in the contract
82 if mediaType, ok := foundResponse.Content.Get(mediaTypeSting); ok {
83 validationErrors = append(validationErrors,
84 v.checkResponseSchema(request, response, mediaTypeSting, mediaType)...)
85 } else {
86 // check that the operation *actually* returns a body. (i.e. a 204 response)
87 if foundResponse.Content != nil && orderedmap.Len(foundResponse.Content) > 0 {
88 // content type not found in the contract
89 validationErrors = append(validationErrors,
90 errors.ResponseContentTypeNotFound(operation, request, response, codeStr, false))
91 }
92 }
93 }
94 } else {
95 // no code match, check for default response
96 if operation.Responses.Default != nil && operation.Responses.Default.Content != nil {
97 // check content type has been defined in the contract
98 if mediaType, ok := operation.Responses.Default.Content.Get(mediaTypeSting); ok {
99 foundResponse = operation.Responses.Default
100 validationErrors = append(validationErrors,
101 v.checkResponseSchema(request, response, contentType, mediaType)...)
102 } else {
103 // check that the operation *actually* returns a body. (i.e. a 204 response)
104 if operation.Responses.Default.Content != nil && orderedmap.Len(operation.Responses.Default.Content) > 0 {
105 // content type not found in the contract
106 validationErrors = append(validationErrors,
107 errors.ResponseContentTypeNotFound(operation, request, response, codeStr, true))
108 }
109 }
110 } else {
111 // TODO: add support for '2XX' and '3XX' responses in the contract
112 // no default, no code match, nothing!
113 validationErrors = append(validationErrors,
114 errors.ResponseCodeNotFound(operation, request, httpCode))
115 }
116 }
117
118 if foundResponse != nil {
119 // check for headers in the response
120 if foundResponse.Headers != nil {
121 if ok, hErrs := ValidateResponseHeaders(request, response, foundResponse.Headers, pathFound, codeStr, config.WithExistingOpts(v.options)); !ok {
122 validationErrors = append(validationErrors, hErrs...)
123 }
124 }
125 }
126
127 errors.PopulateValidationErrors(validationErrors, request, pathFound)
128
129 if len(validationErrors) > 0 {
130 return false, validationErrors
131 }
132 return true, nil
133 }
134
135 func (v *responseBodyValidator) checkResponseSchema(
136 request *http.Request,
137 response *http.Response,
138 contentType string,
139 mediaType *v3.MediaType,
140 ) []*errors.ValidationError {
141 var validationErrors []*errors.ValidationError
142
143 if mediaType.Schema == nil {
144 return validationErrors
145 }
146
147 // currently, we can only validate JSON, XML and URL Encoded based responses, so check for the presence
148 // of 'json' (what ever it may be) and for XML/URLEncoded content type so we can perform a schema check on it.
149 // anything other than JSON XML, or URL Encoded will be ignored.
150
151 isXml := schema_validation.IsXMLContentType(contentType)
152 isUrlEncoded := schema_validation.IsURLEncodedContentType(contentType)
153 isJson := strings.Contains(strings.ToLower(contentType), helpers.JSONType)
154
155 xmlValid := isXml && v.options.AllowXMLBodyValidation
156 urlEncodedValid := isUrlEncoded && v.options.AllowURLEncodedBodyValidation
157
158 if !isJson && !xmlValid && !urlEncodedValid {
159 return validationErrors
160 }
161
162 schema := mediaType.Schema.Schema()
163
164 if !isJson {
165 if response != nil && response.Body != http.NoBody {
166 responseBody, _ := io.ReadAll(response.Body)
167 _ = response.Body.Close()
168
169 stringedBody := string(responseBody)
170 var jsonBody any
171 var prevalidationErrors []*errors.ValidationError
172
173 switch {
174 case xmlValid:
175 jsonBody, prevalidationErrors = schema_validation.TransformXMLToSchemaJSON(stringedBody, schema)
176 case urlEncodedValid:
177 jsonBody, prevalidationErrors = schema_validation.TransformURLEncodedToSchemaJSON(stringedBody, schema, mediaType.Encoding)
178 }
179
180 if len(prevalidationErrors) > 0 {
181 return prevalidationErrors
182 }
183
184 transformedBytes, err := json.Marshal(jsonBody)
185 if err != nil {
186 switch {
187 case isXml:
188 return []*errors.ValidationError{errors.InvalidXMLParsing(err.Error(), stringedBody)}
189 case isUrlEncoded:
190 return []*errors.ValidationError{errors.InvalidURLEncodedParsing(err.Error(), stringedBody)}
191 }
192 }
193
194 response.Body = io.NopCloser(bytes.NewBuffer(transformedBytes))
195 }
196 }
197
198 // Validate response schema
199 valid, vErrs := ValidateResponseSchema(&ValidateResponseSchemaInput{
200 Request: request,
201 Response: response,
202 Schema: schema,
203 Version: helpers.VersionToFloat(v.document.Version),
204 Options: []config.Option{config.WithExistingOpts(v.options)},
205 })
206
207 if !valid {
208 validationErrors = append(validationErrors, vErrs...)
209 }
210
211 return validationErrors
212 }