diff --git a/pkg/envconf/config.go b/pkg/envconf/config.go index 6d497b38..ec728334 100644 --- a/pkg/envconf/config.go +++ b/pkg/envconf/config.go @@ -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" @@ -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] } diff --git a/pkg/envconf/config_test.go b/pkg/envconf/config_test.go index 5be48838..449b1aaa 100644 --- a/pkg/envconf/config_test.go +++ b/pkg/envconf/config_test.go @@ -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) + } + } +}