Skip to content

Commit 519f7dc

Browse files
committed
BUG/MINOR: prevent possible panics when generating random string
1 parent 1a4df15 commit 519f7dc

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

misc/misc.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -274,12 +274,26 @@ func HasOSArg(short, long, env string) bool {
274274
}
275275

276276
func RandomString(size int) (string, error) {
277-
b := make([]byte, size)
277+
str, err := randomString(size)
278+
if err != nil {
279+
return "", err
280+
}
281+
for len(str) < size {
282+
str2, _ := randomString(size)
283+
str += str2
284+
}
285+
return str[:size], nil
286+
}
287+
288+
// randomString generates a random string of the recommended size.
289+
// Result is not guaranteed to be correct length.
290+
func randomString(recommendedSize int) (string, error) {
291+
b := make([]byte, recommendedSize+8)
278292
_, err := rand.Read(b)
279293
result := strings.ReplaceAll(base64.URLEncoding.EncodeToString(b), `=`, ``)
280294
result = strings.ReplaceAll(result, `-`, ``)
281295
result = strings.ReplaceAll(result, `_`, ``)
282-
return result[:size], err
296+
return result, err
283297
}
284298

285299
func IsNetworkErr(err error) bool {

misc/misc_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Copyright 2019 HAProxy Technologies
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
//
15+
16+
package misc
17+
18+
import (
19+
"math/rand"
20+
"testing"
21+
)
22+
23+
func TestRandomString(t *testing.T) {
24+
for i := 0; i < 1024; i++ {
25+
size := rand.Intn(512)
26+
str, err := RandomString(size)
27+
if err != nil {
28+
t.Errorf("RandomString returned an error for size %d: %v", size, err)
29+
}
30+
if len(str) != size {
31+
t.Errorf("RandomString returned a string of length %d for size %d", len(str), size)
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)