Debian Codegraph @

responses/validate_response.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 "errors"
10 "fmt"
11 "io"
12 "net/http"
13 "reflect"
14 "regexp"
15 "strconv"
16
17 "github.com/pb33f/libopenapi/datamodel/high/base"
18 "github.com/pb33f/libopenapi/utils"
19 "github.com/santhosh-tekuri/jsonschema/v6"
20 "go.yaml.in/yaml/v4"
21 "golang.org/x/text/language"
22 "golang.org/x/text/message"
23
24 "github.com/pb33f/libopenapi-validator/cache"
25 "github.com/pb33f/libopenapi-validator/config"
26 liberrors "github.com/pb33f/libopenapi-validator/errors"
27 "github.com/pb33f/libopenapi-validator/helpers"
28 "github.com/pb33f/libopenapi-validator/schema_validation"
29 "github.com/pb33f/libopenapi-validator/strict"
30 )
31
32 var instanceLocationRegex = regexp.MustCompile(`^/(\d+)`)
33
34 // ValidateResponseSchemaInput contains parameters for response schema validation.
35 type ValidateResponseSchemaInput struct {
36 Request *http.Request // Required: The HTTP request (for context)
37 Response *http.Response // Required: The HTTP response to validate
38 Schema *base.Schema // Required: The OpenAPI schema to validate against
39 Version float32 // Required: OpenAPI version (3.0 or 3.1)
40 Options []config.Option // Optional: Functional options (defaults applied if empty/nil)
41 }
42
43 // ValidateResponseSchema will validate the response body for a http.Response pointer. The request is used to
44 // locate the operation in the specification, the response is used to ensure the response code, media type and the
45 // schema of the response body are valid.
46 //
47 // This function is used by the ValidateResponseBody function, but can be used independently.
48 // The schema will be compiled from cache if available, otherwise it will be compiled and cached.
49 func ValidateResponseSchema(input *ValidateResponseSchemaInput) (bool, []*liberrors.ValidationError) {
50 validationOptions := config.NewValidationOptions(input.Options...)
51 var validationErrors []*liberrors.ValidationError
52 var renderedSchema, jsonSchema []byte
53 var referenceSchema string
54 var compiledSchema *jsonschema.Schema
55 var cachedNode *yaml.Node
56
57 if input.Schema == nil {
58 return false, []*liberrors.ValidationError{{
59 ValidationType: helpers.ResponseBodyValidation,
60 ValidationSubType: helpers.Schema,
61 Message: "schema is nil",
62 Reason: "The schema to validate against is nil",
63 }}
64 } else if input.Schema.GoLow() == nil {
65 return false, []*liberrors.ValidationError{{
66 ValidationType: helpers.ResponseBodyValidation,
67 ValidationSubType: helpers.Schema,
68 Message: "schema cannot be rendered",
69 Reason: "The schema does not have low-level information and cannot be rendered. Please ensure the schema is loaded from a document.",
70 }}
71 }
72
73 if validationOptions.SchemaCache != nil {
74 hash := input.Schema.GoLow().Hash()
75 if cached, ok := validationOptions.SchemaCache.Load(hash); ok && cached != nil && cached.CompiledSchema != nil {
76 renderedSchema = cached.RenderedInline
77 referenceSchema = cached.ReferenceSchema
78 compiledSchema = cached.CompiledSchema
79 cachedNode = cached.RenderedNode
80 }
81 }
82
83 // Cache miss or no cache - render and compile
84 if compiledSchema == nil {
85 renderCtx := base.NewInlineRenderContextForValidation()
86 var renderErr error
87 renderedSchema, renderErr = input.Schema.RenderInlineWithContext(renderCtx)
88 referenceSchema = string(renderedSchema)
89
90 // If rendering failed (e.g., circular reference), return the render error
91 if renderErr != nil {
92 violation := &liberrors.SchemaValidationFailure{
93 Reason: renderErr.Error(),
94 ReferenceSchema: referenceSchema,
95 }
96 validationErrors = append(validationErrors, &liberrors.ValidationError{
97 ValidationType: helpers.ResponseBodyValidation,
98 ValidationSubType: helpers.Schema,
99 Message: fmt.Sprintf("%d response body for '%s' failed schema rendering",
100 input.Response.StatusCode, input.Request.URL.Path),
101 Reason: fmt.Sprintf("The response schema for status code '%d' failed to render: %s",
102 input.Response.StatusCode, renderErr.Error()),
103 SpecLine: 1,
104 SpecCol: 0,
105 SchemaValidationErrors: []*liberrors.SchemaValidationFailure{violation},
106 HowToFix: "check the response schema for circular references or invalid structures",
107 Context: referenceSchema,
108 })
109 return false, validationErrors
110 }
111
112 jsonSchema, _ = utils.ConvertYAMLtoJSON(renderedSchema)
113
114 var err error
115 schemaName := fmt.Sprintf("%x", input.Schema.GoLow().Hash())
116 compiledSchema, err = helpers.NewCompiledSchemaWithVersion(
117 schemaName,
118 jsonSchema,
119 validationOptions,
120 input.Version,
121 )
122 if err != nil {
123 validationErrors = append(validationErrors, &liberrors.ValidationError{
124 ValidationType: helpers.ResponseBodyValidation,
125 ValidationSubType: helpers.Schema,
126 Message: fmt.Sprintf("%d response body for '%s' failed schema compilation",
127 input.Response.StatusCode, input.Request.URL.Path),
128 Reason: fmt.Sprintf("The response schema for status code '%d' failed to compile: %s",
129 input.Response.StatusCode, err.Error()),
130 SpecLine: 1,
131 SpecCol: 0,
132 HowToFix: "check the response schema for invalid JSON Schema syntax, complex regex patterns, or unsupported schema constructs",
133 Context: input.Schema,
134 })
135 return false, validationErrors
136 }
137
138 if validationOptions.SchemaCache != nil {
139 hash := input.Schema.GoLow().Hash()
140 validationOptions.SchemaCache.Store(hash, &cache.SchemaCacheEntry{
141 Schema: input.Schema,
142 RenderedInline: renderedSchema,
143 ReferenceSchema: referenceSchema,
144 RenderedJSON: jsonSchema,
145 CompiledSchema: compiledSchema,
146 })
147 }
148 }
149
150 request := input.Request
151 response := input.Response
152 schema := input.Schema
153
154 if response == nil || response.Body == http.NoBody {
155
156 // skip response body validation for head request after processing schema
157 if response != nil && request != nil && request.Method == http.MethodHead {
158 return len(validationErrors) == 0, validationErrors
159 }
160 // cannot decode the response body, so it's not valid
161 validationErrors = append(validationErrors, &liberrors.ValidationError{
162 ValidationType: "response",
163 ValidationSubType: "object",
164 Message: fmt.Sprintf("%s response object is missing for '%s'",
165 request.Method, request.URL.Path),
166 Reason: "The response object is completely missing",
167 SpecLine: 1,
168 SpecCol: 0,
169 HowToFix: "ensure response object has been set",
170 Context: schema,
171 })
172 return false, validationErrors
173 }
174
175 responseBody, ioErr := io.ReadAll(response.Body)
176 if ioErr != nil {
177 // cannot decode the response body, so it's not valid
178 validationErrors = append(validationErrors, &liberrors.ValidationError{
179 ValidationType: helpers.ResponseBodyValidation,
180 ValidationSubType: helpers.Schema,
181 Message: fmt.Sprintf("%s response body for '%s' cannot be read, it's empty or malformed",
182 request.Method, request.URL.Path),
183 Reason: fmt.Sprintf("The response body cannot be decoded: %s", ioErr.Error()),
184 SpecLine: 1,
185 SpecCol: 0,
186 HowToFix: "ensure body is not empty",
187 Context: schema,
188 })
189 return false, validationErrors
190 }
191
192 // close the request body, so it can be re-read later by another player in the chain
193 _ = response.Body.Close()
194 response.Body = io.NopCloser(bytes.NewBuffer(responseBody))
195
196 var decodedObj interface{}
197
198 if len(responseBody) > 0 {
199 // Per RFC7231, a response to a HEAD request MUST NOT include a message body.
200 if request != nil && request.Method == http.MethodHead {
201 violation := &liberrors.SchemaValidationFailure{
202 Reason: "HEAD responses must not include a message body",
203 ReferenceObject: string(responseBody),
204 ReferenceSchema: referenceSchema,
205 }
206 validationErrors = append(validationErrors, &liberrors.ValidationError{
207 ValidationType: helpers.ResponseBodyValidation,
208 ValidationSubType: helpers.Schema,
209 Message: fmt.Sprintf("%s response for '%s' must not include a body",
210 request.Method, request.URL.Path),
211 Reason: "The response to a HEAD request must not contain a body",
212 SpecLine: 1,
213 SpecCol: 0,
214 SchemaValidationErrors: []*liberrors.SchemaValidationFailure{violation},
215 HowToFix: "ensure no response body is present for HEAD requests",
216 Context: referenceSchema,
217 })
218 return false, validationErrors
219 }
220 err := json.Unmarshal(responseBody, &decodedObj)
221 if err != nil {
222 // cannot decode the response body, so it's not valid
223 validationErrors = append(validationErrors, &liberrors.ValidationError{
224 ValidationType: helpers.ResponseBodyValidation,
225 ValidationSubType: helpers.Schema,
226 Message: fmt.Sprintf("%s response body for '%s' failed to validate schema",
227 request.Method, request.URL.Path),
228 Reason: fmt.Sprintf("The response body cannot be decoded: %s", err.Error()),
229 SpecLine: 1,
230 SpecCol: 0,
231 HowToFix: liberrors.HowToFixInvalidSchema,
232 Context: schema,
233 })
234 return false, validationErrors
235 }
236 }
237
238 // no response body? failed to decode anything? nothing to do here.
239 if responseBody == nil || decodedObj == nil {
240 return true, nil
241 }
242
243 // validate the object against the schema
244 scErrs := compiledSchema.Validate(decodedObj)
245 if scErrs != nil {
246 var jk *jsonschema.ValidationError
247 var schemaValidationErrors []*liberrors.SchemaValidationFailure
248
249 if errors.As(scErrs, &jk) {
250 // flatten the validationErrors
251 schFlatErrs := jk.BasicOutput().Errors
252
253 renderedNode := cachedNode
254 if renderedNode == nil {
255 renderedNode = new(yaml.Node)
256 _ = yaml.Unmarshal(renderedSchema, renderedNode)
257 }
258
259 for q := range schFlatErrs {
260 er := schFlatErrs[q]
261
262 errMsg := er.Error.Kind.LocalizedString(message.NewPrinter(language.Tag{}))
263 if er.KeywordLocation == "" || helpers.IgnoreRegex.MatchString(errMsg) {
264 continue // ignore this error, it's useless tbh, utter noise.
265 }
266 if er.Error != nil {
267 // locate the violated property in the schema
268 var located *yaml.Node
269 if len(renderedNode.Content) > 0 {
270 located = schema_validation.LocateSchemaPropertyNodeByJSONPath(renderedNode.Content[0], er.KeywordLocation)
271 }
272
273 // extract the element specified by the instance
274 val := instanceLocationRegex.FindStringSubmatch(er.InstanceLocation)
275 var referenceObject string
276
277 if len(val) > 0 {
278 referenceIndex, _ := strconv.Atoi(val[1])
279 if reflect.ValueOf(decodedObj).Type().Kind() == reflect.Slice {
280 found := decodedObj.([]any)[referenceIndex]
281 recoded, _ := json.MarshalIndent(found, "", " ")
282 referenceObject = string(recoded)
283 }
284 }
285 if referenceObject == "" {
286 referenceObject = string(responseBody)
287 }
288
289 violation := &liberrors.SchemaValidationFailure{
290 Reason: errMsg,
291 FieldName: helpers.ExtractFieldNameFromStringLocation(er.InstanceLocation),
292 FieldPath: helpers.ExtractJSONPathFromStringLocation(er.InstanceLocation),
293 InstancePath: helpers.ConvertStringLocationToPathSegments(er.InstanceLocation),
294 KeywordLocation: er.KeywordLocation,
295 ReferenceSchema: referenceSchema,
296 ReferenceObject: referenceObject,
297 OriginalJsonSchemaError: jk,
298 }
299 // if we have a location within the schema, add it to the error
300 if located != nil {
301
302 line := located.Line
303 // if the located node is a map or an array, then the actual human interpretable
304 // line on which the violation occurred is the line of the key, not the value.
305 if located.Kind == yaml.MappingNode || located.Kind == yaml.SequenceNode {
306 if line > 0 {
307 line--
308 }
309 }
310
311 // location of the violation within the rendered schema.
312 violation.Line = line
313 violation.Column = located.Column
314 }
315 schemaValidationErrors = append(schemaValidationErrors, violation)
316 }
317 }
318 }
319
320 line := 1
321 col := 0
322 if low := schema.GoLow(); low != nil && low.Type.KeyNode != nil {
323 line = low.Type.KeyNode.Line
324 col = low.Type.KeyNode.Column
325 }
326
327 // add the error to the list
328 validationErrors = append(validationErrors, &liberrors.ValidationError{
329 ValidationType: helpers.ResponseBodyValidation,
330 ValidationSubType: helpers.Schema,
331 Message: fmt.Sprintf("%d response body for '%s' failed to validate schema",
332 response.StatusCode, request.URL.Path),
333 Reason: fmt.Sprintf("The response body for status code '%d' is defined as an object. "+
334 "However, it does not meet the schema requirements of the specification", response.StatusCode),
335 SpecLine: line,
336 SpecCol: col,
337 SchemaValidationErrors: schemaValidationErrors,
338 HowToFix: liberrors.HowToFixInvalidSchema,
339 Context: schema,
340 })
341 }
342 if len(validationErrors) > 0 {
343 return false, validationErrors
344 }
345
346 // strict mode: check for undeclared properties in response body
347 if validationOptions.StrictMode && decodedObj != nil {
348 strictValidator := strict.NewValidator(validationOptions, input.Version)
349 strictResult := strictValidator.Validate(strict.Input{
350 Schema: schema,
351 Data: decodedObj,
352 Direction: strict.DirectionResponse,
353 Options: validationOptions,
354 BasePath: "$.body",
355 Version: input.Version,
356 })
357
358 if !strictResult.Valid {
359 for _, undeclared := range strictResult.UndeclaredValues {
360 switch undeclared.Type {
361 case strict.TypeWriteOnlyProperty:
362 validationErrors = append(validationErrors,
363 liberrors.WriteOnlyPropertyError(
364 undeclared.Path, undeclared.Name, undeclared.Value,
365 request.URL.Path, request.Method,
366 undeclared.SpecLine, undeclared.SpecCol,
367 ))
368 default:
369 validationErrors = append(validationErrors,
370 liberrors.UndeclaredPropertyError(
371 undeclared.Path,
372 undeclared.Name,
373 undeclared.Value,
374 undeclared.DeclaredProperties,
375 undeclared.Direction.String(),
376 request.URL.Path,
377 request.Method,
378 undeclared.SpecLine,
379 undeclared.SpecCol,
380 ))
381 }
382 }
383 }
384 }
385
386 if len(validationErrors) > 0 {
387 return false, validationErrors
388 }
389 return true, nil
390 }