From 92f87d0607996d5a16f94a308e0bff833d3ba1dc Mon Sep 17 00:00:00 2001 From: Andrei Baibaratsky Date: Mon, 3 May 2021 17:45:47 +0200 Subject: [PATCH] Fix panic on unmarshalling JSON (#68) --- id.go | 4 ++++ id_test.go | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/id.go b/id.go index f1db1a1..eaa6767 100644 --- a/id.go +++ b/id.go @@ -253,6 +253,10 @@ func (id *ID) UnmarshalJSON(b []byte) error { *id = nilID return nil } + // Check the slice length to prevent panic on passing it to UnmarshalText() + if len(b) < 2 { + return ErrInvalidID + } return id.UnmarshalText(b[1 : len(b)-1]) } diff --git a/id_test.go b/id_test.go index 0cbc816..7c26817 100644 --- a/id_test.go +++ b/id_test.go @@ -176,6 +176,10 @@ func TestIDJSONUnmarshalingError(t *testing.T) { if err != ErrInvalidID { t.Errorf("json.Unmarshal() err=%v, want %v", err, ErrInvalidID) } + err = json.Unmarshal([]byte(`{"ID":1}`), &v) + if err != ErrInvalidID { + t.Errorf("json.Unmarshal() err=%v, want %v", err, ErrInvalidID) + } } func TestIDDriverValue(t *testing.T) {