From 1a8e6b3e966b466e39bf1c2737cd13e9981a5d58 Mon Sep 17 00:00:00 2001 From: "maxim.polezhaev" Date: Tue, 12 Feb 2019 19:19:00 +0700 Subject: [PATCH 1/2] Fix UUID length overflow --- base57.go | 4 +++- shortuuid_test.go | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/base57.go b/base57.go index 2637c7d..5b79657 100644 --- a/base57.go +++ b/base57.go @@ -75,9 +75,11 @@ func (b *base57) stringToNum(s string) (string, error) { x := fmt.Sprintf("%x", n) - // Pad the most significant bit (MSG) with 0 (zero) if the string is too short. if len(x) < 32 { + // Pad the most significant bit (MSG) with 0 (zero) if the string is too short. x = strings.Repeat("0", 32-len(x)) + x + } else if len(x) > 32 { + return "", fmt.Errorf("UUID length overflow for %q", s) } return fmt.Sprintf("%s-%s-%s-%s-%s", x[0:8], x[8:12], x[12:16], x[16:20], x[20:32]), nil diff --git a/shortuuid_test.go b/shortuuid_test.go index 02f5e4f..d6c38d2 100644 --- a/shortuuid_test.go +++ b/shortuuid_test.go @@ -212,6 +212,28 @@ func TestDecoding(t *testing.T) { } } +func TestDecodingErrors(t *testing.T) { + const ( + NotPartOfAlphabetError = "not part of alphabet" + UUIDLengthOverflowError = "UUID length overflow" + ) + var tests = []struct { + shortuuid string + error string + }{ + {"6B8cwPMGnU6qLbRvo7qEZo", UUIDLengthOverflowError}, + {"SiKyfue4VDTKnynXckqVNt", UUIDLengthOverflowError}, + {"122222222222222222222", NotPartOfAlphabetError}, + {"0a6hrgRGNfQ57QMHZdNYAg", NotPartOfAlphabetError}, + } + for _, test := range tests { + _, err := DefaultEncoder.Decode(test.shortuuid) + if err == nil { + t.Errorf("expected %q error for %q", test.error, test.shortuuid) + } + } +} + func TestNewWithAlphabet(t *testing.T) { abc := DefaultAlphabet[:len(DefaultAlphabet)-1] + "=" enc := base57{newAlphabet(abc)} From 8afad847c5c492246a2f6236d05ac85104f63e8d Mon Sep 17 00:00:00 2001 From: "maxim.polezhaev" Date: Tue, 12 Feb 2019 20:07:02 +0700 Subject: [PATCH 2/2] Change test value --- shortuuid_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/shortuuid_test.go b/shortuuid_test.go index d6c38d2..e39edbd 100644 --- a/shortuuid_test.go +++ b/shortuuid_test.go @@ -213,7 +213,7 @@ func TestDecoding(t *testing.T) { } func TestDecodingErrors(t *testing.T) { - const ( + var ( NotPartOfAlphabetError = "not part of alphabet" UUIDLengthOverflowError = "UUID length overflow" ) @@ -223,7 +223,7 @@ func TestDecodingErrors(t *testing.T) { }{ {"6B8cwPMGnU6qLbRvo7qEZo", UUIDLengthOverflowError}, {"SiKyfue4VDTKnynXckqVNt", UUIDLengthOverflowError}, - {"122222222222222222222", NotPartOfAlphabetError}, + {"1lIO022222222222222222", NotPartOfAlphabetError}, {"0a6hrgRGNfQ57QMHZdNYAg", NotPartOfAlphabetError}, } for _, test := range tests {