Skip to content

Commit

Permalink
Prevent panic in exported.Payload (#22148)
Browse files Browse the repository at this point in the history
Treat a nil response body as no body.
  • Loading branch information
jhendrixMSFT authored Dec 14, 2023
1 parent 8536f47 commit 8867496
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
2 changes: 2 additions & 0 deletions sdk/internal/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

### Bugs Fixed

* Prevent `exported.Payload` from panicking in the rare event `*http.Response.Body` is `nil`.

### Other Changes

## 1.5.1 (2023-12-06)
Expand Down
5 changes: 5 additions & 0 deletions sdk/internal/exported/exported.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ type PayloadOptions struct {
// Subsequent reads will access the cached value.
// Exported as runtime.Payload() WITHOUT the opts parameter.
func Payload(resp *http.Response, opts *PayloadOptions) ([]byte, error) {
if resp.Body == nil {
// this shouldn't happen in real-world scenarios as a
// response with no body should set it to http.NoBody
return nil, nil
}
modifyBytes := func(b []byte) []byte { return b }
if opts != nil && opts.BytesModifier != nil {
modifyBytes = opts.BytesModifier
Expand Down
6 changes: 6 additions & 0 deletions sdk/internal/exported/exported_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ func TestPayloadBytesModifier(t *testing.T) {
require.EqualValues(t, newPayload, string(b))
}

func TestPayloadNilBody(t *testing.T) {
b, err := Payload(&http.Response{}, nil)
require.NoError(t, err)
require.Nil(t, b)
}

func TestNopClosingBytesReader(t *testing.T) {
const val1 = "the data"
ncbr := &nopClosingBytesReader{s: []byte(val1)}
Expand Down

0 comments on commit 8867496

Please sign in to comment.