Skip to content

Commit

Permalink
Merge pull request #8013 from hashicorp/gh-8008
Browse files Browse the repository at this point in the history
api: return custom error if API attempts to decode empty body.
  • Loading branch information
jrasell authored May 20, 2020
2 parents 041e251 + 87d51e6 commit 06f0f3a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
6 changes: 6 additions & 0 deletions command/agent/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
Expand Down Expand Up @@ -548,6 +549,11 @@ func isAPIClientError(code int) bool {

// decodeBody is used to decode a JSON request body
func decodeBody(req *http.Request, out interface{}) error {

if req.Body == http.NoBody {
return errors.New("Request body is empty")
}

dec := json.NewDecoder(req.Body)
return dec.Decode(&out)
}
Expand Down
38 changes: 38 additions & 0 deletions command/agent/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -1094,6 +1096,42 @@ func Test_IsAPIClientError(t *testing.T) {
}
}

func Test_decodeBody(t *testing.T) {

testCases := []struct {
inputReq *http.Request
inputOut interface{}
expectedOut interface{}
expectedError error
name string
}{
{
inputReq: &http.Request{Body: http.NoBody},
expectedError: errors.New("Request body is empty"),
name: "empty input request body",
},
{
inputReq: &http.Request{Body: ioutil.NopCloser(strings.NewReader(`{"foo":"bar"}`))},
inputOut: &struct {
Foo string `json:"foo"`
}{},
expectedOut: &struct {
Foo string `json:"foo"`
}{Foo: "bar"},
expectedError: nil,
name: "populated request body and correct out",
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
actualError := decodeBody(tc.inputReq, tc.inputOut)
assert.Equal(t, tc.expectedError, actualError, tc.name)
assert.Equal(t, tc.expectedOut, tc.inputOut, tc.name)
})
}
}

func httpTest(t testing.TB, cb func(c *Config), f func(srv *TestAgent)) {
s := makeHTTPServer(t, cb)
defer s.Shutdown()
Expand Down

0 comments on commit 06f0f3a

Please sign in to comment.