Skip to content

Empty request body is treated as valid and skips validation #1127

@dzherb

Description

@dzherb

It looks like an empty request body is treated as valid even when the OpenAPI schema defines required fields.

Here's an example:

func Test(t *testing.T) {
	specStr := `
openapi: "3.0.0"
info:
  version: 1.0.0
  title: Sample API
components:
  schemas:
    TestRequest:
      type: object
      required: [ field ]
      properties:
        field:
          type: string
paths:
  "/test":
    post:
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/TestRequest"
      responses:
        200:
          description: Successful response
`

	spec, err := openapi3.NewLoader().LoadFromData([]byte(specStr))
	require.NoError(t, err)

	router, err := gorillamux.NewRouter(spec)
	require.NoError(t, err)

	tests := []struct {
		body []byte
	}{
		{body: []byte("{}")}, // this expectedly fails
		{body: []byte("")},   // but this doesn't ???
	}

	for _, testcase := range tests {
		t.Run(string(testcase.body), func(t *testing.T) {
			req, _ := http.NewRequest(
				http.MethodPost,
				"/test",
				bytes.NewBuffer(testcase.body),
			)
			req.Header.Set("Content-Type", "application/json")

			route, pathParams, err := router.FindRoute(req)
			require.NoError(t, err)

			requestValidationInput := &openapi3filter.RequestValidationInput{
				Request:    req,
				PathParams: pathParams,
				Route:      route,
				Options:    &openapi3filter.Options{},
			}

			err = openapi3filter.ValidateRequest(
				context.Background(),
				requestValidationInput,
			)
			require.Error(t, err)
		})
	}
}

Is this intentional behavior?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions