From c45f03e144a1bd0420be48c0dde531cbef090b4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E6=9D=A8=E6=96=87?= Date: Thu, 28 Oct 2021 13:06:34 +0800 Subject: [PATCH] fix: allowed ConcatenateJSON with empty input (#138) --- pkg/utils/marshal.go | 8 ++++++++ pkg/utils/marshal_test.go | 32 +++++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/pkg/utils/marshal.go b/pkg/utils/marshal.go index 4f53b4e..8c04588 100644 --- a/pkg/utils/marshal.go +++ b/pkg/utils/marshal.go @@ -29,6 +29,14 @@ func ConcatenateJSON(first, second []byte) ([]byte, error) { if !bytes.HasPrefix(second, []byte{'{'}) { return nil, fmt.Errorf("jws: invalid JSON %s", second) } + // check empty + if len(first) == 2 { + return second, nil + } + if len(second) == 2 { + return first, nil + } + first[len(first)-1] = ',' first = append(first, second[1:]...) return first, nil diff --git a/pkg/utils/marshal_test.go b/pkg/utils/marshal_test.go index f9221f6..bfc8275 100644 --- a/pkg/utils/marshal_test.go +++ b/pkg/utils/marshal_test.go @@ -44,6 +44,36 @@ func TestConcatenateJSON(t *testing.T) { []byte(`{"some": "thing","another": "thing"}`), false, }, + { + "first empty", + args{ + []byte(`{}`), + []byte(`{"some": "thing"}`), + }, + + []byte(`{"some": "thing"}`), + false, + }, + { + "second empty", + args{ + []byte(`{"some": "thing"}`), + []byte(`{}`), + }, + + []byte(`{"some": "thing"}`), + false, + }, + { + "both empty", + args{ + []byte(`{}`), + []byte(`{}`), + }, + + []byte(`{}`), + false, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -53,7 +83,7 @@ func TestConcatenateJSON(t *testing.T) { return } if !bytes.Equal(got, tt.want) { - t.Errorf("ConcatenateJSON() got = %v, want %v", got, tt.want) + t.Errorf("ConcatenateJSON() got = %v, want %v", string(got), tt.want) } }) }