Skip to content

Commit 34223b9

Browse files
committed
Add secure string generator
1 parent 1d9e64b commit 34223b9

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

pkg/controller/postgresuser/postgresuser_controller.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,11 @@ func (r *ReconcilePostgresUser) Reconcile(request reconcile.Request) (reconcile.
162162

163163
// Creation logic
164164
var role, login string
165-
password := utils.GetRandomString(15)
165+
password, err := utils.GetSecureRandomString(15)
166+
167+
if err != nil {
168+
return r.requeue(instance, err)
169+
}
166170

167171
if instance.Status.PostgresRole == "" {
168172
// We need to get the Postgres CR to get the group role name
@@ -172,6 +176,7 @@ func (r *ReconcilePostgresUser) Reconcile(request reconcile.Request) (reconcile.
172176
}
173177
// Create user role
174178
suffix := utils.GetRandomString(6)
179+
175180
role = fmt.Sprintf("%s-%s", instance.Spec.Role, suffix)
176181
login, err = r.pg.CreateUserRole(role, password)
177182
if err != nil {

pkg/utils/random.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package utils
22

3+
import cryptorand "crypto/rand"
34
import "math/rand"
45

56
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
@@ -11,3 +12,17 @@ func GetRandomString(length int) string {
1112
}
1213
return string(b)
1314
}
15+
16+
// If the secure random number generator malfunctions it will return an error
17+
func GetSecureRandomString(length int) (string, error) {
18+
b := make([]rune, length)
19+
for i := 0; i < length; i++ {
20+
num, err := cryptorand.Int(cryptorand.Reader, big.NewInt(int64(len(letterRunes))))
21+
if err != nil {
22+
return "", err
23+
}
24+
b[i] = letterRunes[num.Int64()]
25+
}
26+
27+
return string(b), nil
28+
}

0 commit comments

Comments
 (0)