From 2403c2a265c198024c196704d9f14db858de097b Mon Sep 17 00:00:00 2001 From: Abhishek Kumar <43061995+xenowits@users.noreply.github.com> Date: Tue, 14 Feb 2023 16:48:02 +0530 Subject: [PATCH] validatorapi: fix content type in http response (#1803) 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 --- core/validatorapi/router.go | 4 +--- core/validatorapi/router_internal_test.go | 27 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/core/validatorapi/router.go b/core/validatorapi/router.go index d1331e40f..18d2e5096 100644 --- a/core/validatorapi/router.go +++ b/core/validatorapi/router.go @@ -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 } @@ -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) diff --git a/core/validatorapi/router_internal_test.go b/core/validatorapi/router_internal_test.go index 22b44d34b..1e304b73d 100644 --- a/core/validatorapi/router_internal_test.go +++ b/core/validatorapi/router_internal_test.go @@ -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{