Skip to content

Commit

Permalink
Don't try to parse error responses with no body (#4307)
Browse files Browse the repository at this point in the history
  • Loading branch information
milosgajdos committed Mar 20, 2024
2 parents 3cb985c + e8820b2 commit 94146f5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
8 changes: 7 additions & 1 deletion internal/client/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,14 @@ func parseHTTPErrorResponse(resp *http.Response) error {
}

statusCode := resp.StatusCode
ctHeader := resp.Header.Get("Content-Type")

// A HEAD request for example validly does not contain any body, while
// still returning a JSON content-type.
if len(body) == 0 {
return makeError(statusCode, "")
}

ctHeader := resp.Header.Get("Content-Type")
if ctHeader == "" {
return makeError(statusCode, string(body))
}
Expand Down
16 changes: 16 additions & 0 deletions internal/client/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,22 @@ func TestHandleHTTPResponseError401WithInvalidBody(t *testing.T) {
}
}

func TestHandleHTTPResponseError401WithNoBody(t *testing.T) {
json := ""
response := &http.Response{
Status: "401 Unauthorized",
StatusCode: 401,
Body: nopCloser{bytes.NewBufferString(json)},
Header: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}},
}
err := HandleHTTPResponseError(response)

expectedMsg := "unauthorized: "
if !strings.Contains(err.Error(), expectedMsg) {
t.Errorf("Expected %q, got: %q", expectedMsg, err.Error())
}
}

func TestHandleHTTPResponseErrorExpectedStatusCode400ValidBody(t *testing.T) {
json := `{"errors":[{"code":"DIGEST_INVALID","message":"provided digest does not match"}]}`
response := &http.Response{
Expand Down

0 comments on commit 94146f5

Please sign in to comment.