Skip to content

fix: return HTTP 405 when request method mismatch #25

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

Merged
merged 5 commits into from
Apr 24, 2025
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
13 changes: 13 additions & 0 deletions internal/test/chi/oapi_validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,19 @@ func testRequestValidatorBasicFunctions(t *testing.T, r *chi.Mux) {
called = false
}

// Send a request with wrong HTTP method
{
body := struct {
Name string `json:"name"`
}{
Name: "Marcin",
}
rec := doPost(t, r, "http://deepmap.ai/resource", body)
assert.Equal(t, http.StatusMethodNotAllowed, rec.Code)
assert.False(t, called, "Handler should not have been called")
called = false
}

// Add a handler for the POST message
r.Post("/resource", func(w http.ResponseWriter, r *http.Request) {
called = true
Expand Down
13 changes: 13 additions & 0 deletions internal/test/gorilla/oapi_validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,19 @@ func testRequestValidatorBasicFunctions(t *testing.T, r *mux.Router) {
called = false
}

// Send a request with wrong HTTP method
{
body := struct {
Name string `json:"name"`
}{
Name: "Marcin",
}
rec := doPost(t, r, "http://deepmap.ai/resource", body)
assert.Equal(t, http.StatusMethodNotAllowed, rec.Code)
assert.False(t, called, "Handler should not have been called")
called = false
}

// Add a handler for the POST message
r.HandleFunc("/resource", func(w http.ResponseWriter, r *http.Request) {
called = true
Expand Down
34 changes: 34 additions & 0 deletions internal/test/nethttp/oapi_validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,27 @@ func doPost(t *testing.T, mux http.Handler, rawURL string, jsonBody interface{})
return rr
}

func doPatch(t *testing.T, mux http.Handler, rawURL string, jsonBody interface{}) *httptest.ResponseRecorder {
u, err := url.Parse(rawURL)
if err != nil {
t.Fatalf("Invalid url: %s", rawURL)
}

data, err := json.Marshal(jsonBody)
require.NoError(t, err)

req, err := http.NewRequest(http.MethodPatch, u.String(), bytes.NewReader(data))
require.NoError(t, err)

req.Header.Set("content-type", "application/json")

rr := httptest.NewRecorder()

mux.ServeHTTP(rr, req)

return rr
}

// use wraps a given http.ServeMux with middleware for execution
func use(r *http.ServeMux, mw func(next http.Handler) http.Handler) http.Handler {
return mw(r)
Expand Down Expand Up @@ -434,6 +455,19 @@ func testRequestValidatorBasicFunctions(t *testing.T, r *http.ServeMux, mw func(
called = false
}

// Send a request with wrong method
{
body := struct {
Name string `json:"name"`
}{
Name: "Marcin",
}
rec := doPatch(t, server, "http://deepmap.ai/resource", body)
assert.Equal(t, http.StatusMethodNotAllowed, rec.Code)
assert.False(t, called, "Handler should not have been called")
called = false
}

called = false
// Send a good request body
{
Expand Down
4 changes: 4 additions & 0 deletions oapi_validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ func validateRequest(r *http.Request, router routers.Router, options *Options) (
// Find route
route, pathParams, err := router.FindRoute(r)
if err != nil {
if errors.Is(err, routers.ErrMethodNotAllowed) {
return http.StatusMethodNotAllowed, err
}

return http.StatusNotFound, err // We failed to find a matching route for the request.
}

Expand Down
25 changes: 25 additions & 0 deletions oapi_validate_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,27 @@ components:
logResponseBody(rr)
fmt.Println()

// ================================================================================
fmt.Println("# A request with an invalid HTTP method, to a valid path, is rejected with an HTTP 405 Method Not Allowed")
body = map[string]string{
"invalid": "not expected",
}

data, err = json.Marshal(body)
must(err)

req, err = http.NewRequest(http.MethodPatch, "/resource", bytes.NewReader(data))
must(err)
req.Header.Set("Content-Type", "application/json")

rr = httptest.NewRecorder()

server.ServeHTTP(rr, req)

fmt.Printf("Received an HTTP %d response. Expected HTTP 405\n", rr.Code)
logResponseBody(rr)
fmt.Println()

// ================================================================================
fmt.Println("# A request that is well-formed is passed through to the Handler")
body = map[string]string{
Expand Down Expand Up @@ -207,6 +228,10 @@ components:
// Received an HTTP 400 response. Expected HTTP 400
// Response body: request body has an error: doesn't match schema: property "invalid" is unsupported
//
// # A request with an invalid HTTP method, to a valid path, is rejected with an HTTP 405 Method Not Allowed
// Received an HTTP 405 response. Expected HTTP 405
// Response body: method not allowed
//
// # A request that is well-formed is passed through to the Handler
// POST /resource was called
// Received an HTTP 204 response. Expected HTTP 204
Expand Down