| 1 |
// Copyright 2023 Princess B33f Heavy Industries / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
package requests |
| 5 |
|
| 6 |
import ( |
| 7 |
"encoding/json" |
| 8 |
"fmt" |
| 9 |
"net/http" |
| 10 |
"strings" |
| 11 |
|
| 12 |
v3 "github.com/pb33f/libopenapi/datamodel/high/v3" |
| 13 |
|
| 14 |
"github.com/pb33f/libopenapi-validator/config" |
| 15 |
"github.com/pb33f/libopenapi-validator/errors" |
| 16 |
"github.com/pb33f/libopenapi-validator/helpers" |
| 17 |
"github.com/pb33f/libopenapi-validator/paths" |
| 18 |
"github.com/pb33f/libopenapi-validator/schema_validation" |
| 19 |
) |
| 20 |
|
| 21 |
func (v *requestBodyValidator) ValidateRequestBody(request *http.Request) (bool, []*errors.ValidationError) { |
| 22 |
pathItem, errs, foundPath := paths.FindPath(request, v.document, v.options) |
| 23 |
if len(errs) > 0 { |
| 24 |
return false, errs |
| 25 |
} |
| 26 |
return v.ValidateRequestBodyWithPathItem(request, pathItem, foundPath) |
| 27 |
} |
| 28 |
|
| 29 |
func (v *requestBodyValidator) ValidateRequestBodyWithPathItem(request *http.Request, pathItem *v3.PathItem, pathValue string) (bool, []*errors.ValidationError) { |
| 30 |
if pathItem == nil { |
| 31 |
return false, []*errors.ValidationError{{ |
| 32 |
ValidationType: helpers.PathValidation, |
| 33 |
ValidationSubType: helpers.ValidationMissing, |
| 34 |
Message: fmt.Sprintf("%s Path '%s' not found", request.Method, request.URL.Path), |
| 35 |
Reason: fmt.Sprintf("The %s request contains a path of '%s' "+ |
| 36 |
"however that path, or the %s method for that path does not exist in the specification", |
| 37 |
request.Method, request.URL.Path, request.Method), |
| 38 |
SpecLine: -1, |
| 39 |
SpecCol: -1, |
| 40 |
HowToFix: errors.HowToFixPath, |
| 41 |
}} |
| 42 |
} |
| 43 |
operation := helpers.ExtractOperation(request, pathItem) |
| 44 |
if operation == nil { |
| 45 |
return false, []*errors.ValidationError{errors.OperationNotFound(pathItem, request, request.Method, pathValue)} |
| 46 |
} |
| 47 |
if operation.RequestBody == nil { |
| 48 |
return true, nil |
| 49 |
} |
| 50 |
|
| 51 |
// extract the content type from the request |
| 52 |
contentType := request.Header.Get(helpers.ContentTypeHeader) |
| 53 |
required := false |
| 54 |
if operation.RequestBody.Required != nil { |
| 55 |
required = *operation.RequestBody.Required |
| 56 |
} |
| 57 |
if contentType == "" { |
| 58 |
if !required { |
| 59 |
// request body is not required, the validation stop there. |
| 60 |
return true, nil |
| 61 |
} |
| 62 |
return false, []*errors.ValidationError{errors.RequestContentTypeNotFound(operation, request, pathValue)} |
| 63 |
} |
| 64 |
|
| 65 |
// extract the media type from the content type header. |
| 66 |
mediaType, ok := v.extractContentType(contentType, operation) |
| 67 |
if !ok { |
| 68 |
return false, []*errors.ValidationError{errors.RequestContentTypeNotFound(operation, request, pathValue)} |
| 69 |
} |
| 70 |
|
| 71 |
// Nothing to validate |
| 72 |
if mediaType.Schema == nil { |
| 73 |
return true, nil |
| 74 |
} |
| 75 |
|
| 76 |
// extract schema from media type |
| 77 |
schema := mediaType.Schema.Schema() |
| 78 |
|
| 79 |
isJson := strings.Contains(strings.ToLower(contentType), helpers.JSONType) |
| 80 |
|
| 81 |
// we currently only support JSON, XML and URLEncoded validation for request bodies |
| 82 |
if !isJson { |
| 83 |
isXml := schema_validation.IsXMLContentType(contentType) |
| 84 |
isUrlEncoded := schema_validation.IsURLEncodedContentType(contentType) |
| 85 |
|
| 86 |
xmlValid := isXml && v.options.AllowXMLBodyValidation |
| 87 |
urlEncodedValid := isUrlEncoded && v.options.AllowURLEncodedBodyValidation |
| 88 |
|
| 89 |
if !xmlValid && !urlEncodedValid { |
| 90 |
return true, nil |
| 91 |
} |
| 92 |
|
| 93 |
if request != nil && (request.Body != nil || request.GetBody != nil) { |
| 94 |
requestBody := readAndResetRequestBody(request) |
| 95 |
stringedBody := string(requestBody) |
| 96 |
var jsonBody any |
| 97 |
var prevalidationErrors []*errors.ValidationError |
| 98 |
|
| 99 |
switch { |
| 100 |
case xmlValid: |
| 101 |
jsonBody, prevalidationErrors = schema_validation.TransformXMLToSchemaJSON(stringedBody, schema) |
| 102 |
case urlEncodedValid: |
| 103 |
jsonBody, prevalidationErrors = schema_validation.TransformURLEncodedToSchemaJSON(stringedBody, schema, mediaType.Encoding) |
| 104 |
} |
| 105 |
|
| 106 |
if len(prevalidationErrors) > 0 { |
| 107 |
return false, prevalidationErrors |
| 108 |
} |
| 109 |
|
| 110 |
transformedBytes, err := json.Marshal(jsonBody) |
| 111 |
if err != nil { |
| 112 |
switch { |
| 113 |
case isXml: |
| 114 |
return false, []*errors.ValidationError{errors.InvalidXMLParsing(err.Error(), stringedBody)} |
| 115 |
case isUrlEncoded: |
| 116 |
return false, []*errors.ValidationError{errors.InvalidURLEncodedParsing(err.Error(), stringedBody)} |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
setRequestBody(request, transformedBytes) |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
validationSucceeded, validationErrors := ValidateRequestSchema(&ValidateRequestSchemaInput{ |
| 125 |
Request: request, |
| 126 |
Schema: schema, |
| 127 |
Version: helpers.VersionToFloat(v.document.Version), |
| 128 |
Options: []config.Option{config.WithExistingOpts(v.options)}, |
| 129 |
BodyRequired: required, |
| 130 |
}) |
| 131 |
|
| 132 |
errors.PopulateValidationErrors(validationErrors, request, pathValue) |
| 133 |
|
| 134 |
return validationSucceeded, validationErrors |
| 135 |
} |
| 136 |
|
| 137 |
func (v *requestBodyValidator) extractContentType(contentType string, operation *v3.Operation) (*v3.MediaType, bool) { |
| 138 |
ct, _, _ := helpers.ExtractContentType(contentType) |
| 139 |
mediaType, ok := operation.RequestBody.Content.Get(ct) |
| 140 |
if ok { |
| 141 |
return mediaType, true |
| 142 |
} |
| 143 |
ctMediaRange := strings.SplitN(ct, "/", 2) |
| 144 |
for contentPair := operation.RequestBody.Content.First(); contentPair != nil; contentPair = contentPair.Next() { |
| 145 |
s := contentPair.Key() |
| 146 |
mediaTypeValue := contentPair.Value() |
| 147 |
opMediaRange := strings.SplitN(s, "/", 2) |
| 148 |
if (opMediaRange[0] == "*" || opMediaRange[0] == ctMediaRange[0]) && |
| 149 |
(opMediaRange[1] == "*" || opMediaRange[1] == ctMediaRange[1]) { |
| 150 |
return mediaTypeValue, true |
| 151 |
} |
| 152 |
} |
| 153 |
return nil, false |
| 154 |
} |