| 1 |
// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
package requests |
| 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 |
// ValidateRequestSchemaInput contains parameters for request schema validation. |
| 35 |
type ValidateRequestSchemaInput struct { |
| 36 |
Request *http.Request // Required: The HTTP request to validate |
| 37 |
Schema *base.Schema // Required: The OpenAPI schema to validate against |
| 38 |
Version float32 // Required: OpenAPI version (3.0 or 3.1) |
| 39 |
Options []config.Option // Optional: Functional options (defaults applied if empty/nil) |
| 40 |
BodyRequired bool // Optional: Whether the request body is required (default false) |
| 41 |
} |
| 42 |
|
| 43 |
type replayableBody interface { |
| 44 |
io.ReaderAt |
| 45 |
Size() int64 |
| 46 |
} |
| 47 |
|
| 48 |
func setRequestBody(request *http.Request, body []byte) { |
| 49 |
if request == nil { |
| 50 |
return |
| 51 |
} |
| 52 |
bodyCopy := append([]byte(nil), body...) |
| 53 |
request.Body = io.NopCloser(bytes.NewReader(bodyCopy)) |
| 54 |
request.ContentLength = int64(len(bodyCopy)) |
| 55 |
request.GetBody = func() (io.ReadCloser, error) { |
| 56 |
return io.NopCloser(bytes.NewReader(bodyCopy)), nil |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
func requestBodySnapshot(request *http.Request) ([]byte, bool) { |
| 61 |
if request == nil || request.Body == nil || request.Body == http.NoBody { |
| 62 |
return nil, false |
| 63 |
} |
| 64 |
reader := requestBodyReader(request.Body) |
| 65 |
body, ok := reader.(replayableBody) |
| 66 |
if !ok { |
| 67 |
return nil, false |
| 68 |
} |
| 69 |
size := body.Size() |
| 70 |
if size <= 0 { |
| 71 |
return nil, false |
| 72 |
} |
| 73 |
snapshot, err := io.ReadAll(io.NewSectionReader(body, 0, size)) |
| 74 |
if err != nil { |
| 75 |
return nil, false |
| 76 |
} |
| 77 |
return snapshot, true |
| 78 |
} |
| 79 |
|
| 80 |
func requestBodyReader(body io.ReadCloser) io.Reader { |
| 81 |
if body == nil || body == http.NoBody { |
| 82 |
return nil |
| 83 |
} |
| 84 |
|
| 85 |
value := reflect.ValueOf(body) |
| 86 |
if value.Kind() == reflect.Ptr { |
| 87 |
if value.IsNil() { |
| 88 |
return nil |
| 89 |
} |
| 90 |
value = value.Elem() |
| 91 |
} |
| 92 |
if value.Kind() == reflect.Struct { |
| 93 |
field := value.FieldByName("Reader") |
| 94 |
if field.IsValid() && field.CanInterface() { |
| 95 |
if reader, ok := field.Interface().(io.Reader); ok { |
| 96 |
return reader |
| 97 |
} |
| 98 |
} |
| 99 |
} |
| 100 |
return body |
| 101 |
} |
| 102 |
|
| 103 |
func readAndResetRequestBody(request *http.Request) []byte { |
| 104 |
if request == nil { |
| 105 |
return nil |
| 106 |
} |
| 107 |
|
| 108 |
var requestBody []byte |
| 109 |
bodyRead := false |
| 110 |
bodySnapshot, hasBodySnapshot := requestBodySnapshot(request) |
| 111 |
if request.Body != nil { |
| 112 |
requestBody, _ = io.ReadAll(request.Body) |
| 113 |
_ = request.Body.Close() |
| 114 |
bodyRead = true |
| 115 |
} |
| 116 |
|
| 117 |
if len(requestBody) == 0 && hasBodySnapshot && request.GetBody != nil { |
| 118 |
if body, err := request.GetBody(); err == nil && body != nil { |
| 119 |
replayedBody, _ := io.ReadAll(body) |
| 120 |
_ = body.Close() |
| 121 |
if bytes.Equal(replayedBody, bodySnapshot) { |
| 122 |
requestBody = replayedBody |
| 123 |
bodyRead = true |
| 124 |
} |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
if bodyRead { |
| 129 |
setRequestBody(request, requestBody) |
| 130 |
} |
| 131 |
return requestBody |
| 132 |
} |
| 133 |
|
| 134 |
// ValidateRequestSchema will validate a http.Request pointer against a schema. |
| 135 |
// If validation fails, it will return a list of validation errors as the second return value. |
| 136 |
// The schema will be stored and reused from cache if available, otherwise it will be compiled on each call. |
| 137 |
func ValidateRequestSchema(input *ValidateRequestSchemaInput) (bool, []*liberrors.ValidationError) { |
| 138 |
validationOptions := config.NewValidationOptions(input.Options...) |
| 139 |
var validationErrors []*liberrors.ValidationError |
| 140 |
var renderedSchema, jsonSchema []byte |
| 141 |
var referenceSchema string |
| 142 |
var compiledSchema *jsonschema.Schema |
| 143 |
var cachedNode *yaml.Node |
| 144 |
|
| 145 |
if input.Schema == nil { |
| 146 |
return false, []*liberrors.ValidationError{{ |
| 147 |
ValidationType: helpers.RequestBodyValidation, |
| 148 |
ValidationSubType: helpers.Schema, |
| 149 |
Message: "schema is nil", |
| 150 |
Reason: "The schema to validate against is nil", |
| 151 |
}} |
| 152 |
} else if input.Schema.GoLow() == nil { |
| 153 |
return false, []*liberrors.ValidationError{{ |
| 154 |
ValidationType: helpers.RequestBodyValidation, |
| 155 |
ValidationSubType: helpers.Schema, |
| 156 |
Message: "schema cannot be rendered", |
| 157 |
Reason: "The schema does not have low-level information and cannot be rendered. Please ensure the schema is loaded from a document.", |
| 158 |
}} |
| 159 |
} |
| 160 |
|
| 161 |
if validationOptions.SchemaCache != nil { |
| 162 |
hash := input.Schema.GoLow().Hash() |
| 163 |
if cached, ok := validationOptions.SchemaCache.Load(hash); ok && cached != nil && cached.CompiledSchema != nil { |
| 164 |
renderedSchema = cached.RenderedInline |
| 165 |
referenceSchema = cached.ReferenceSchema |
| 166 |
jsonSchema = cached.RenderedJSON |
| 167 |
compiledSchema = cached.CompiledSchema |
| 168 |
cachedNode = cached.RenderedNode |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
// Cache miss or no cache - render and compile |
| 173 |
if compiledSchema == nil { |
| 174 |
renderCtx := base.NewInlineRenderContextForValidation() |
| 175 |
var renderErr error |
| 176 |
renderedSchema, renderErr = input.Schema.RenderInlineWithContext(renderCtx) |
| 177 |
referenceSchema = string(renderedSchema) |
| 178 |
|
| 179 |
// If rendering failed (e.g., circular reference), return the render error |
| 180 |
if renderErr != nil { |
| 181 |
violation := &liberrors.SchemaValidationFailure{ |
| 182 |
Reason: renderErr.Error(), |
| 183 |
ReferenceSchema: referenceSchema, |
| 184 |
} |
| 185 |
validationErrors = append(validationErrors, &liberrors.ValidationError{ |
| 186 |
ValidationType: helpers.RequestBodyValidation, |
| 187 |
ValidationSubType: helpers.Schema, |
| 188 |
Message: fmt.Sprintf("%s request body for '%s' failed schema rendering", |
| 189 |
input.Request.Method, input.Request.URL.Path), |
| 190 |
Reason: fmt.Sprintf("The request schema failed to render: %s", |
| 191 |
renderErr.Error()), |
| 192 |
SpecLine: 1, |
| 193 |
SpecCol: 0, |
| 194 |
SchemaValidationErrors: []*liberrors.SchemaValidationFailure{violation}, |
| 195 |
HowToFix: liberrors.HowToFixInvalidRenderedSchema, |
| 196 |
Context: referenceSchema, |
| 197 |
}) |
| 198 |
return false, validationErrors |
| 199 |
} |
| 200 |
|
| 201 |
jsonSchema, _ = utils.ConvertYAMLtoJSON(renderedSchema) |
| 202 |
|
| 203 |
var err error |
| 204 |
schemaName := fmt.Sprintf("%x", input.Schema.GoLow().Hash()) |
| 205 |
compiledSchema, err = helpers.NewCompiledSchemaWithVersion( |
| 206 |
schemaName, |
| 207 |
jsonSchema, |
| 208 |
validationOptions, |
| 209 |
input.Version, |
| 210 |
) |
| 211 |
if err != nil { |
| 212 |
validationErrors = append(validationErrors, &liberrors.ValidationError{ |
| 213 |
ValidationType: helpers.RequestBodyValidation, |
| 214 |
ValidationSubType: helpers.Schema, |
| 215 |
Message: fmt.Sprintf("%s request body for '%s' failed schema compilation", |
| 216 |
input.Request.Method, input.Request.URL.Path), |
| 217 |
Reason: fmt.Sprintf("The request schema failed to compile: %s", err.Error()), |
| 218 |
SpecLine: 1, |
| 219 |
SpecCol: 0, |
| 220 |
HowToFix: "check the request schema for invalid JSON Schema syntax, complex regex patterns, or unsupported schema constructs", |
| 221 |
Context: input.Schema, |
| 222 |
}) |
| 223 |
return false, validationErrors |
| 224 |
} |
| 225 |
|
| 226 |
if validationOptions.SchemaCache != nil { |
| 227 |
hash := input.Schema.GoLow().Hash() |
| 228 |
validationOptions.SchemaCache.Store(hash, &cache.SchemaCacheEntry{ |
| 229 |
Schema: input.Schema, |
| 230 |
RenderedInline: renderedSchema, |
| 231 |
ReferenceSchema: referenceSchema, |
| 232 |
RenderedJSON: jsonSchema, |
| 233 |
CompiledSchema: compiledSchema, |
| 234 |
}) |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
request := input.Request |
| 239 |
schema := input.Schema |
| 240 |
|
| 241 |
requestBody := readAndResetRequestBody(request) |
| 242 |
|
| 243 |
var decodedObj interface{} |
| 244 |
|
| 245 |
if len(requestBody) > 0 { |
| 246 |
err := json.Unmarshal(requestBody, &decodedObj) |
| 247 |
if err != nil { |
| 248 |
// cannot decode the request body, so it's not valid |
| 249 |
validationErrors = append(validationErrors, &liberrors.ValidationError{ |
| 250 |
ValidationType: helpers.RequestBodyValidation, |
| 251 |
ValidationSubType: helpers.Schema, |
| 252 |
Message: fmt.Sprintf("%s request body for '%s' failed to validate schema", |
| 253 |
request.Method, request.URL.Path), |
| 254 |
Reason: fmt.Sprintf("The request body cannot be decoded: %s", err.Error()), |
| 255 |
SpecLine: 1, |
| 256 |
SpecCol: 0, |
| 257 |
HowToFix: liberrors.HowToFixInvalidSchema, |
| 258 |
Context: schema, |
| 259 |
}) |
| 260 |
return false, validationErrors |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
// no request body? but we do have a schema? |
| 265 |
if len(requestBody) == 0 && len(jsonSchema) > 0 { |
| 266 |
if !input.BodyRequired { |
| 267 |
return true, nil |
| 268 |
} |
| 269 |
|
| 270 |
line := 1 |
| 271 |
col := 0 |
| 272 |
if schema.ParentProxy != nil { |
| 273 |
if keyNode := schema.ParentProxy.GetSchemaKeyNode(); keyNode != nil { |
| 274 |
line = keyNode.Line |
| 275 |
col = keyNode.Column |
| 276 |
} |
| 277 |
} |
| 278 |
if schema.Type != nil { |
| 279 |
if low := schema.GoLow(); low != nil && low.Type.KeyNode != nil { |
| 280 |
line = low.Type.KeyNode.Line |
| 281 |
col = low.Type.KeyNode.Column |
| 282 |
} |
| 283 |
} |
| 284 |
|
| 285 |
validationErrors = append(validationErrors, &liberrors.ValidationError{ |
| 286 |
ValidationType: helpers.RequestBodyValidation, |
| 287 |
ValidationSubType: helpers.Schema, |
| 288 |
Message: fmt.Sprintf("%s request body is empty for '%s'", |
| 289 |
request.Method, request.URL.Path), |
| 290 |
Reason: "The request body is empty but there is a schema defined", |
| 291 |
SpecLine: line, |
| 292 |
SpecCol: col, |
| 293 |
HowToFix: liberrors.HowToFixInvalidSchema, |
| 294 |
Context: schema, |
| 295 |
}) |
| 296 |
return false, validationErrors |
| 297 |
} |
| 298 |
|
| 299 |
// validate the object against the schema |
| 300 |
scErrs := compiledSchema.Validate(decodedObj) |
| 301 |
if scErrs != nil { |
| 302 |
var jk *jsonschema.ValidationError |
| 303 |
var schemaValidationErrors []*liberrors.SchemaValidationFailure |
| 304 |
|
| 305 |
if errors.As(scErrs, &jk) { |
| 306 |
// flatten the validationErrors |
| 307 |
schFlatErrs := jk.BasicOutput().Errors |
| 308 |
|
| 309 |
// Use cached node if available, otherwise parse |
| 310 |
renderedNode := cachedNode |
| 311 |
if renderedNode == nil { |
| 312 |
renderedNode = new(yaml.Node) |
| 313 |
_ = yaml.Unmarshal(renderedSchema, renderedNode) |
| 314 |
} |
| 315 |
for q := range schFlatErrs { |
| 316 |
er := schFlatErrs[q] |
| 317 |
|
| 318 |
errMsg := er.Error.Kind.LocalizedString(message.NewPrinter(language.Tag{})) |
| 319 |
|
| 320 |
if er.KeywordLocation == "" || helpers.IgnoreRegex.MatchString(errMsg) { |
| 321 |
continue // ignore this error, it's useless tbh, utter noise. |
| 322 |
} |
| 323 |
if er.Error != nil { |
| 324 |
|
| 325 |
// locate the violated property in the schema |
| 326 |
var located *yaml.Node |
| 327 |
if len(renderedNode.Content) > 0 { |
| 328 |
located = schema_validation.LocateSchemaPropertyNodeByJSONPath(renderedNode.Content[0], er.KeywordLocation) |
| 329 |
} |
| 330 |
|
| 331 |
// extract the element specified by the instance |
| 332 |
val := instanceLocationRegex.FindStringSubmatch(er.InstanceLocation) |
| 333 |
var referenceObject string |
| 334 |
|
| 335 |
if len(val) > 0 { |
| 336 |
referenceIndex, _ := strconv.Atoi(val[1]) |
| 337 |
if reflect.ValueOf(decodedObj).Type().Kind() == reflect.Slice { |
| 338 |
found := decodedObj.([]any)[referenceIndex] |
| 339 |
recoded, _ := json.MarshalIndent(found, "", " ") |
| 340 |
referenceObject = string(recoded) |
| 341 |
} |
| 342 |
} |
| 343 |
if referenceObject == "" { |
| 344 |
referenceObject = string(requestBody) |
| 345 |
} |
| 346 |
|
| 347 |
errMsg := er.Error.Kind.LocalizedString(message.NewPrinter(language.Tag{})) |
| 348 |
|
| 349 |
violation := &liberrors.SchemaValidationFailure{ |
| 350 |
Reason: errMsg, |
| 351 |
FieldName: helpers.ExtractFieldNameFromStringLocation(er.InstanceLocation), |
| 352 |
FieldPath: helpers.ExtractJSONPathFromStringLocation(er.InstanceLocation), |
| 353 |
InstancePath: helpers.ConvertStringLocationToPathSegments(er.InstanceLocation), |
| 354 |
KeywordLocation: er.KeywordLocation, |
| 355 |
ReferenceSchema: referenceSchema, |
| 356 |
ReferenceObject: referenceObject, |
| 357 |
OriginalJsonSchemaError: jk, |
| 358 |
} |
| 359 |
// if we have a location within the schema, add it to the error |
| 360 |
if located != nil { |
| 361 |
|
| 362 |
line := located.Line |
| 363 |
// if the located node is a map or an array, then the actual human interpretable |
| 364 |
// line on which the violation occurred is the line of the key, not the value. |
| 365 |
if located.Kind == yaml.MappingNode || located.Kind == yaml.SequenceNode { |
| 366 |
if line > 0 { |
| 367 |
line-- |
| 368 |
} |
| 369 |
} |
| 370 |
|
| 371 |
// location of the violation within the rendered schema. |
| 372 |
violation.Line = line |
| 373 |
violation.Column = located.Column |
| 374 |
} |
| 375 |
schemaValidationErrors = append(schemaValidationErrors, violation) |
| 376 |
} |
| 377 |
} |
| 378 |
} |
| 379 |
|
| 380 |
line := 1 |
| 381 |
col := 0 |
| 382 |
if low := schema.GoLow(); low != nil && low.Type.KeyNode != nil { |
| 383 |
line = low.Type.KeyNode.Line |
| 384 |
col = low.Type.KeyNode.Column |
| 385 |
} |
| 386 |
|
| 387 |
// add the error to the list |
| 388 |
validationErrors = append(validationErrors, &liberrors.ValidationError{ |
| 389 |
ValidationType: helpers.RequestBodyValidation, |
| 390 |
ValidationSubType: helpers.Schema, |
| 391 |
Message: fmt.Sprintf("%s request body for '%s' failed to validate schema", |
| 392 |
request.Method, request.URL.Path), |
| 393 |
Reason: "The request body is defined as an object. " + |
| 394 |
"However, it does not meet the schema requirements of the specification", |
| 395 |
SpecLine: line, |
| 396 |
SpecCol: col, |
| 397 |
SchemaValidationErrors: schemaValidationErrors, |
| 398 |
HowToFix: liberrors.HowToFixInvalidSchema, |
| 399 |
Context: schema, |
| 400 |
}) |
| 401 |
} |
| 402 |
if len(validationErrors) > 0 { |
| 403 |
return false, validationErrors |
| 404 |
} |
| 405 |
|
| 406 |
// strict mode: check for undeclared properties in request body |
| 407 |
if validationOptions.StrictMode && decodedObj != nil { |
| 408 |
strictValidator := strict.NewValidator(validationOptions, input.Version) |
| 409 |
strictResult := strictValidator.Validate(strict.Input{ |
| 410 |
Schema: schema, |
| 411 |
Data: decodedObj, |
| 412 |
Direction: strict.DirectionRequest, |
| 413 |
Options: validationOptions, |
| 414 |
BasePath: "$.body", |
| 415 |
Version: input.Version, |
| 416 |
}) |
| 417 |
|
| 418 |
if !strictResult.Valid { |
| 419 |
for _, undeclared := range strictResult.UndeclaredValues { |
| 420 |
switch undeclared.Type { |
| 421 |
case strict.TypeReadOnlyProperty: |
| 422 |
validationErrors = append(validationErrors, |
| 423 |
liberrors.ReadOnlyPropertyError( |
| 424 |
undeclared.Path, undeclared.Name, undeclared.Value, |
| 425 |
request.URL.Path, request.Method, |
| 426 |
undeclared.SpecLine, undeclared.SpecCol, |
| 427 |
)) |
| 428 |
default: |
| 429 |
validationErrors = append(validationErrors, |
| 430 |
liberrors.UndeclaredPropertyError( |
| 431 |
undeclared.Path, |
| 432 |
undeclared.Name, |
| 433 |
undeclared.Value, |
| 434 |
undeclared.DeclaredProperties, |
| 435 |
undeclared.Direction.String(), |
| 436 |
request.URL.Path, |
| 437 |
request.Method, |
| 438 |
undeclared.SpecLine, |
| 439 |
undeclared.SpecCol, |
| 440 |
)) |
| 441 |
} |
| 442 |
} |
| 443 |
} |
| 444 |
} |
| 445 |
|
| 446 |
if len(validationErrors) > 0 { |
| 447 |
return false, validationErrors |
| 448 |
} |
| 449 |
return true, nil |
| 450 |
} |