Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: invalid pointer deref in pgotel instrumentation #1990

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion extra/pgotel/pgotel.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package pgotel

import (
"context"
"reflect"
"runtime"
"strings"

Expand Down Expand Up @@ -125,7 +126,7 @@ func (h *TracingHook) AfterQuery(ctx context.Context, evt *pg.QueryEvent) error
span.RecordError(evt.Err)
span.SetStatus(codes.Error, evt.Err.Error())
}
} else if evt.Result != nil {
} else if hasResults(evt) {
numRow := evt.Result.RowsAffected()
if numRow == 0 {
numRow = evt.Result.RowsReturned()
Expand All @@ -138,6 +139,10 @@ func (h *TracingHook) AfterQuery(ctx context.Context, evt *pg.QueryEvent) error
return nil
}

func hasResults(evt *pg.QueryEvent) bool {
return evt.Result != nil && (reflect.ValueOf(evt.Result).Kind() != reflect.Ptr || !reflect.ValueOf(evt.Result).IsNil())
}

func funcFileLine(pkg string) (string, string, int) {
const depth = 16
var pcs [depth]uintptr
Expand Down
62 changes: 62 additions & 0 deletions extra/pgotel/pgotel_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package pgotel

import (
"testing"

"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
)

// mockResult is a mock implementation of the Result interface
type mockResult struct {
model orm.Model
rowsAffected int
rowsReturned int
}

func (m mockResult) Model() orm.Model {
return m.model
}

func (m mockResult) RowsAffected() int {
return m.rowsAffected
}

func (m mockResult) RowsReturned() int {
return m.rowsReturned
}

func TestHasResults(t *testing.T) {
// Define test cases
testCases := []struct {
name string
event *pg.QueryEvent
expected bool
}{
{
name: "Nil Result",
event: &pg.QueryEvent{Result: nil},
expected: false,
},
{
name: "Nil Pointer Result",
event: &pg.QueryEvent{Result: (*mockResult)(nil)},
expected: false,
},
{
name: "Non-Nil Result",
event: &pg.QueryEvent{Result: mockResult{rowsAffected: 1, rowsReturned: 1}},
expected: true,
},
}

// Run test cases
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
result := hasResults(tc.event)
if result != tc.expected {
t.Errorf("hasResults(%v) = %v, want %v", tc.event, result, tc.expected)
}
})
}
}
Loading