Skip to content

Commit

Permalink
feat: use crypto/rand to generate event bus token (#1149)
Browse files Browse the repository at this point in the history
Signed-off-by: Derek Wang <whynowy@gmail.com>
  • Loading branch information
whynowy authored Mar 31, 2021
1 parent 2df1bdd commit 63d6cd9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
25 changes: 17 additions & 8 deletions controllers/eventbus/installer/nats.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package installer

import (
"context"
"crypto/rand"
"errors"
"fmt"
"math/rand"
"math/big"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -289,7 +290,12 @@ func (i *natsInstaller) createAuthSecrets(ctx context.Context, strategy v1alpha1
log.Infow("created server auth secret", "serverAuthSecretName", expectedSSecret.Name)
return expectedSSecret, nil, nil
case v1alpha1.AuthStrategyToken:
token := generateToken(64)
token, err := generateToken(64)
if err != nil {
i.eventBus.Status.MarkDeployFailed("BuildServerAuthSecretFailed", "Failed to generate auth token")
log.Errorw("error generating auth token", zap.Error(err))
return nil, nil, err
}
serverAuthText := fmt.Sprintf(`authorization {
token: "%s"
}`, token)
Expand Down Expand Up @@ -859,14 +865,17 @@ func (i *natsInstaller) mergeEventBusLabels(given map[string]string) map[string]
}

// generate a random string as token with given length
func generateToken(length int) string {
func generateToken(length int) (string, error) {
seeds := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))
b := make([]byte, length)
for i := range b {
b[i] = seeds[seededRand.Intn(len(seeds))]
result := make([]byte, length)
for i := 0; i < length; i++ {
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(seeds))))
if err != nil {
return "", err
}
result[i] = seeds[num.Int64()]
}
return string(b)
return string(result), nil
}

func serverAuthSecretLabels(given map[string]string) map[string]string {
Expand Down
7 changes: 7 additions & 0 deletions controllers/eventbus/installer/nats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,3 +303,10 @@ func TestBuildConfigMap(t *testing.T) {
}
})
}

func TestGenerateToken(t *testing.T) {
n := 30
token, err := generateToken(n)
assert.NoError(t, err)
assert.Equal(t, len(token), n)
}

0 comments on commit 63d6cd9

Please sign in to comment.