Skip to content

Commit 84cd50a

Browse files
authored
Fix nil pointer dereferences from status.FromProto(nil) (#1211)
1 parent fc5d355 commit 84cd50a

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

status/status.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,16 +71,25 @@ type Status struct {
7171

7272
// Code returns the status code contained in s.
7373
func (s *Status) Code() codes.Code {
74+
if s == nil || s.s == nil {
75+
return codes.OK
76+
}
7477
return codes.Code(s.s.Code)
7578
}
7679

7780
// Message returns the message contained in s.
7881
func (s *Status) Message() string {
82+
if s == nil || s.s == nil {
83+
return ""
84+
}
7985
return s.s.Message
8086
}
8187

8288
// Proto returns s's status as an spb.Status proto message.
8389
func (s *Status) Proto() *spb.Status {
90+
if s == nil {
91+
return nil
92+
}
8493
return proto.Clone(s.s).(*spb.Status)
8594
}
8695

status/status_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,24 @@ func TestFromToProto(t *testing.T) {
6565
}
6666
}
6767

68+
func TestFromNilProto(t *testing.T) {
69+
tests := []*Status{nil, FromProto(nil)}
70+
for _, s := range tests {
71+
if c := s.Code(); c != codes.OK {
72+
t.Errorf("s: %v - Expected s.Code() = OK; got %v", s, c)
73+
}
74+
if m := s.Message(); m != "" {
75+
t.Errorf("s: %v - Expected s.Message() = \"\"; got %q", s, m)
76+
}
77+
if p := s.Proto(); p != nil {
78+
t.Errorf("s: %v - Expected s.Proto() = nil; got %q", s, p)
79+
}
80+
if e := s.Err(); e != nil {
81+
t.Errorf("s: %v - Expected s.Err() = nil; got %v", s, e)
82+
}
83+
}
84+
}
85+
6886
func TestError(t *testing.T) {
6987
err := Error(codes.Internal, "test description")
7088
if got, want := err.Error(), "rpc error: code = Internal desc = test description"; got != want {

0 commit comments

Comments
 (0)