Skip to content

Commit

Permalink
transport/http2: use HTTP 400 for bad requests instead of 500
Browse files Browse the repository at this point in the history
Non-servicable HTTP requests from clients previously resulted in an HTTP
500 response, but no error exists within the server; the client simply
sent a malformed request. Detect bad requests and return HTTP 400 Bad
Request instead of HTTP 500 Internal Server Error.

fixes #5802
  • Loading branch information
sjbarag committed Nov 18, 2022
1 parent 817c1e8 commit 4fb92d6
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
8 changes: 7 additions & 1 deletion internal/transport/handler_server.go
Expand Up @@ -46,6 +46,12 @@ import (
"google.golang.org/grpc/status"
)

// ErrInvalidWriter indicates that the provided http.ResponseWriter doesn't
// support http.Flusher. Since this is typically a server-side error,
// ErrInvalidWriter is intended for use in differentiating bad requests from
// internal errors.
var ErrInvalidWriter = errors.New("gRPC requires a ResponseWriter supporting http.Flusher")

// NewServerHandlerTransport returns a ServerTransport handling gRPC
// from inside an http.Handler. It requires that the http Server
// supports HTTP/2.
Expand All @@ -63,7 +69,7 @@ func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats []s
return nil, errors.New("invalid gRPC request content-type")
}
if _, ok := w.(http.Flusher); !ok {
return nil, errors.New("gRPC requires a ResponseWriter supporting http.Flusher")
return nil, ErrInvalidWriter
}

st := &serverHandlerTransport{
Expand Down
6 changes: 5 additions & 1 deletion server.go
Expand Up @@ -1008,7 +1008,11 @@ var _ http.Handler = (*Server)(nil)
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
st, err := transport.NewServerHandlerTransport(w, r, s.opts.statsHandlers)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
var status = http.StatusBadRequest
if err == transport.ErrInvalidWriter {
status = http.StatusInternalServerError
}
http.Error(w, err.Error(), status)
return
}
if !s.addConn(listenerAddressForServeHTTP, st) {
Expand Down

0 comments on commit 4fb92d6

Please sign in to comment.