Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merging to release-5-lts: [TT-10438] add date, date-time validation hooks for validate request on kin-openapi3 (#5980) #5992

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions gateway/mw_oas_validate_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,26 @@ import (
"context"
"fmt"
"net/http"
"time"

"github.com/getkin/kin-openapi/openapi3"

"github.com/getkin/kin-openapi/openapi3filter"
)

const dateOnlyTimeLayout = "2006-01-02"

func init() {
openapi3.SchemaErrorDetailsDisabled = true
openapi3.DefineStringFormatCallback("date-time", func(value string) error {
_, err := time.Parse(time.RFC3339, value)
return err
})

openapi3.DefineStringFormatCallback("date", func(value string) error {
_, err := time.Parse(dateOnlyTimeLayout, value)
return err
})
}

type ValidateRequest struct {
Expand Down
22 changes: 22 additions & 0 deletions gateway/mw_oas_validate_request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ const testOASForValidateRequest = `{
},
"owner": {
"$ref": "#/components/schemas/Owner"
},
"createdAt": {
"type": "string",
"format": "date-time"
},
"expiryOn": {
"type": "string",
"format": "date"
}
}
}
Expand Down Expand Up @@ -178,6 +186,20 @@ func TestValidateRequest(t *testing.T) {
ts.Gw.LoadAPI(apis...)
check(t)
})

t.Run("validate date/date-time format", func(t *testing.T) {
apiPath := "/product/post"
_, _ = ts.Run(t, []test.TestCase{
{Data: `{"name": "123", "createdAt": "2016-02-30T14:30:15Z"}`, Code: http.StatusUnprocessableEntity,
Method: http.MethodPost, Headers: headers, Path: apiPath},
{Data: `{"name": "123", "createdAt": "2016-02-28T30:30:15Z"}`, Code: http.StatusUnprocessableEntity,
Method: http.MethodPost, Headers: headers, Path: apiPath},
{Data: `{"name": "123", "createdAt": "2016-02-28T12:30:15Z"}`, Code: http.StatusOK,
Method: http.MethodPost, Headers: headers, Path: apiPath},
{Data: `{"name": "123", "expiryOn": "2016-02-28"}`, Code: http.StatusOK,
Method: http.MethodPost, Headers: headers, Path: apiPath},
}...)
})
})

t.Run("custom error response code", func(t *testing.T) {
Expand Down
Loading