Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

envconf: use crypto/rand for random name generator #439

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions pkg/envconf/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@ limitations under the License.
package envconf

import (
"crypto/rand"
"encoding/hex"
"fmt"
"math/rand"
"regexp"
"time"

log "k8s.io/klog/v2"

Expand Down Expand Up @@ -303,9 +302,13 @@ func RandomName(prefix string, n int) string {
if len(prefix) >= n {
return prefix
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))

p := make([]byte, n)
r.Read(p)
_, err := rand.Read(p)
if err != nil {
log.ErrorS(err, "failed to generate random name. falling back to prefix directly")
return prefix
}
if prefix == "" {
return hex.EncodeToString(p)[:n]
}
Expand Down
12 changes: 12 additions & 0 deletions pkg/envconf/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,15 @@ func TestRandomName(t *testing.T) {
}
})
}

func TestRandomGeneratorIsIndeedGeneratingRandom(t *testing.T) {
randomValues := make(map[string]int)
for attempt := 0; attempt < 10; attempt++ {
randomValues[RandomName("test-randomness", 32)]++
}
for key, val := range randomValues {
if val > 1 {
t.Errorf("random name %q was generated %d times", key, val)
}
}
}