From 60d9ca2d85a394647336e6393213219ccb33e23a Mon Sep 17 00:00:00 2001 From: Adam Shannon Date: Wed, 6 Apr 2022 12:54:49 -0500 Subject: [PATCH 1/2] otelhttp: nil check wrappedBody.Close --- CHANGELOG.md | 4 ++++ instrumentation/net/http/otelhttp/transport.go | 5 ++++- instrumentation/net/http/otelhttp/transport_test.go | 7 +++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d0f274394..58b89ce17a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Upgraded all dependencies on stable modules from `go.opentelemetry.io/otel` from v1.5.0 to v1.6.1. (#2134) - Upgraded all dependencies on metric modules from `go.opentelemetry.io/otel` from v0.27.0 to v0.28.0. (#1977) +### Fixed + +- otelhttp: Avoid panic by adding nil check to `wrappedBody.Close` (#2164) + ## [1.5.0/0.30.0/0.1.0] - 2022-03-16 ### Added diff --git a/instrumentation/net/http/otelhttp/transport.go b/instrumentation/net/http/otelhttp/transport.go index b436f6a2a9..6c32bb1174 100644 --- a/instrumentation/net/http/otelhttp/transport.go +++ b/instrumentation/net/http/otelhttp/transport.go @@ -186,5 +186,8 @@ func (wb *wrappedBody) Read(b []byte) (int, error) { func (wb *wrappedBody) Close() error { wb.span.End() - return wb.body.Close() + if wb.body != nil { + return wb.body.Close() + } + return nil } diff --git a/instrumentation/net/http/otelhttp/transport_test.go b/instrumentation/net/http/otelhttp/transport_test.go index e155d3e088..8630d06011 100644 --- a/instrumentation/net/http/otelhttp/transport_test.go +++ b/instrumentation/net/http/otelhttp/transport_test.go @@ -281,6 +281,13 @@ func TestWrappedBodyClose(t *testing.T) { s.assert(t, true, nil, codes.Unset, "") } +func TestWrappedBodyClosePanic(t *testing.T) { + s := new(span) + var body io.ReadCloser + wb := newWrappedBody(s, body) + assert.NoError(t, wb.Close()) +} + func TestWrappedBodyCloseError(t *testing.T) { s := new(span) expectedErr := errors.New("test") From c30f5a26a99cf6eb9fa879bcac76a3db73e37dc8 Mon Sep 17 00:00:00 2001 From: Adam Shannon Date: Thu, 7 Apr 2022 11:08:27 -0700 Subject: [PATCH 2/2] Update instrumentation/net/http/otelhttp/transport_test.go Co-authored-by: Tyler Yahn --- instrumentation/net/http/otelhttp/transport_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/instrumentation/net/http/otelhttp/transport_test.go b/instrumentation/net/http/otelhttp/transport_test.go index 8630d06011..af532fa88e 100644 --- a/instrumentation/net/http/otelhttp/transport_test.go +++ b/instrumentation/net/http/otelhttp/transport_test.go @@ -285,7 +285,7 @@ func TestWrappedBodyClosePanic(t *testing.T) { s := new(span) var body io.ReadCloser wb := newWrappedBody(s, body) - assert.NoError(t, wb.Close()) + assert.NotPanics(t, func() { wb.Close() }, "nil body should not panic on close") } func TestWrappedBodyCloseError(t *testing.T) {