diff --git a/agent/http.go b/agent/http.go index b9791232d..3e95a9722 100644 --- a/agent/http.go +++ b/agent/http.go @@ -3,6 +3,7 @@ package agent import ( "encoding/json" "fmt" + "io" "net" "net/http" "net/http/pprof" @@ -384,6 +385,13 @@ func (s *HTTPServer) Index(resp http.ResponseWriter, req *http.Request) { // decodeBody is used to decode a JSON request body func decodeBody(req *http.Request, out interface{}, cb func(interface{}) error) error { + // This generally only happens in tests since real HTTP requests set + // a non-nil body with no content. We guard against it anyways to prevent + // a panic. The EOF response is the same behavior as an empty reader. + if req.Body == nil { + return io.EOF + } + var raw interface{} dec := json.NewDecoder(req.Body) if err := dec.Decode(&raw); err != nil { diff --git a/agent/intentions_endpoint.go b/agent/intentions_endpoint.go index 4720e6f31..8a482f08a 100644 --- a/agent/intentions_endpoint.go +++ b/agent/intentions_endpoint.go @@ -50,9 +50,7 @@ func (s *HTTPServer) IntentionCreate(resp http.ResponseWriter, req *http.Request s.parseDC(req, &args.Datacenter) s.parseToken(req, &args.Token) if err := decodeBody(req, &args.Intention, nil); err != nil { - resp.WriteHeader(http.StatusBadRequest) - fmt.Fprintf(resp, "Request decode failed: %v", err) - return nil, nil + return nil, fmt.Errorf("Failed to decode request body: %s", err) } var reply string diff --git a/agent/intentions_endpoint_test.go b/agent/intentions_endpoint_test.go index 991ab9017..00263a14e 100644 --- a/agent/intentions_endpoint_test.go +++ b/agent/intentions_endpoint_test.go @@ -303,6 +303,19 @@ func TestIntentionsCreate_good(t *testing.T) { } } +func TestIntentionsCreate_noBody(t *testing.T) { + t.Parallel() + + a := NewTestAgent(t.Name(), "") + defer a.Shutdown() + + // Create with no body + req, _ := http.NewRequest("POST", "/v1/connect/intentions", nil) + resp := httptest.NewRecorder() + _, err := a.srv.IntentionCreate(resp, req) + require.Error(t, err) +} + func TestIntentionsSpecificGet_good(t *testing.T) { t.Parallel()