Skip to content

Commit 70fbd7b

Browse files
author
Mark Pierce
committed
feat: support rejecting when request body present but not required by specification
1 parent 8933711 commit 70fbd7b

File tree

3 files changed

+22
-5
lines changed

3 files changed

+22
-5
lines changed

.github/docs/openapi3filter.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,9 @@ type Options struct {
238238
// Set RegexCompiler to override the regex implementation
239239
RegexCompiler openapi3.RegexCompilerFunc
240240

241+
// Set RejectWhenRequestBodyNotSpecified so ValidateRequest fails when request body is present but not defined in the specification
242+
RejectWhenRequestBodyNotSpecified bool
243+
241244
// A document with security schemes defined will not pass validation
242245
// unless an AuthenticationFunc is defined.
243246
// See NoopAuthenticationFunc

openapi3filter/options.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ type Options struct {
2828
// Set RegexCompiler to override the regex implementation
2929
RegexCompiler openapi3.RegexCompilerFunc
3030

31+
// Set RejectWhenRequestBodyNotSpecified so ValidateRequest fails when request body is present but not defined in the specification
32+
RejectWhenRequestBodyNotSpecified bool
33+
3134
// A document with security schemes defined will not pass validation
3235
// unless an AuthenticationFunc is defined.
3336
// See NoopAuthenticationFunc

openapi3filter/validate_request.go

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -90,12 +90,23 @@ func ValidateRequest(ctx context.Context, input *RequestValidationInput) error {
9090

9191
// RequestBody
9292
requestBody := operation.RequestBody
93-
if requestBody != nil && !options.ExcludeRequestBody {
94-
if err := ValidateRequestBody(ctx, input, requestBody.Value); err != nil {
95-
if !options.MultiError {
96-
return err
93+
if !options.ExcludeRequestBody {
94+
// Validate specification request body if present
95+
if requestBody != nil {
96+
if err := ValidateRequestBody(ctx, input, requestBody.Value); err != nil {
97+
if !options.MultiError {
98+
return err
99+
}
100+
me = append(me, err)
101+
}
102+
}
103+
104+
// Reject if specification request body if not present (not wanted) but is present in the HTTP request
105+
if options.RejectWhenRequestBodyNotSpecified && input.Request.ContentLength > 0 {
106+
return &RequestError{
107+
Input: input,
108+
Err: fmt.Errorf("request body not allowed for this request"),
97109
}
98-
me = append(me, err)
99110
}
100111
}
101112

0 commit comments

Comments
 (0)