agent: intention create returns 500 for bad body

This commit is contained in:
Mitchell Hashimoto 2018-06-05 11:09:45 -07:00 committed by Jack Pearkes
parent 62512adb84
commit e3562e39cc
3 changed files with 22 additions and 3 deletions

View File

@ -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 {

View File

@ -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

View File

@ -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()