Skip to content

Commit

Permalink
validatorapi: fix content type in http response (#1803)
Browse files Browse the repository at this point in the history
Fixes sending incorrect `Content-Type` header in HTTP response. Found this bug while integrating nimbus VC which errored when charon sent `text/plain` instead of `application/json`.

category: bug 
ticket: none
  • Loading branch information
xenowits authored Feb 14, 2023
1 parent 34e37ef commit 2403c2a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
4 changes: 1 addition & 3 deletions core/validatorapi/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -883,8 +883,6 @@ func getBeaconNodeAddress(ctx context.Context, eth2Cl eth2wrap.Client) (*url.URL

// writeResponse writes the 200 OK response and json response body.
func writeResponse(ctx context.Context, w http.ResponseWriter, endpoint string, response interface{}) {
w.WriteHeader(http.StatusOK)

if response == nil {
return
}
Expand Down Expand Up @@ -952,8 +950,8 @@ func writeError(ctx context.Context, w http.ResponseWriter, endpoint string, err
log.Error(ctx, "Failed marshalling error response", err2)
}

w.WriteHeader(aerr.StatusCode)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(aerr.StatusCode)

if _, err2 = w.Write(b); err2 != nil {
log.Error(ctx, "Failed writing api error", err2)
Expand Down
27 changes: 27 additions & 0 deletions core/validatorapi/router_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,33 @@ func TestRawRouter(t *testing.T) {
testRawRouter(t, handler, callback)
})

t.Run("valid content type in 2xx response", func(t *testing.T) {
handler := testHandler{}

callback := func(ctx context.Context, baseURL string) {
res, err := http.Get(baseURL + "/eth/v1/node/version")
require.NoError(t, err)
require.Equal(t, res.Header.Get("Content-Type"), "application/json")
}

testRawRouter(t, handler, callback)
})

t.Run("valid content type in non-2xx response", func(t *testing.T) {
handler := testHandler{}

callback := func(ctx context.Context, baseURL string) {
res, err := http.Post(baseURL+"/eth/v1/validator/duties/attester/1", "", strings.NewReader("not json"))
require.NoError(t, err)
require.Equal(t, res.Header.Get("Content-Type"), "application/json")
var errRes errorResponse
require.NoError(t, json.NewDecoder(res.Body).Decode(&errRes))
require.Equal(t, errRes.Code, http.StatusBadRequest)
}

testRawRouter(t, handler, callback)
})

t.Run("client timeout", func(t *testing.T) {
cctx, cancel := context.WithCancel(context.Background())
handler := testHandler{
Expand Down

0 comments on commit 2403c2a

Please sign in to comment.