agent: intention create returns 500 for bad body

pull/4275/head
Mitchell Hashimoto 2018-06-05 11:09:45 -07:00 committed by Jack Pearkes
parent 297e4f272e
commit 8bcadddda7
3 changed files with 22 additions and 3 deletions

View File

@ -3,6 +3,7 @@ package agent
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"net" "net"
"net/http" "net/http"
"net/http/pprof" "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 // decodeBody is used to decode a JSON request body
func decodeBody(req *http.Request, out interface{}, cb func(interface{}) error) error { 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{} var raw interface{}
dec := json.NewDecoder(req.Body) dec := json.NewDecoder(req.Body)
if err := dec.Decode(&raw); err != nil { 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.parseDC(req, &args.Datacenter)
s.parseToken(req, &args.Token) s.parseToken(req, &args.Token)
if err := decodeBody(req, &args.Intention, nil); err != nil { if err := decodeBody(req, &args.Intention, nil); err != nil {
resp.WriteHeader(http.StatusBadRequest) return nil, fmt.Errorf("Failed to decode request body: %s", err)
fmt.Fprintf(resp, "Request decode failed: %v", err)
return nil, nil
} }
var reply string 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) { func TestIntentionsSpecificGet_good(t *testing.T) {
t.Parallel() t.Parallel()